diff --git a/CHANGELOG.md b/CHANGELOG.md
index 403ee08..1e931ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,10 +8,134 @@ API between minor releases.
### Added
+- `PlaDocument.ReadEmbeddedLibraryCatalog()` returns verified archived GSM library parts with their original
+ bytes, saved names, main and revision GUIDs, and the offsets of unreadable asset blocks.
+- Embedded library reading follows the decoded asset pool across QuickLZ frame boundaries, including asset
+ records whose headers are stored inside compressed frames.
+- Doors with verified library descriptors expose the main and revision GUIDs recorded on the placed element.
+- Doors on supported straight walls expose their reference line position and nominal sill elevations in project
+ and host-story coordinates in the core reader, CLI and IOScene.
+- Doors expose the wall-hole width and height from verified placed GDL parameter tables.
+
+- `PlaSceneReader.Read()` maps Archicad elements, levels, supported properties and verified slab meshes into IOScene.
+ Straight-edged slabs can have saved holes, supported through cuts from rectangular columns or separate Opening
+ elements, and multiple connected parts.
+- `PlaElement.WallExtrusion` and the scene adapter expose supported straight vertical wall solids and their net
+ volumes, including walls with straight-edged complex profiles and verified zone-area references.
+- Rectangular walls with verified simple Door openings expose closed solids with the through cuts, including
+ supported walls saved without a cached plan outline.
+- Straight walls with an empty plan cache can expose element boxes from their verified inline contour or placed
+ profile. Verified inline contours and reciprocal annotations also support elevations at structural junctions.
+- Supported straight composite walls expose schedule elevations after composite slabs cut through all wall skins,
+ including independently verified cuts at opposite ends. Reciprocal slab labels preserve eligible cutting bands.
+- Supported walls expose schedule elevations after a combination of straight-edged slab cuts, including
+ reciprocal slab subtraction links with vertical extrusion upwards or downwards.
+- Wall end coverage now accounts for verified oblique wall joins, collinear butt joins with different face
+ offsets, and acyclic slab subtractions where each operator cuts the wall in the same direction.
+- Wall elevation checks account for reciprocal Openings located between the wall ends and verify whether
+ openings in a cutting slab reach the cutting band, including supported centered circular openings.
+ Standalone slab labels and typed directory label references can also preserve that band.
+- Walls with verified rectangular door openings can retain their schedule elevations where an intact section
+ reaches both end planes. This includes supported swing doors with and without transoms whose placed GDL parameters
+ confirm the rectangular cut. At supported slab junctions the reader checks the slab contour within the wall strip.
+- Wall elevation checks account for the axial reach of verified beam joints and circular column contacts
+ outside the wall's height range. A verified full cap cut can be combined with a separate slab cut at the opposite end.
+- For supported basic walls with slab cuts at opposite ends, verified rectangular beams can preserve slab
+ coverage where they replace a cutting skin. The reader checks for a remaining wall section beyond the cut.
+- `PlaElement.ColumnExtrusion` and the scene adapter expose supported vertical column solids and their net
+ volumes, including rectangular sections with planar caps and straight-edged profiles split into spans by
+ verified full-section beam cuts.
+- `PlaElement.ColumnCutMesh` and the scene adapter expose supported partial cuts of vertical profiled columns
+ by horizontal or inclined beams, including evaluated elevations and net volume.
+- Column geometry accounts for verified right-angle beam T-junctions, including matching cutters and repeated
+ references to the same end trim.
+- Column cutters can retain their sweep through verified interior beam collisions, angled T-junctions and
+ symmetric miters that clear the column.
+- Columns can retain a verified solid at contacts with weaker composite walls whose skins cannot wrap them.
+- Rotated rectangular columns can retain their solid when validated joined beam caps clear the actual footprint.
+- Rectangular columns support partial cuts by verified coextensive beams where the stronger rectangular section contains the other cutters.
+- Column cuts include the joined caps of verified equal-priority rectangular beams that meet at an angled miter.
+- Columns preserve supported geometry with reciprocal labels, angular dimension anchors or verified beam crossings
+ away from the cutter's caps. Beams also support verified angular dimension anchors.
+- Profiled columns expose element boxes from their saved cap-axis elevations and profile outline, including
+ the plan extension of a centered crosshair symbol.
+- The core reader and scene adapter reconstruct circular columns with horizontal caps. They expose analytic
+ and Archicad listing quantities. The mesh preserves the analytic bounds with a bounded sagitta.
+- `PlaDocument.ReadStories()` and `plaio stories` expose project story indices, saved names and elevations.
+- `PlaDocument.ReadLayers()` and `plaio layers` expose layer GUIDs, indices, saved names and intersection groups.
+- `PlaDocument.ReadMaterialCatalog()` and `plaio materials` expose building materials, connection priorities and ordered
+ composite skins. Supported walls and slabs expose the corresponding material or composite index.
+- `PlaDocument.ReadProfileCatalog()` and `plaio profiles` expose complex profile definitions, enabled element types,
+ section dimensions, stretch limits, named offset modifiers with their default offsets and saved material fills.
+- `PlaDocument.ReadClassificationSystems()` and `plaio classifications` expose the saved classification systems and
+ item hierarchy. `PlaElement.Classifications` and `plaio elements` expose each recognized element's saved assignments.
+- `PlaDocument.ReadPropertyCatalog()` and `plaio properties` expose user-defined property groups, definition types,
+ classification availability, enumeration choices and supported defaults.
+ `PlaElement.PropertyOverrides` exposes supported overrides linked to recognized model elements.
+- `PlaDocument.ReadLayoutBook()` and `plaio layouts` expose the saved layout book, layouts in navigator order,
+ placed drawing entries, source GUIDs and paths, layout databases, assigned masters and paper sizes.
+- Layout entries expose issued revisions in saved order, transmittal date and issuer, and verified open transmittal links.
+- Open layout revisions expose saved IDs and supported automatic numbering, including transmittal overrides.
+- Object membership follows the declared length of the database record, including the longer record in older archives.
+ The supported older Object format also exposes its Element ID, layer index and home story index.
+- Standalone QuickLZ record decoding reads consecutive frames with short or long size headers.
+- `PlaElement.BoundingBox` and `plaio elements` expose project-coordinate 3D extents for supported walls, slabs,
+ zones, vertical columns and horizontal beams, including supported beam junctions and column contacts.
+- Supported horizontal beams expose their evaluated top and bottom elevations in both reference systems,
+ including complex profiles and verified junctions that preserve a transverse section.
+ Straight beams with supported inclined axes or oblique end planes can also expose 3D bounds and elevations.
+ Horizontally curved beams with supported profiles expose 3D bounds and elevations at verified end connections
+ and slab cuts that preserve their extrema.
+ `PlaElement.BeamNetVolume` gives the volume of supported horizontal rectangular beams and inclined prisms.
+ It reports zero when the verified intact portions of higher-priority rectangular beams cover the whole
+ horizontal profiled beam, including supported end extensions.
+- `PlaElement.BeamReferenceAxis` exposes the saved endpoints, inclination and length of straight and horizontally curved beams.
+- `PlaElement.WallReferencePlan` exposes the directed reference line and face offsets for supported straight walls.
+- `PlaElement.WallProfile` exposes the profile attribute index and saved material sections, including holes and circular
+ edges, for supported complex-profile walls.
+- `PlaElement.MemberProfile` exposes the saved material cross-sections and profile attribute index of supported
+ complex-profile beams and columns.
+ A verified inline rectangle also supplies extents and end elevations for supported walls without junctions or a saved 3D box.
+- `PlaElement.SlabGeometry` exposes slab outlines with holes, circular edges, analytic areas and perimeters, and the volume
+ of verified straight-edged extrusions.
+- Slab geometry exposes both gross face areas after verified Opening cuts and deducts their volume from
+ supported slab prisms.
+- Slab volume accounts for verified intersections with vertical rectangular columns and the priorities
+ of the affected slab skins.
+- Slab volume also accounts for verified cuts by straight profiled walls, including cuts that apply to
+ only some slab skins.
+- `PlaElement` exposes Opening shapes, profile dimensions, associated walls and slabs, and verified cut targets.
+ Supported vertical wall openings also have elevations relative to project zero and the home story.
+- `PlaElement` exposes nominal Door dimensions, sill height relative to its saved anchor, and the host wall GUID when both records confirm the relationship.
+- Supported slab openings expose elevations in both reference systems after through and one-sided cuts, including
+ overlapping limited-depth cuts that fully cover another opening's profile.
+- `PlaElement.OpeningGeometry` exposes project XY opening profiles, verified cut intervals by slab and cut volume.
+
+- `PlaDocument.ReadObjectClasses()` resolves file-local class numbers to stored GUIDs and recognizes API type names
+ by GUID. `PlaDocument.ReadElements()` and `plaio elements` expose recognized model elements, their GUIDs and basic
+ parameters such as Element ID and constant-width wall thickness. Objects are selected by the saved database element
+ and grid GUID lists. Element IDs are read from Raw, ZeroMask and standalone QuickLZ records. Zones get their IDs
+ from the linked zone stamp. Elements also carry the effective layer and home story, with names from the saved
+ layer and story tables. Slabs and zones expose bottom and top elevations relative to the home story and project zero.
+ Walls and columns expose the index of the story to which their top is linked. Supported walls and vertical columns
+ expose bottom and top elevations using saved story links, profiles, cut planes and material priorities. Supported
+ rectangular slab junctions can change wall and column end elevations. Isolated higher-priority rectangular beams
+ use their saved section and rotation to cut column ends. Supported perpendicular wall junctions preserve elevations
+ when a remaining section reaches both end planes.
+ Supported sets of horizontal rectangular beams can cut a column together. Verified collinear wall junctions and
+ bounded contacts with beams, columns and slabs can preserve elevations when some wall section reaches both ends.
+ Supported perpendicular beam joins preserve known cutter coverage beyond the junction and at verified T-junctions.
+ A supported horizontal beam or a straight-edged slab outline can define a basic wall's cut end.
+ Verified T-junctions can cut a column with one beam. A composite slab can cut a basic wall at the boundary
+ of its cutting skins.
+ Verified adjacent walls and beams can participate in composite-slab wall cuts when the joined footprint stays covered.
+ Several supported rectangular beams, including verified right-angle beam joins, can extend the same composite-slab cut.
+ See `docs/public-api.md` for the supported layouts.
+
- The `PlaIO.Scene` adapter project (namespace `PlaIO.Scene`): `PlaSceneReader.Read(path)` turns a `.pla` or `.pln`
container into an `IOScene` `SceneDocument` — one model per file with the frozen `Key` derivation (the
- `PlaSceneOptions.ModelKey`, else the file name), no elements yet (the container reader does not decode element
- contents), and the `container-only` diagnostic. The project is `IsPackable=false` and is not published; it ships on a
+ `PlaSceneOptions.ModelKey`, else the file name), model metadata, and the `container-only` diagnostic.
+ The project is `IsPackable=false` and is not published; it ships on a
`PlaIO` release tag when the reader decodes elements and geometry. See `docs/scene.md`.
- `PlaDocument.ReadPayload` decodes mode 2 (LZ) payloads. A payload may start with a 9-byte stream header with a
diff --git a/Directory.Packages.props b/Directory.Packages.props
index fb361bf..d29ee97 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -7,9 +7,8 @@
-
-
+
+
diff --git a/README.md b/README.md
index d84695a..db367f1 100644
--- a/README.md
+++ b/README.md
@@ -5,11 +5,9 @@
PlaIO is a pure managed .NET library and command line tool that reads the container of Archicad project files (`.pla`,
`.pln`) and the cover image of BIMx files (`.bimx`) directly from disk, without Archicad and without native dependencies.
-In the [IOExtend](https://github.com/IOExtend) ecosystem PlaIO is a leaf engine: it depends on no other IOExtend package
-and on no scene type. The `PlaIO.Scene` adapter in this repository turns an Archicad container into an `IOScene` scene
-document for [IOViewer](https://github.com/IOExtend/IOViewer) and coordination tools; while the reader decodes only the
-container, the scene holds one model and no elements, and the adapter is not published yet — it ships on a `PlaIO`
-release tag when the reader decodes elements and geometry (see [the scene adapter](docs/scene.md)).
+In the [IOExtend](https://github.com/IOExtend) ecosystem PlaIO is a leaf engine with no dependency on scene types.
+The `PlaIO.Scene` adapter maps decoded elements, storeys, grids, properties and supported slab meshes into an `IOScene`
+document for [IOViewer](https://github.com/IOExtend/IOViewer) and coordination tools. See [the scene adapter](docs/scene.md).
## What it does
@@ -19,6 +17,12 @@ release tag when the reader decodes elements and geometry (see [the scene adapte
- Decodes block payloads stored raw (mode 0), with zero masks (mode 1), or with LZ compression (mode 2).
Some mode 1 blocks in real files do not decode (see [Limitations](#limitations)).
- Searches raw blocks for object directories (30-byte records of class number, position, count and object GUID).
+- Reads the object class GUID table and lists recognized model elements with their GUIDs, type and basic parameters
+ where available. See [element coverage](docs/public-api.md#model-elements).
+- Lists project stories with their signed indices, saved names and elevations in metres.
+- Lists supported straight and circular grid axes with their saved labels and geometry in project coordinates.
+- Lists layer attributes with their GUIDs, project-local indices, saved names and intersection groups.
+- Lists complex profile definitions with their GUIDs, indices, names, enabled element types and saved sections.
- Reads the PNG cover image at the start of a `.bimx` file and reports where the rest of the content begins.
## Install
@@ -48,6 +52,14 @@ Windows-only APIs and supports Windows, Linux and macOS. Tests currently run on
plaio info # kind, length, header fields, block counts (or the .bimx cover bounds)
plaio blocks # one tab-separated line per indexed block (.pla, .pln)
plaio directory [--out ] # object directories found in raw blocks (.pla, .pln)
+plaio elements # recognized elements as JSON (.pla, .pln)
+plaio stories # saved project stories as JSON (.pla, .pln)
+plaio grids # supported grid axes as JSON (.pla, .pln)
+plaio layers # saved project layers as JSON (.pla, .pln)
+plaio profiles # complex profile definitions as JSON (.pla, .pln)
+plaio classifications # classification systems and items as JSON (.pla, .pln)
+plaio properties # user-defined property catalog as JSON (.pla, .pln)
+plaio layouts # layout book and drawing entries as JSON (.pla, .pln)
plaio --help
plaio --version
```
@@ -66,7 +78,8 @@ phase records abutting overlapping duplicates`. With `--out` it also writes ever
written under a temporary name next to the target and then moved over it, so a failed write leaves no truncated file. The
input file name is not written into the JSON.
-`blocks` and `directory` work on `.pla` and `.pln` files only. Messages go to standard error, prefixed with `plaio: `.
+`blocks`, `directory`, `elements`, `stories`, `grids`, `layers`, `materials`, `profiles`, `classifications`, `properties` and `layouts` work on `.pla`
+and `.pln` files. Messages go to standard error, prefixed with `plaio: `.
### Exit codes
diff --git a/docs/cli.md b/docs/cli.md
index cc1be94..28b1111 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -10,6 +10,15 @@ standard error and tells success from failure by its exit code. It uses only the
| `plaio info ` | `.pla`, `.pln`, `.bimx` | `key: value` lines: kind, length, header fields and block counts, or the cover bounds of a `.bimx` file. |
| `plaio blocks ` | `.pla`, `.pln` | A tab-separated header line, then one line per indexed block. |
| `plaio directory [--out ]` | `.pla`, `.pln` | A tab-separated header line, then one line per object directory found. With `--out`, also every record as JSON. |
+| `plaio elements ` | `.pla`, `.pln` | JSON with the recognized elements and their available parameters. |
+| `plaio stories ` | `.pla`, `.pln` | JSON with the saved project stories. |
+| `plaio grids ` | `.pla`, `.pln` | JSON with supported straight and circular grid axes. |
+| `plaio layers ` | `.pla`, `.pln` | JSON with the saved project layer attributes. |
+| `plaio materials ` | `.pla`, `.pln` | JSON with building materials and composite definitions. |
+| `plaio profiles ` | `.pla`, `.pln` | JSON with complex profile definitions. |
+| `plaio classifications ` | `.pla`, `.pln` | JSON with classification systems and item trees. |
+| `plaio properties ` | `.pla`, `.pln` | JSON with user-defined property groups and definitions. |
+| `plaio layouts ` | `.pla`, `.pln` | JSON with the layout book and placed drawings. |
| `plaio --help`, `plaio -h` | | The usage text, on standard output. |
| `plaio --version` | | `plaio `, for example `plaio 0.1.0`. |
@@ -37,11 +46,115 @@ The limits are fixed; the tool has no option to change them.
| Mode 2 (LZ) payloads | Listed by `blocks`. The CLI `directory` command reads raw blocks only. |
| Object directories | Searched in raw (mode 0) blocks of at least 1920 bytes, at most one per block. A directory needs at least 64 records whose extents mostly abut. The run that is reported is an estimate and can be shorter than the real directory. |
-The CLI reports `pos`, `count` and class numbers as stored and does not read object contents. The library exposes
-extent reads through `PlaDocument.OpenStream()`.
+The `directory` command reports `pos`, `count` and class numbers as stored. The library exposes extent reads
+through `PlaDocument.OpenStream()`.
## Output format
+### elements
+
+The JSON object has an `elements` array. Each entry contains `guid`, `type`, `elementId`, `layerIndex`, `layerName`,
+`homeStoryIndex`, `homeStoryName`, `topLinkedStoryIndex`, `wallThickness`, `wallReferenceLineChordLength`, `bottomElevationToProjectZero`,
+`topElevationToProjectZero`, `bottomElevationToHomeStory`, `topElevationToHomeStory`, `boundingBox`, `wallReferencePlan`,
+`wallProfile`, `memberProfile`, `slabGeometry`, `beamReferenceAxis`, `beamNetVolume`,
+`buildingMaterialIndex`, `compositeIndex`, `classifications`, `propertyOverrides`, `hostGuid`, `doorDimensions`, `openingCutElementGuids`, `openingProfile`
+and `openingGeometry`. The fields after
+`type` can be null. A box contains `xMin`, `yMin`, `zMin`, `xMax`, `yMax` and `zMax` in project coordinates and metres.
+`beamNetVolume` is the verified net volume in cubic metres for a supported rectangular beam.
+The wall reference plan has project XY points `start` and `end`, and signed face offsets `outsideOffset` and
+`insideOffset` in metres to the right of the directed line. It describes the wall before junction cleanup.
+`wallProfile` and `memberProfile` have a project-local `profileIndex` and `components` in saved drawing order. Each component has
+`buildingMaterialIndex`, nullable `function`, `crossSectionArea` in square metres, local `rings` with `u` and `z`
+coordinates in metres, and nullable `arcs`.
+Slab geometry contains `rings` of XY points, `bottom`, `top` and the analytic `outlineArea`.
+For profiles and slabs, the nullable `arcs` array contains `ringIndex`, `startVertexIndex` and `sweepRadians`. Indices are zero-based.
+An arc ends at the next vertex of the ring, wrapping to the first vertex when needed. A positive sweep turns counterclockwise.
+`floorPlanPerimeter` measures all saved boundaries and `floorPlanHolesPerimeter` measures the saved hole boundaries.
+Both use metres.
+Nullable `topAreaWithOpenings`
+and `bottomAreaWithOpenings` give the horizontal face areas after verified Opening cuts. The nullable `volume`
+gives the verified solid volume. Units are metres, square metres and cubic metres.
+The Opening profile contains `shape`, `width` and `height` in metres. `hostGuid` and `openingCutElementGuids` report
+the associated element and verified cut targets for supported Openings. For Doors, `hostGuid` gives the verified
+wall and `doorDimensions` contains the saved nominal `width`, `height` and optional `sillHeightFromAnchor` in metres.
+For supported straight hosts, `doorPlacement` gives the reference line point in project XY, the distance
+from the wall's directed start, and the nominal sill elevation in project and host-story coordinates.
+When the saved Door and its library descriptor confirm the link, `libraryPartReference` gives the main and revision GUIDs.
+`doorWallHoleDimensions` contains the saved GDL wall-hole `width` and `height` in metres when the linked
+instance parameter table can be verified.
+For supported horizontal Openings, `openingGeometry` gives the project XY `origin` and nullable `rings` of the profile.
+It also gives nullable `cuts` with a `slabGuid`, `bottom` and `top` in project coordinates, and nullable `cutVolume` in cubic metres.
+`classifications` contains `systemGuid` and `itemGuid` pairs. An empty list means the element has no assignments
+in the readable systems. Null means the classification catalog is unavailable.
+`propertyOverrides` contains explicit saved overrides, each with a `definitionGuid` and a nullable `value` object.
+The value uses the same `status` and `value` fields as the property default. The list is null when no override
+is recovered for the element.
+See the [supported types and parameters](public-api.md#model-elements).
+
+### stories
+
+The JSON object has a `stories` array, sorted by ascending `index`. Each story contains the signed `index`, saved
+`name` and nullable `elevationToProjectZero` in metres. An empty saved name is written as an empty string.
+
+### grids
+
+The JSON object has a `grids` array in GUID order. Each entry contains `guid`, the saved start-marker `label`,
+`start` and `end` XY points in project metres, and nullable `homeStoryIndex`. When available, the entry includes
+`elevationToHomeStory` and `elevationToProjectZero` in metres. Circular axes include an `arc`
+with `center`, `radius` in metres and `sweepRadians` counterclockwise. Axes displayed as segments on the floor
+plan include `floorPlanSegmentLength` in metres. Axes whose lines are hidden on the floor plan include
+`isFloorPlanLineHidden`. The endpoints describe the full reference axis. See the [grid API](public-api.md#model-elements).
+
+### layers
+
+The JSON object has a `layers` array sorted by `index`. Each entry contains `guid`, `index`, nullable `name` and
+nullable `intersectionGroup`. A stored intersection group of zero is preserved.
+
+### materials
+
+The JSON object contains `buildingMaterials` and `composites` arrays sorted by their project-local `index`.
+Materials have `guid`, `index`, `name`, `id` and `connectionPriority`. Composites have `guid`, `index`, `name`,
+`totalThickness`, `useWith` and an ordered `skins` array. Each skin has `buildingMaterialIndex`, `thickness`,
+`isCore` and `isFinish`. Thicknesses are in metres.
+
+### profiles
+
+The JSON object has a `profiles` array sorted by `index`. Each definition has `guid`, `index`, `name`, `useWith`,
+`width`, `height`, `hasCoreSkin` and `components`. Width and height measure the saved local section, in metres.
+The optional `widthStretch` and `heightStretch` objects carry `enabled`, `start`, `end` and `minimumSize`.
+`modifiers` supplies the saved name and the instance and definition GUIDs for each verified named offset modifier.
+Its nullable `defaultValue` gives the signed offset in metres on the undeformed catalog section.
+The section uses the same component fields as placed profiles in `elements`. A `buildingMaterialIndex` of zero
+denotes a fill without an assigned building material. Unsupported usage flags or section layouts yield null values
+for the affected fields.
+
+### classifications
+
+The JSON object has a `classificationSystems` array sorted by GUID. Each system contains `guid`, `name`,
+`description`, `source`, `version`, nullable ISO date `date` and `items`. Items appear in depth-first order
+with siblings in saved order. Each item contains `guid`, `parentGuid`, `id`, `name` and `description`.
+The `parentGuid` is null for top-level items.
+
+### properties
+
+The JSON object has `groups` and `definitions` arrays sorted by GUID. Each group has a `guid` and `name`.
+A definition has a `guid`, `groupGuid`, `name`, `description`, `dataType` and `availableClassificationItemGuids`.
+An enumeration's `choices` give each saved choice's `guid` and `displayValue` in display order.
+
+The nullable `defaultValue` has a `status` of `normal`, `userUndefined` or `expression`. A verified normal default
+has a typed JSON `value`. Numeric measurements are in SI units. A single enumeration default references the
+choice GUID. See [User-defined properties](public-api.md#user-defined-properties) for available fields.
+
+### layouts
+
+The JSON object contains a nullable `layoutBook` with the root `guid` and an ordered `items` array. Each item
+has a `guid`, `parentGuid`, `type`, nullable `name`, `id`, `sourceGuid`, `drawingSourcePath`, `databaseGuid`,
+`masterLayoutGuid` and `paperSize`. An available `paperSize` has `width` and `height` in metres.
+The nullable `revision` contains the current revision IDs, status flags, `issuedRevisions` in saved order and
+the linked `openTransmittal` when available. A transmittal's `overridesRevisionIds` reports whether it imposes its
+own ID on every included layout. Its `issuedAtUtc` uses ISO 8601.
+See the [layout book API](public-api.md#layout-book).
+
### info
For a `.pla` or `.pln` file:
diff --git a/docs/dependencies.md b/docs/dependencies.md
index e3a1a3d..c0978b7 100644
--- a/docs/dependencies.md
+++ b/docs/dependencies.md
@@ -10,8 +10,8 @@ None. The library and the command line tool use only the .NET base class library
third-party code with them. No engine package depends on another IOExtend package.
The `PlaIO.Scene` adapter (not published yet) depends on [`IOScene`](https://github.com/IOExtend/IOScene)
-`[0.1.1, 0.2.0-0.0)`: any patch of the IOScene 0.1 line, no preview of the next (breaking) minor. `IOScene` itself has
-no dependencies.
+`[0.1.2, 0.2.0-0.0)`. Version 0.1.2 adds the grid paths used by the adapter for circular axes. The range excludes
+previews of the next minor. `IOScene` itself has no dependencies.
## Build-time packages
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 64e98f5..6a110b9 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -16,9 +16,12 @@ plaio info project.pln
```sh
plaio blocks project.pln
plaio directory project.pln --out directories.json
+plaio stories project.pln
+plaio layers project.pln
+plaio profiles project.pln
```
-`blocks` lists every indexed block as tab-separated lines. `directory` prints one summary line per object directory found, and with `--out` writes all records as JSON. Both work on `.pla` and `.pln` files only.
+`blocks` lists indexed blocks as tab-separated lines. `directory` prints one summary line per detected object directory, and with `--out` writes its records as JSON. `elements` writes recognized elements and available parameters as JSON. `stories`, `layers` and `profiles` write their project catalogs as JSON. These commands work on `.pla` and `.pln` files.
Run `plaio --help` for the usage. The output columns, the JSON shape and the exit codes are described in [Command line and exit codes](cli.md).
diff --git a/docs/index.md b/docs/index.md
index 1cd0954..f2b0df2 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -12,7 +12,7 @@ PlaIO is a .NET library and command line tool that reads the container structure
- Searches raw blocks for object directories and returns their records as stored (class number, position, count, GUID).
- Reads the PNG cover image of a `.bimx` file.
-PlaIO reports the structure of a file; it does not read Archicad elements, class names or object contents, and it does not write files. The library targets .NET 8 and .NET 10, uses managed code only, has no package dependencies and supports Windows, Linux and macOS.
+PlaIO reports the structure of a file and reads recognized Archicad elements with their GUIDs, types and available basic parameters. PlaIO reads Archicad files without modifying them. The library targets .NET 8 and .NET 10, uses managed code only, has no package dependencies and supports Windows, Linux and macOS.
## Where to go next
diff --git a/docs/public-api.md b/docs/public-api.md
index 072500d..72c4b5b 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -40,19 +40,496 @@ the 0.1.0 surface are unchanged: the options come through added overloads (`Open
| `PlaDocument.Blocks` | The block index in file order, found by scanning from offset 32. No on-disk block map is known, so completeness is not claimed. The scan can take a byte run for a block header, so the index may contain false entries. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. |
| `PlaDocument.ReadPayload(PlaBlock block)` | The decoded payload of a block of this document. Decodes all three storage modes: raw (mode 0), zero masks (mode 1) and the LZ token stream (mode 2). A mode 2 payload may start with a 9-byte stream header with a 0x46 or 0x47 marker and matching packed and unpacked sizes. The token stream produces the block's declared unpacked size — some blocks declare a buffer larger than the stream produces, the tail of the buffer stays zero — and may reference the output of any preceding block, so the payload is produced by decoding every preceding block of the file in order into one global window; the cost of the call grows with the size of the file. Preceding blocks that do not decode (false entries of the scan) are skipped and leave the window unchanged. Throws `InvalidDataException` when a back-reference reaches beyond the decoded stream or the file is cut short, and `ArgumentException` when the block is not from this document. |
| `PlaDocument.FindDirectories()` | Searches every raw (mode 0) block large enough for 64 records of 30 bytes for an object directory, at most one per block. Recomputed on each call; mode 1 payloads are not searched. |
+| `PlaDocument.ReadEmbeddedLibraryCatalog()` | Reads supported embedded GSM library parts in file order from the archive asset class. |
+| `PlaEmbeddedLibraryCatalog`, `PlaEmbeddedLibraryPart` | Each part exposes the archive asset GUID, saved file name, main GUID, revision GUID and original GSM bytes. Physical offsets of asset blocks or pools with unreadable data are reported separately. |
| `PlaDocument.OpenStream()` | The document's decoded global stream (`PlaStream`): every block's payload decoded in block order. Blocks that fail to decode are skipped and mark the remaining offsets as unreliable. The stream holds the decoded bytes in memory and can outlive the document. |
| `PlaDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. |
| `FdbHeader` | `Size` (64), `LayoutVersion` (u16 at offset 8), `FormatVersion` (u16 at offset 10), `Field12` (u32 at offset 12; meaning not documented), `Raw` (the first min(64, file length) bytes; bytes 32..63 overlap the first block). |
| `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200): an LZ token stream decoded against the global window. |
| `PlaBlock` | One indexed block: `Offset`, `Tag` (`BL` or `DY`), `Id` and `Kind` (raw), `Version` (0 or 1), `Flags` (raw), `SizeClass` (`Flags & 0xF`), `Mode`, `Guid` (present when flag 0x20 is set), `PackedSize`, `UnpackedSize`, `Extra` (present when flag 0x400 is set; raw), `PayloadOffset`, `HeaderLength`, `End`. |
| `ObjectDirectory` | A run of directory records inside a raw block: `Block`, `RecordOffset` (payload offset of the first record), `Phase` (`RecordOffset % 30`), `Records`, `AbuttingPairs`, `OverlappingPairs`, `DuplicatePositions`. The run is an estimate and can be shorter than the real directory: it stops after more than 8 consecutive records without an abutting neighbour. |
-| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The position and count name a byte extent of the decoded global stream — the object's data (see `PlaDocument.OpenStream`). The class number is not mapped to a class name. |
+| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. `PlaStream.ReadExtent` interprets the extent as bytes in the decoded global stream. The framed FDEA tables used by `ReadElements` store extents in 16-byte units in the decoded pool. |
| `PlaStream.Length` | Length of the decoded stream in bytes, including the bytes beyond the unreliable boundary. |
| `PlaStream.UnreliableFrom` | The offset of the first indexed block that failed to decode, or null when every indexed block decoded. |
| `PlaStream.SkippedBlocks` | The indexed blocks that failed to decode to their declared size (false entries of the scan), in file order. |
| `PlaStream.ReadExtent(long position, long count)` | The bytes of one extent. Throws `ArgumentOutOfRangeException` for negative or out-of-bounds extents and `InvalidDataException` for extents that reach the unreliable range. |
| `PlaStream.ReadExtent(ObjectDirectoryRecord record)` | The bytes addressed by a directory record. Throws `InvalidDataException` if the extent exceeds the stream or reaches the unreliable range. |
+The embedded library catalog reads Windows GSM version 46 from verified archive records. It recognizes raw, zero-mask
+and supported standalone QuickLZ payloads. For a verified QuickLZ asset pool, it reassembles the pool before reading
+its logical blocks. This includes asset headers and payloads that cross frame boundaries. Pool decoding respects
+`MaxDecodedPoolBytes`.
+Readable assets with other media types are excluded. The GSM bytes belong to the archived revision, which may have a
+different GUID from the revision saved in an element's library reference. Library files linked outside the archive
+and script evaluation require separate readers.
+
+## Model elements
+
+| Member | Use |
+|---|---|
+| `PlaDocument.ReadObjectClasses()` | Reads the file-local class numbers and stored class GUIDs from the version 1 `FDE9` block. The class number can differ between projects. |
+| `PlaDocument.HasObjectClassTable` | Reports presence of an indexed object class table before reading or validating its contents. |
+| `PlaObjectClass` | `Number`, `Guid`, and `Name`. Names are Archicad API labels for known GUIDs. The table stores GUIDs, and a class with an unrecognized GUID has a null name. |
+| `PlaDocument.ReadElements()` | Reads recognized elements from framed `FDEA` directories and verifies the class and GUID of pool records used for parameters. Returns a read-only snapshot with one record per GUID. An unusable class table, conflicting types, a truncated element or grid list, or a pool decode failure raises `InvalidDataException`. |
+| `PlaElement` | `Guid`, `Type`, nullable basic parameters, `BoundingBox` and the elevation properties described below. The wall values are in metres. The chord is the distance between the stored endpoints. Thickness is returned when the stored endpoint thicknesses agree. |
+| `PlaDocument.ReadClassificationSystems()` | Reads the saved systems and item hierarchy as described under [Classifications](#classifications). |
+| `PlaElement.Classifications` | A list of `PlaClassificationAssignment` values with `SystemGuid` and `ItemGuid`. Empty means the element has no assignment in the readable systems. Null means the classification catalog is unavailable. |
+| `PlaDocument.ReadPropertyCatalog()` | Reads the saved user-defined groups and definitions described under [User-defined properties](#user-defined-properties). |
+| `PlaElement.PropertyOverrides` | Saved overrides linked to the element, sorted by definition GUID. Null means the reader found no verified override record for the element. |
+| `PlaDocument.ReadLayoutBook()` | Reads the [layout book](#layout-book), including layouts, master layouts and drawing entries. |
+| `PlaBoundingBox` | `XMin`, `YMin`, `ZMin`, `XMax`, `YMax`, `ZMax`. These are axis-aligned limits in project coordinates, in metres, with Z relative to project zero. |
+| `PlaElement.BeamNetVolume` | The net volume in cubic metres for a supported beam. A verified box can be available when the contact geometry leaves the volume unresolved. |
+| `PlaBeamReferenceAxis` | The saved directed axis of a supported straight or horizontally curved beam, exposed through `PlaElement.BeamReferenceAxis`. |
+| `PlaWallReferencePlan` | The directed reference line of a supported straight basic or composite wall, and the signed offsets to its outside and inside faces. Exposed through `PlaElement.WallReferencePlan`. |
+| `PlaWallProfile` | The saved local cross-section of a supported complex-profile wall, exposed through `PlaElement.WallProfile`. |
+| `PlaMemberProfile` | The saved local cross-section of a supported single-segment complex-profile beam or column, exposed through `PlaElement.MemberProfile`. |
+| `PlaSlabGeometry`, `PlaSlabArc`, `PlaPlanPoint`, `PlaSlabPrism` | The saved slab outline and elevations, analytic outline area, optional face areas and volume, and evaluated vertical slab parts when their geometry is available. Exposed through `PlaElement.SlabGeometry`. |
+| `PlaWallExtrusion`, `PlaWallExtrusionSection` | The verified solid of a supported straight wall, with the sweep endpoints, section origin elevation, connected section contours and net volume. Available through `PlaElement.WallExtrusion` in .NET. |
+| `PlaColumnExtrusion`, `PlaColumnExtrusionSection`, `PlaColumnEndPlane` | A supported vertical column solid with its axis, section contours, cap planes, tight bounds and net volume. Available through `PlaElement.ColumnExtrusion` in .NET. |
+| `PlaColumnCutMesh`, `PlaColumnMeshPoint` | The triangulated boundary, tight bounds and net volume of a supported column cut by beams. Available through `PlaElement.ColumnCutMesh` in .NET. |
+| `PlaOpeningProfile` | An Opening's base profile shape, width and height in metres, exposed through `PlaElement.OpeningProfile`. |
+| `PlaDoorDimensions` | A Door's saved nominal width and height in metres and optional sill height relative to its saved anchor, exposed through `PlaElement.DoorDimensions`. |
+| `PlaDoorPlacement` | The position on a supported straight host wall, the distance from the directed start of its reference line, and optional nominal sill elevations to project zero and to the wall's home story. Exposed through `PlaElement.DoorPlacement`. |
+| `PlaDoorWallHoleDimensions` | The saved GDL wall-hole width and height in metres, exposed through `PlaElement.DoorWallHoleDimensions`. |
+| `PlaLibraryPartReference` | A Door's saved main and revision GUIDs when the element and library descriptor confirm their link, exposed through `PlaElement.LibraryPartReference`. |
+| `PlaOpeningGeometry`, `PlaOpeningCut` | The project XY profile of a supported horizontal Opening, its optional per-slab cut intervals and cut volume through `PlaElement.OpeningGeometry`. |
+| `PlaDocument.ReadStories()` | Lists saved project stories in ascending index order, including those without elements. Returns an empty list when the class table is usable and no supported story table is present. Invalid class tables, invalid recognized rows and conflicting names raise `InvalidDataException`. |
+| `PlaStory` | The signed project-relative `Index`, saved `Name` and `ElevationToProjectZero` in metres. A saved empty name is preserved. The elevation is null if the stored elevation is nonfinite or multiple tables disagree. |
+| `PlaDocument.ReadGridAxes()` | Lists supported straight and circular grid axes in GUID order. The grid store and placed object must confirm membership, and the object must have a model partition and a verified library descriptor and parameter table. Incomplete or unsupported placements and drawing copies are omitted. |
+| `PlaGridAxis` | The placed object's `Guid`, saved start-marker `Label`, directed `Start` and `End` in project XY metres, and nullable signed `HomeStoryIndex`. `ElevationToHomeStory` is the saved offset in metres, and `ElevationToProjectZero` adds the home story elevation when known. `FloorPlanSegmentLength` gives the saved segment length for segmented floor plan lines and `IsFloorPlanLineHidden` indicates a hidden line. The endpoints describe the full reference axis. `Tessellate(maxError)` samples that axis with a chord error limit in metres. |
+| `PlaGridArc` | The circular radius in metres, center in project XY metres and positive counterclockwise sweep in radians. Returned by `PlaGridAxis.Arc` for circular axes, whose endpoints are ordered counterclockwise. |
+| `PlaDocument.ReadLayers()` | Lists identifiable layer attributes in ascending layer index order, including layers without elements. Conflicting GUIDs or index records raise `InvalidDataException`. |
+| `PlaLayer` | The stored attribute `Guid`, positive project-local `Index`, saved `Name` and stored `IntersectionGroup`. The name can be null for the built-in layer's localization token. The group can be null when the record ends before the field. |
+| `PlaDocument.ReadMaterialCatalog()` | Reads the saved building materials and composite definitions in ascending project-local index order, including unused attributes. Conflicting indices and GUIDs raise `InvalidDataException`. |
+| `PlaMaterialCatalog`, `PlaBuildingMaterial` | The catalog's materials expose their GUID, index, name, user-defined ID and normalized connection priority. The priority is null for unsupported encodings. |
+| `PlaComposite`, `PlaCompositeSkin` | A composite exposes its GUID, index, name, total thickness, supported element types and ordered skins. Each skin identifies the referenced building material by index and gives its thickness and core and finish flags. |
+| `PlaDocument.ReadProfileCatalog()`, `PlaProfileAttribute` | Lists complex profile definitions in ascending project-local index order, including unused attributes. Conflicting indices and GUIDs raise `InvalidDataException`. |
+
+Recognized model types are Beam, Column, CurtainWall, Door, Lamp, Mesh, Morph, Object, Opening, Railing, Roof, Slab,
+Stair, Wall and Zone. An Object must appear in the element GUID list of its owning model database. Grid GUIDs are
+excluded using the saved grid list. PlaIO uses the declared record lengths to locate both lists. Older supported
+Object records also expose Element ID, layer index and home story index. If the membership records use an
+unsupported layout, Objects are omitted.
+Unknown classes remain visible through `ReadObjectClasses()`.
+
+For supported basic walls and slabs, `BuildingMaterialIndex` stores the material attribute index. For supported composite
+walls and slabs, `CompositeIndex` stores the index of the composite definition. Join these indices to the corresponding
+entries from `ReadMaterialCatalog()`. A composite wall's skins are ordered from outside to inside and a slab's from
+top to bottom. Thicknesses are in metres. Profile components and geometry altered by joins have separate representations.
+
+Element ID decoding covers all the recognized types in the supported record layouts. For zones, the reader follows the
+saved relationship to the zone stamp in the same pool and reads the ID from the stamp. A missing, incomplete, ambiguous,
+or unsupported parameter is null.
+
+The effective layer is given as a project-local attribute index and its saved name. Doors and openings take the effective
+layer from their host. Openings also take the home story from their host. The home story number is signed and is relative
+to the project's story zero. `HomeStoryName` preserves the saved name, including an empty name when Archicad displays a
+localized default. A built-in layer stored as a localization token has a layer index and a null name.
+
+`TopLinkedStoryIndex` is the signed project-relative index of the story to which a wall or column top is linked.
+It is resolved from the stored story partition relationship. An unlinked element or an unresolved partition has a null index.
+
+For Doors, `HostGuid` identifies the wall when both saved records confirm the relationship.
+`DoorDimensions` gives the saved width and height independently of host resolution. `SillHeightFromAnchor`
+uses the Door's saved vertical anchor and is null if the placement frame is unsupported.
+`DoorPlacement` resolves the point on the directed reference line from the saved distance along that line.
+It combines the wall's saved base offset and the Door's sill offset for the host-story elevation, then
+adds the wall's story elevation for the project-zero value. The placement applies to supported vertical
+doors on straight walls. The nominal sill describes the placement anchor. Evaluated door and cut geometry
+has its own limits.
+`DoorWallHoleDimensions` reads the instance's saved `ac_wallhole_width` and `ac_wallhole_height`. It requires
+reciprocal links from the Door to the library descriptor and from the descriptor to its parameter table.
+Several Door instances may share a table. The evaluated aperture can extend beyond these dimensions
+when the library part adds cut geometry.
+
+For Openings, `HostGuid` identifies the associated wall or slab. `OpeningCutElementGuids` lists the host and any
+additional cut walls or slabs in GUID order. Both fields require reciprocal references in the same decoded pool.
+An unresolved host or an incomplete cut list gives null for the respective field. `OpeningProfile` gives the shape
+and dimensions measured in the extrusion plane. For custom profiles, width and height are the profile's planar dimensions.
+
+`BottomElevationToHomeStory` and `TopElevationToHomeStory` are measured in metres above the home story.
+`BottomElevationToProjectZero` and `TopElevationToProjectZero` add the home story's elevation from the saved story table.
+For supported straight horizontal beams, the reader projects the saved cross-section, including the placed
+components and circular edges of a complex profile. It can report both elevations when the verified beam,
+column and slab contacts leave a complete transverse section outside the combined cuts. Opposite collinear
+beam ends meet at their common section. A transverse junction limits the affected part of the axis to the
+peer section's projected strip. An unresolved plan extent can leave the 3D box null while both elevations
+are available. Overlapping collinear beams and unverified cuts can leave the elevations null.
+For a supported inclined straight beam, the saved normals and reference axis determine the two end faces.
+An inclined butt joint can make the schedule elevations depend on the adjoining beam. In those cases the
+reader can report verified 3D bounds and leave the schedule elevations null.
+Slab elevations use the saved horizontal planes derived from the reference plane and thickness. Zone elevations use
+the saved base offset, floor adjustment and height.
+Supported center-anchored vertical openings that cut one wall use their saved anchor elevation and profile height.
+Openings with a supported horizontal base frame can derive elevations across the slabs they cut. This covers
+the center anchor and the verified downward through-opening frame anchored at the top center of its profile.
+The reader uses each slab's saved planes and vertical edge layout and applies the Opening's through or one-sided depth limit.
+Additional cut slabs contribute only if the projected profile is inside their saved outline. A cut target whose
+plan bounds are disjoint from the Opening is skipped.
+For two Openings with the same associated slab, a limited-depth Opening can remove a vertical interval when its
+profile fully covers the other Opening's plan bounds. If limited-depth overlap remains ambiguous, the elevations
+are null.
+
+`OpeningGeometry` gives the saved profile in project XY. Rectangular and supported custom polygonal profiles have
+straight `Rings` with implicit closure, ordered as exterior then holes. For circular and elliptical profiles, use
+`Origin` as the center and `OpeningProfile.Width` and `Height` as the diameters along the project axes.
+`Cuts` is a list of slab GUIDs and project-zero elevation intervals. Each interval cuts the whole reported profile.
+The cut volume remains unavailable for the top-center circular frame, whose native subdivision can vary with diameter.
+Disjoint intervals are kept separate. `CutVolume` sums their depths and multiplies by the section area in square
+metres. For the supported circle layout, the volume uses the area of a circumscribed 36-gon, which matches the
+measured Archicad quantity. Elliptical cut volume, partial plan clipping, ambiguous overlap and effects of other
+solid operations remain unsupported. A known placement may still be returned when the cut geometry is unavailable.
+
+For supported basic, composite and profiled walls, PlaIO resolves linked tops from the saved story elevation and offset.
+It checks the reference planes against the world-space envelope when present. At verified junctions with walls,
+beams and slabs it checks material priorities, vertical overlap and whether the joined walls leave a section that
+still reaches both end planes. This includes supported collinear wall overlaps with reciprocal junctions and saved
+plan contours. A supported horizontal rectangular beam or a slab can move a basic wall's end plane when it covers
+the wall footprint. For non-rectangular slabs with straight-edged contours, the reader verifies that the footprint lies
+inside the filled polygon and clear of its boundaries and holes.
+A supported composite slab meeting a basic wall's end uses the boundary of its contiguous cutting skins. PlaIO
+reconstructs the skin elevations from the saved top plane and thicknesses and checks each material's priority.
+It bounds changes in plan at verified wall junctions and checks whether the other slab contacts can alter the
+cutting band at that footprint. At an oblique junction with a verified straight neighboring wall, it projects
+the intersection of the two wall strips onto the target axis. Collinear butt joints can have different offsets
+from their shared reference line. Compatible horizontal rectangular beams can extend the cut when their
+vertical ranges overlap the slab's cutting band. PlaIO checks the combined beam footprints between successive
+beam faces, including verified equal-priority right-angle beam joins where the wall stays clear of the outer
+corner. The cut extends only through the bands that cover the entire joined wall footprint.
+For a beam connected to the cutting slab, PlaIO can verify clearance after beam-to-beam joins. It checks
+reciprocal joins and projects the intersection of horizontal rectangular beam strips onto the beam axis.
+Verified collinear butt joints also preserve clearance. Slab contacts are checked in the part of each skin
+inside the wall's elevation range, including contacts with supported circular columns below the wall.
+For a supported straight composite wall and a vertical-edged composite slab, a continuous cutting band can
+move an end plane if its priority reaches that of every wall skin. The reader verifies both cutting bands
+and the remaining contacts when separate slabs trim opposite ends. Reciprocal labels on the slabs preserve
+the cutting band. The schedule elevations are reported relative to both the home story and project zero.
+Several vertical-edged slabs can jointly cover a wall end. PlaIO checks the union of their filled outlines,
+including holes, between successive cutting planes. For automatic junctions, this calculation supports basic
+walls and straight composite walls with verified transverse skin placement. At wall junctions it checks that
+the cuts cover any extension of the joined wall and that a section of the authored wall survives at each
+reported plane. Multiple junction records connecting the same wall and slab contribute one cutting body
+after the reader verifies the reciprocal links. The reader also evaluates supported reciprocal slab subtraction
+links, including vertical extrusion in either direction. When one slab subtracts from another, both slabs must
+independently cut the same wall with the same operation and direction. The reader checks that these dependencies
+are acyclic and checks the layer intersection groups independently of the subtraction. A wall used as an
+operator retains its own geometry after the reader verifies the operation and its reciprocal target link.
+A verified subtractive operation keeps a neighboring wall within its reference body. If a verified wall contact
+may remove material from a slab, PlaIO evaluates the cuts with the full saved slab body and with that uncertain
+contribution omitted. It reports elevations only if both reproduce the same limits and the full-cut case leaves a
+verified patch at each plane.
+A verified slab opening that misses the cutting band in plan or height can preserve coverage. For a supported
+centered circular opening, the clearance check uses the circumscribed 36-gon. If a reciprocal opening may reduce
+a slab cutting band, the reader compares the wall limits with that full band and with the band omitted. It can
+report an end when both limits agree there and the remaining material is verified. A verified separate opening
+in the wall can preserve the reported elevations
+when it lies between those planes. Additional operations that can alter the end sections may leave the schedule
+elevations unavailable.
+
+For a basic wall, a single slab can establish a complete cut through the cap beyond its cutting skins.
+Two or more verified composite slabs can also establish a complete cut when their single cutting skins share
+both elevations and their combined outlines cover the joined wall footprint all the way across.
+PlaIO can combine that verified cap with a separate cut at the opposite end.
+In that case, a horizontal rectangular beam can replace part of the slab's cutting layer when its saved
+connections and material priority confirm that it also cuts the wall. The reader checks the beam's joints
+and other structural contacts over the wall footprint. It requires a surviving section of the wall outside
+the combined beam contacts at the resulting elevations.
+
+For a supported straight wall with a rectangular door opening, PlaIO checks the reciprocal host link, the saved
+library part and revision, and the placement along the wall. For supported swing doors and swing doors with a transom,
+the saved GDL parameters must confirm the rectangular passage and exclude additional cuts. It reports the wall elevations when a section outside
+the opening and the other cutters reaches both end planes. At a junction with a straight-edged, vertical-sided
+slab, the reader projects the slab contour along the wall with a `1e-7` metre clearance margin. If that
+projection leaves no gap, it checks the saved slab outlines in plan, including holes with verified vertical
+edges. It can confirm each plane using a different square of wall material with a `2e-6` metre side.
+Supported slabs, horizontal beams, basic neighboring walls and rectangular door apertures use their verified
+height ranges to determine which planes they can reach. A contact without verified height is included at both
+planes. The reader reports an independently verified wall elevation even when the opposite plane is unresolved.
+This includes retained original planes and evaluated slab cuts where the expanded joined wall and the verified
+remaining material in the authored section reach the same elevation. A wall solid requires both planes
+and a verified section. Door parts with unverified cut geometry leave the wall schedule elevations unavailable.
+
+At a reciprocal end-to-end junction, the saved junction point can confirm a common longitudinal end plane for
+parallel rectangular walls whose transverse coordinates differ by up to `1e-6` metres. For an overlapping basic
+neighbor with a corroborated saved height range, PlaIO can retain a wall elevation outside that range while
+treating the neighbor's plan coverage as unresolved.
+
+For a supported sliding pocket door revision, PlaIO checks the saved aperture dimensions, centered leaf and frame
+settings, and the three skins of the symmetric composite host. On an axis-aligned vertical wall it looks for
+material outside the through opening and both possible pocket envelopes bounded by the leaf width and frame depth.
+This can establish wall schedule elevations even when the placement direction of the recess is unresolved. It leaves
+the cut solid unavailable in that case.
+
+For supported vertical columns, PlaIO projects a rectangular section onto its saved end planes, including angled
+cuts on an unrotated section. A supported single-material custom profile can supply bounds when its end planes
+are horizontal. Automatic junctions with walls, beams and slabs are checked against the saved materials and
+composite skins. An isolated horizontal beam with a rectangular section or a supported rectangular slab can change
+a column endpoint when it covers the full end face. PlaIO projects the beam section with its saved rotation about the axis.
+For supported horizontal rectangular beams parallel to the project axes, PlaIO combines their footprints between changes
+in elevation. A beam collision within the group is supported when the two parallel axes are distinct and the axial ends
+and vertical ranges agree. Rectangular beams in a perpendicular junction are supported where the junction stays clear
+of the element footprint. For a verified T-junction with both beams in the cutter group over the same vertical band,
+PlaIO can use their combined footprint where the through beam covers the joining end. If only the stronger branch
+can cut a column in that junction, its cutter footprint reaches the far face of the through beam. A stronger
+through beam retains its footprint at a junction with a weaker branch.
+
+Unresolved geometry and operations leave the affected elevation fields null. Beam joins that may change coverage
+at the element, coupled cutters outside the supported group and wall junctions without a verified remaining section
+still require additional geometry.
+A missing story elevation
+leaves the project-zero fields null.
+
+### 3D bounding boxes
+
+`PlaElement.BoundingBox` returns a box for supported wall, slab, zone, column and beam records. A wall may carry a saved
+3D box. For a supported straight wall without one, PlaIO can combine a reciprocal rectangular plan contour with
+verified end planes when its only junction contacts are with other walls. A verified inline rectangle can supply the plan
+extents of a straight wall with an empty plan cache. Supported placed wall profiles use the full cross-section,
+including when an inline slice confirms its orientation. The element box can preserve the authored height at a cut.
+For wall elevations, a verified inline rectangle can also establish the wall's strip in a reciprocal junction.
+The reader checks associated dimension and label records before using that proof.
+For slabs and zones, PlaIO uses the
+saved contour extents and horizontal planes, including slab contours with arcs. For supported isolated vertical
+columns, PlaIO projects the saved section into plan and uses the end planes for Z. Joined rectangular columns
+can also retain their box when the saved relationships, priorities and cutter bands leave the end faces intact.
+An evaluated rectangular `ColumnExtrusion` can provide a box after a verified full-width end cut.
+For a supported single-segment complex-profile column, the element box uses the placed profile and saved
+cap-axis elevations. This also applies to verified cuts, including columns with oblique end planes.
+For a centered profile with a crosshair symbol the plan bounds include the four ends of its saved extension,
+rotated with the element. The extrusion or cut mesh supplies the bounds of the evaluated physical solid.
+
+`ColumnExtrusion` describes a supported vertical single-segment column with a rectangular or straight-edged
+single-fill profile section. Its contours use project X and Y directions with the column axis as the origin.
+For a circular column with horizontal faces, `CircularRadius` supplies the analytic radius and `Sections` is empty.
+The analytic volume and bounding box of the circular solid use that radius. `ScheduledCapArea`,
+`ScheduledLateralArea` and `ScheduledVolume` use the Archicad listing polygon with equal subdivisions of
+each quadrant and a maximum sagitta of one millimetre.
+Each end plane gives an elevation relative to project zero at that axis and two slopes for other points on the
+plane. Supported full-width end cuts can replace the saved cap. When verified beam cuts remove the entire
+section at intermediate heights, `Spans` lists the remaining project-zero intervals in ascending order.
+For a verified T-junction with matching vertical section limits, the reader can use the combined
+sweep of two rectangular cutters with equal priority when the through beam still covers the join. It also
+supports a rectangular branch ending against the near face of a weaker through beam with a straight-edged
+concave section. Repeated contacts must agree on that face. Coincident horizontal cutter faces within
+`1e-8` metres use the same mesh boundary. Interior beam collisions and
+symmetric miters preserve the cutter where the saved contact and section geometry establish clearance or
+priority. Possible wall wrapping can leave the geometry unavailable. A composite wall with verified skins all
+in the core or all outside the core cannot wrap the column. Its contact can preserve the column solid when
+the material priority and the other contacts permit it.
+A rectangular column with horizontal caps can retain its solid when its rotated footprint misses a joined beam.
+PlaIO tests the footprint inside the beam's section strip against the axial reach of all verified beam joins.
+For a crossing recorded without a point, the reader checks that the overlap of the two section strips
+stays strictly between the cutter beam's saved caps.
+A reciprocal annotation link can coexist with the column geometry. PlaIO verifies the back-reference of an associated
+column label or angular dimension before evaluating the column. A label's wall and column references are verified
+independently. PlaIO also verifies angular dimension references on
+connected beams. The extrusion box encloses the solid tightly.
+An Archicad element box can preserve authored extents or be wider in plan than the evaluated solid.
+
+`ColumnCutMesh` supplies the closed boundary of a supported rectangular or profiled vertical column after a partial beam cut.
+With horizontal caps and horizontal rectangular cutters, it uses the saved straight-edged section, including
+concave outlines with a single boundary. Two verified cutters of equal priority with matching rectangular sections can
+share a miter plane through their common endpoint. PlaIO clips both masks at that plane. A weaker peer at the same
+endpoint is accepted when it repeats the verified cap geometry and its full section stays inside the matching envelope.
+At a rectangular column, a weaker beam sharing the same saved axis
+and caps can share the rectangular cutter's mask when its entire section fits inside the stronger beam and
+the verified contacts leave the cut unchanged. PlaIO also exposes the element's box when the mesh retains all
+six limits of the saved rectangular column. For oblique caps and inclined cutters, it supports axis-aligned
+rectangular column profiles. The reader verifies the cap planes, cutter profiles and structural contacts.
+Cuts can remove only part of the section or leave internal cavities.
+The triangle vertices are relative to the mesh's project-coordinate origin. `BoundingBox` on this mesh
+encloses the evaluated solid tightly.
+
+`WallExtrusion` describes the solid of a verified straight vertical wall. A wall with a constant cross-section
+sweeps a rectangle or a straight-edged complex section along its reference line. The complex section combines
+the saved material regions, retaining holes and disconnected pieces. For an axis-aligned rectangular wall with
+supported simple Door openings, the reader subtracts the rectangles from the wall elevation and sweeps the remaining section
+across the wall thickness. The Door links and instance parameters must confirm the openings, with all four
+oversize parameters set to zero. This path can also recover the wall box and elevations when the plan cache
+is absent. The sweep endpoints describe the solid's direction in both cases. `WallReferencePlan` gives the
+authored reference line. Wall junctions, other cut types, slants and profiles with curved edges remain outside
+this solid reconstruction. A verified zone-area calculation can reference the wall without affecting mesh eligibility.
+
+For supported horizontal beams, PlaIO sweeps the saved section along the beam axis, including the stored section
+rotation. It resolves validated equal-priority butt joints, perpendicular T-junctions and axis-aligned L-junctions
+with matching vertical profiles. At a supported T-junction the branch ends at the through beam's near face.
+At a supported L-junction an outer corner of each beam reaches the far face of its peer. A beam that takes
+precedence over a reciprocally linked slab, wall or supported rectangular column keeps its box at that contact.
+Unjoined horizontal complex-profile beams can also supply a box from the saved placed section.
+For a straight beam with inclined or oblique end planes, PlaIO intersects the section's sweep with the two
+saved planes and projects the resulting end faces. An inclined beam can keep that box when material priorities
+preserve the solid or the checked cutters miss both end faces. This includes supported walls whose placed profile
+is clear of both faces and collinear vertical butt planes unaffected by a distant transverse junction.
+
+For horizontal circular beams with supported unrolled complex profiles, PlaIO sweeps the section about the saved
+circle. At verified end connections with matching placed profiles, it intersects equal transverse offsets of the
+neighboring circular or straight axes. A slab cut within the beam's vertical span preserves the elevations when
+the end connections leave a complete section. The 3D box also requires a surviving point at each plan extremum.
+
+Saved wall boxes are read independently of schedule elevations and may differ after junction cleanup. For the boxes
+reconstructed from profiles, contours or planes, a missing story elevation or unsupported geometry leaves the box
+null. Unresolved wrapping, column cuts and beam end changes may require additional geometry.
+General solid element operations are still outside this reconstruction.
+
+For a horizontal `BeamNetVolume`, the reader multiplies the rectangular section area by the evaluated length. A supported square
+butt cut shortens that length. At a supported symmetric miter, the added and removed wedges have equal volume.
+For supported inclined beams with parallel cut planes, the reader uses the rectangular or single-component
+straight-edged profile area and the 3D axis length when the known contacts preserve the solid.
+A horizontal profiled beam has zero net volume when the intact portions of reciprocally linked rectangular beams
+with higher material priority cover its complete section along the span. The reader includes supported end
+extensions of the profile and excludes the portions of each covering beam that its verified contacts can remove.
+This zero is available even when the covered beam has no evaluated box or elevations.
+Net volumes for curved beams remain unresolved. Their saved circular axes and profile arcs suffice for supported
+extents, while their volumes also depend on how the model facets the curves and resolves the end connections.
+
+`BeamReferenceAxis` gives the saved start and end in project XY, their project-zero elevations, and the signed
+plan sweep. A positive sweep turns counterclockwise from start to end. `Length` follows that straight line or arc
+before junction cleanup. `InclinationRadians` is positive when the end is higher than the start. The axis remains
+available when the evaluated beam geometry is unresolved. A circular axis requires agreement between the saved
+sweep and both end-plane normals. A missing story or unresolved axis record leaves the field null.
+
+`WallReferencePlan` describes the authored placement before junction cleanup. Its start and end are in project XY,
+and both face offsets are positive toward the right of the directed reference line. PlaIO reports the plan for
+validated inline rectangles of constant width, including flipped and core-referenced walls. The property is null
+when the reference settings and saved rectangle disagree, or when no supported rectangle is present.
+
+### Classifications
+
+`ReadClassificationSystems()` returns the supported saved systems sorted by GUID. A system carries its saved name,
+description, source, version label and optional publication date. Its flat `Items` list gives the saved item GUID,
+displayed ID, name and description. Items appear in depth-first order with siblings in saved order. A null
+`ParentGuid` identifies a top-level item.
+
+The reader follows the saved links between each system, its internal root and its visible items. Assignments
+come from item records and are limited to elements recognized by `ReadElements()`. An element can have one saved
+assignment per system. The assignment list follows system GUID order. A file without a supported catalog returns
+an empty system list. Truncated supported records, broken trees and conflicting assignments raise
+`InvalidDataException` when reading the affected data.
+
+### User-defined properties
+
+`ReadPropertyCatalog()` reads user-defined groups and definitions directly from the file. Group and definition
+lists are sorted by GUID and include unused records. Definitions expose the group GUID, name, description,
+data type, classification availability and saved enumeration choices. A definition applies to an element when
+one of the element's `Classifications` item GUIDs occurs in its `AvailableClassificationItemGuids`.
+
+Recognized scalar types are integer, number, length, area, volume, string and boolean. Enumerations expose
+their choices in display order. Supported literal defaults return `normal` and an `int`, `double`, `string`
+or single choice `Guid` value according to the data type. Length, area and volume use metres, square metres
+and cubic metres. The statuses `userUndefined` and `expression` carry no literal value. An unsupported default
+encoding yields null.
+
+`PropertyOverrides` exposes explicitly saved element-level values with the definition GUID. The reader verifies
+both the definition's link to the override record and the override's link back to the definition. An override
+with a recognized link and an unsupported value encoding has a null value. Values inherited from the definition
+are available through `ReadPropertyCatalog()`. Built-in property definitions, formula evaluation and Boolean and
+multiple-choice literal values need additional support.
+
+### Layout book
+
+`ReadLayoutBook()` returns the book root GUID and a flat list of its items in depth-first order. Each item
+supplies the parent GUID and an Archicad navigator type label. The supported item types are `LayoutItem`,
+`DrawingItem`, `SubsetItem`, `MasterFolderItem` and `MasterLayoutItem`. Top-level items refer to the book GUID.
+The master folder is represented by its GUID and type.
+
+Subsets, layouts, master layouts and drawings expose their saved name and navigator identifier. An identifier
+can be empty. Layouts and master layouts expose the source GUID from the navigator link and the verified layout
+database GUID. A layout exposes the navigator GUID of its assigned master and inherits that master's paper size.
+Paper sizes use metres.
+
+A placed drawing exposes its saved source path and the source GUID from a verified internal view link or supported
+external source record. An empty source path is preserved. A missing or ambiguous internal view link yields a null
+source GUID. Drawing content remains pending.
+
+`PlaLayoutBookItem.Revision` exposes the revision status of layouts and master layouts with recognized revision
+records. It includes the issued history in saved order, oldest first. Each entry has the revision GUID and ID
+and the transmittal's GUID, ID, name, UTC issue time and issuer. A saved open revision link exposes its transmittal
+with a null issue time and issuer. If there is no open revision, the last issued ID supplies both current ID
+fields. Two empty IDs represent a layout with a readable state and no revisions. A null revision summary means
+the record is unavailable or its format is unsupported.
+
+For an open revision, `CurrentRevisionId` comes from the transmittal ID when `OverridesRevisionIds` is enabled.
+Otherwise the saved layout numbering applies, including a retained transmittal override and the history of issued
+IDs. Automatic numbering supports decimal suffixes and uppercase ASCII letter sequences. An unsupported sequence
+yields a null current ID. `CurrentFinalRevisionId` remains null while the revision is open because the
+application supplies the localized display suffix. Open revisions without a verified transmittal link and
+changes associated with each revision need additional support.
+
+The method returns null when no supported book is found. A recognized book with conflicting records or broken
+links raises `InvalidDataException`.
+
+### Complex profiles
+
+`WallProfile` gives the project-local profile attribute index and the material components saved for a placed wall.
+`MemberProfile` gives the corresponding values for a supported single-segment beam or column. Saved profile indices
+can refer to attributes unavailable in the project catalog.
+`ReadProfileCatalog()` resolves either index to its saved attribute when present and exposes the undeformed section.
+The profile definition includes its enabled element types, width, height and core flag when those fields are supported.
+The width and height include circular edge extrema. `WidthStretch` and `HeightStretch` expose the saved enabled flags,
+local stretch intervals and minimum sizes in metres. An enabled interval gives the part of the section that can contract.
+The reader computes the minimum size by removing the interval's overlap with the section extent. A disabled axis has
+null interval bounds and keeps its full size. A missing or unsupported stretch record leaves the whole axis value null.
+
+`Modifiers` lists the saved names and GUIDs of offset modifiers whose profile, instance and definition links agree.
+An empty list represents a verified profile without named modifiers. A null list means the links or layout are unavailable.
+Each modifier's `DefaultValue` is its signed value in metres on the undeformed catalog section. The reader resolves
+its saved dimensional constraints and projects the distance between their anchors onto the stored direction.
+The value is null when the anchors are unavailable or the modifier's dimensions disagree. Placement-specific
+overrides remain unavailable.
+Positive component `BuildingMaterialIndex` values resolve through `ReadMaterialCatalog()`. Zero denotes an unassigned
+catalog fill. Components follow saved drawing
+order. `Function` supports `Core` and `Other` and is null for unrecognized values.
+
+The first ring is the exterior and any following rings are holes. Vertices are in saved order with the closing
+vertex omitted. `U` and `Z` are the saved coordinates in the local profile plane, in metres. For a wall they
+represent the horizontal and vertical coordinates of the section. A column's section is transverse to the column axis.
+`Arcs` identifies circular edges by zero-based ring and starting vertex. Each extends to the next vertex, wrapping
+at the end. Positive angles turn counterclockwise. `CrossSectionArea` integrates the saved exterior and subtracts
+the holes, including the circular edges.
+
+PlaIO requires reciprocal links from the wall or through the beam or column segment, and a valid section for every component. Each component
+may include up to 4,096 stored vertices. The saved fills may overlap. The profile describes the local cross-section
+before inter-component clipping, element junctions and other solid operations.
+
+### Slab outlines and solids
+
+`PlaElement.SlabGeometry` exposes a supported slab outline in project coordinates. The first
+ring is the exterior in counterclockwise order. Subsequent rings are holes in clockwise order. The final edge
+joins the last point back to the first. The reader validates simple rings and rejects holes that touch, cross,
+nest or lie outside the exterior. The outline limit is 4,096 stored points.
+
+`Arcs` supplies the circular edges. Each arc identifies its zero-based ring and starting vertex. Its end is the
+next vertex, including the first vertex for a closing arc. `SweepRadians` is positive counterclockwise.
+Edges with no arc entry are straight. `Arcs` is null when all edges are straight.
+`FloorPlanPerimeter` is the total length of the saved exterior and hole boundaries. `FloorPlanHolesPerimeter` gives
+the length of the hole boundaries alone, or zero when there are no holes. Both lengths use metres and include exact
+arc lengths. Linked Opening cuts are tracked separately.
+
+`Bottom` and `Top` are saved slab elevations relative to project zero in metres. The reader includes the saved
+offset from the reference to the upper plane in supported composite slab layouts. `OutlineArea` is the area inside
+the saved exterior minus holes in the outline, in square metres. For circular edges, it integrates the exact saved
+arcs. Archicad's scheduled face areas can differ from this analytic area. `TopAreaWithOpenings` and `BottomAreaWithOpenings`
+are gross horizontal face areas with both saved holes and verified linked Opening cuts subtracted. A one-sided
+opening reduces the face it reaches. Unverified opening links, nonvertical edges or curved outlines yield null face areas.
+
+`Volume` in cubic metres is available when the slab has vertical edges and the reader can verify all contacts.
+Supported linked openings reduce the volume when other contacts preserve the slab prism. For slabs without
+linked openings, the reader can also deduct verified cuts by vertical rectangular columns and straight
+walls with a saved polygonal profile. It intersects a rotated column footprint with the slab rings at skins
+with equal or lower material priority. For a profiled wall it checks the placement against the saved envelope
+and integrates the profile overlap through strictly lower-priority slab skins. Other joins that can modify the
+cutting element, unresolved overlaps between cuts or curved outlines withhold the volume.
+
+`IsUncutVerticalPrism` confirms that the saved outline and elevations describe the whole solid.
+`VerticalPrisms` supplies the evaluated solid as one or more connected parts from `Bottom` to `Top`.
+Each part has one counterclockwise exterior and optional clockwise holes. Vertical cuts by supported rectangular
+columns can add holes, change the exterior or split a slab into separate parts. Each cut must span the full slab,
+cut every skin and produce a closed polygonal boundary. Verified separate Opening elements with straight-edged
+profiles can also cut the whole extrusion when the other contacts preserve the slab. `VerticalPrisms` is null for
+cuts into individual skins, profiled wall cuts, partial-depth or curved Opening cuts, and unresolved contacts.
+Use `Rings` for the saved outline. Both prism properties are available in .NET. The JSON fields describe the
+saved outline and its quantities.
+
## Compressed pools
Pool framing was verified using saved container bytes. A 16-byte marker is followed by the decoded total and frame count
diff --git a/docs/reader-parity.md b/docs/reader-parity.md
new file mode 100644
index 0000000..9802b12
--- /dev/null
+++ b/docs/reader-parity.md
@@ -0,0 +1,144 @@
+# Reader parity with RvtIO
+
+The reference is the published RvtIO source at revision `2d65eefd39f3f53843d581753424c247e4b1addb`. The comparison
+covers data read from files and exposed to consumers. Revit-specific identifiers and schema objects need an Archicad
+counterpart only where they represent comparable model data. See the [RvtIO public API](https://github.com/IOExtend/RvtIO/blob/2d65eefd39f3f53843d581753424c247e4b1addb/docs/public-api.md).
+
+| Reader capability | RvtIO code and tests | PlaIO status and evidence needed |
+| --- | --- | --- |
+| Offline input and container metadata | `RvtDocument`, `RvtFileReader`, `RvtReaderOptions` and container diagnostics tests | PLN and PLA open from file or stream. The reader exposes raw header fields, class GUIDs, directories and pools. Project metadata and a fixture matrix by format version remain to be covered. |
+| Element census and selection | `RvtDocument`, `FilteredElementCollector`; class and category tests | `ReadElements()` and `plaio elements` report a GUID and type for recognized model elements. Coverage needs to account for each unsupported class and model database. |
+| Storeys, axes and element placement | `GetBuildingStoreyCatalog()`, `GetGridAxes()`; storey checks in `RvtSceneReaderTests` and grid paths in `SceneGridPathTests` | `ReadStories()` provides the full saved catalog for supported story tables. `ReadGridAxes()` reads straight and circular reference axes, including segmented and hidden floor plan displays, and the saved axis height. The scene adapter preserves grid labels and places lines and tessellated circular paths at their elevation relative to project zero. Labels, endpoints and arc geometry can be compared with a native IFC export. Element records expose the home story and, for walls and columns, the linked top story. Straight walls with a verified saved rectangle have a project XY reference line and face offsets. Supported straight and horizontally curved beams expose their directed reference axes in project coordinates. Supported doors expose the station on the wall's reference line and nominal sill elevations. Other grid layouts and general element placement are pending. |
+| Effective categories, materials and classifications | `Element`, `MaterialLayer` and `IfcExporterClassificationCurrentTests` | PlaIO exposes native element types, effective layer references, building materials, ordered composite skins, complex profile definitions with default modifier values and the material, composite or profile references for supported elements. It reads classification systems, ordered item trees and per-element assignments, verified against Archicad API with exact matches. Placed modifier overrides and materials on other element types remain pending. |
+| Native and user properties | `Parameter`, `ParameterDefinition`, `StorageType`; `NativeFieldParametersTests`, `UserParameterCatalogTests` | PlaIO exposes Element ID and supported dimensional and placement values, including wall-hole dimensions from the placed Door's GDL parameters. It reads user-defined groups, definitions, data types, classification availability, enumeration choices, supported literal defaults and linked element-level overrides. Definition metadata, default status, element applicability and the saved text and single-choice overrides match Archicad API on the validation corpus. Built-in property definitions, remaining value encodings and formula evaluation are pending. |
+| Hosts, openings and other model relationships | `Element.HostId`, `SerializedHostId`, `DerivedInstanceParamsTests`, `CurtainFamilyHostSerializationTests` | PlaIO exposes the Door wall, associated wall or slab for Openings, and Opening cut targets when both records confirm the links. It checks several structural junctions. Relationships still need a direct API comparison. The embedded library catalog exposes verified GSM parts and their identities. Assembly members, external library references and evaluation of door cuts from library parts are pending. |
+| Extents and quantities | `Element.BoundingBox`, `Element.Geometry.BoundingBox`; wall and quantity tests | PlaIO exposes 3D boxes for supported walls, slabs, zones, vertical columns and beams with straight or circular axes. It reports evaluated wall elevations for supported junctions by checking which cutters reach each plane and which wall material survives inside slab holes or beyond the slab edges. It resolves supported circular end connections with matching profiles and slab cuts that preserve the extrema. Net volumes are available for supported horizontal rectangular beams, fully covered horizontal profiles and inclined prisms. Supported wall and slab Openings expose elevations, including one-sided slab cuts and overlaps that fully cover the Opening profile. Boxes for other layouts and types, general evaluated boxes, areas and volumes are pending. |
+| Evaluated geometry, meshes and instances | `GeometryData`, `ElementMeshes`; `ElementMeshesTests`, `ElementMeshesSampleTests` | PlaIO exposes slab boundaries and saved complex cross-sections with straight and circular edges, including holes. It computes slab face areas after verified openings and volume after supported opening, column and profiled wall cuts on straight-edged slabs. It builds closed meshes for verified straight-edged slab parts, straight unjoined walls and supported vertical single-segment columns. Column meshes cover circular sections with horizontal caps, full-section end cuts, separated spans and verified partial cuts by horizontal or inclined beams. Circular columns expose analytic volume and the polygonal listing quantities. Supported Opening profiles and cut intervals are available in project coordinates. Multi-segment beam and column profiles, other curved solids, general partial-depth cuts and evaluated junction geometry are pending. |
+| Sheets and view contents | `SheetCatalog`; `SheetCatalogTests` | PlaIO reads layout book membership and order, layout and drawing identifiers and names, layout databases, assigned master layouts, paper sizes, drawing source GUIDs and issued revision history with transmittal date and issuer. For revisions explicitly linked to an open transmittal it reads supported current IDs, including manually assigned IDs and transmittal overrides. Localized display IDs, drawing content and view-owned graphics remain pending. |
+| Reader diagnostics and geometry coverage | `RvtReadDiagnostics`, `ExportReport`; `DiagnosticOutputTests` | PlaIO reports container limits and unusable data. Element reports still need to identify unsupported operations and distinguish absent, unsupported and verified values. |
+| Consumer output | RvtIO element JSON, IFC and `RvtSceneReader`; `RvtSceneReaderTests` | PlaIO provides CLI JSON for elements, stories, layers and grid axes. The scene adapter maps recognized elements, saved levels, grid lines and paths, native properties, applicable literal user properties, classification assignments, host relationships and supported slab, wall and column meshes. Broader mesh coverage and downstream IFC export are pending. |
+
+For each supported field, compare PlaIO against Archicad API for the exact saved files. Match elements by GUID and storeys
+by their signed index. Record applicable API values, matching reader values, missing reader values and differences
+separately for each type and field. Record the tolerances with the comparison. For project-zero and home-story elevations,
+and for coordinates of 3D bounding boxes, the current absolute tolerance is `1e-7` metres. Preservation of other CLI output is checked according to
+[CONTRIBUTING.md](https://github.com/IOExtend/PlaIO/blob/main/CONTRIBUTING.md).
+
+For grid axes, the Archicad JSON interface identifies the placed object by GUID but returns unsupported-element
+errors for its boxes. Compare saved labels, directed endpoints, project elevations and circular center, radius and sweep with the native
+`IfcGridAxis` export after converting IFC units and removing the IFC site placement. Keep repeated labels and
+coincident axes in the comparison. Floor plan display segment length is saved separately from the reference geometry.
+
+Check the IOScene output by source GUID against the same API element census and classification assignments.
+Compare level elevations by saved story index using `GetStoryNavigatorItems`, recording any API labels generated
+for empty saved names. Compare typed scene properties with the core reader and applicable literal values with
+`GetPropertyValuesOfElements`. Check closed, consistently oriented triangles for each mesh. Aggregate all instances
+by element GUID before comparing world-space bounds, cap areas and signed volume. For evaluated slab solids check
+`General_NetTopSurfaceArea`, `General_NetBottomSurfaceArea` and `General_NetVolume`. Apply the slab quantity
+tolerances below using the evaluated boundary perimeter and report missing meshes by category.
+Record any difference between the element extent reported by `Get3DBoundingBoxes` and the mesh's
+evaluated extent. When a cut removes a slab extremum, an isolated 3D export can verify the extent separately,
+using the coordinate precision of the export.
+For wall meshes, compare `General_NetVolume` with a tolerance of `1e-7` metres times the total mesh surface area,
+with a minimum of one square metre of surface area. For a rectangular wall, compare `General_NetTopSurfaceArea`
+at a tolerance of `1e-7` metres times the upper face perimeter, with a minimum of one metre of perimeter.
+For a wall with through Door cuts, compare the closed mesh in project coordinates. Check the net volume,
+upper face area, box and four scheduled elevations independently against the native API.
+Use the same volume and face-area tolerances for columns with a horizontal upper face. Check the column mesh
+against its tight `ColumnExtrusion.BoundingBox`. For columns with separated spans, measure the area left at
+the authored top face for `General_NetTopSurfaceArea`. Compare the tight box separately with `Get3DBoundingBoxes`
+and record the per-axis difference. Compare `PlaElement.BoundingBox` directly with `Get3DBoundingBoxes`, including
+the authored cap-axis heights and the plan extent of a supported crosshair symbol on a complex-profile column.
+Compare the four scheduled elevations using their individual API properties.
+For `ColumnCutMesh`, include only triangles on the saved upper cap when measuring the native upper area.
+For circular `ColumnExtrusion` solids, compare `ScheduledCapArea` with `General_NetTopSurfaceArea`,
+`ScheduledLateralArea` with `General_NetBottomSurfaceArea` and `ScheduledVolume` with `General_NetVolume`.
+On the validated files, the API's bottom surface property returns the polygon's lateral area.
+Use a tolerance of `1e-9` square or cubic metres. Compare extents and heights directly.
+Verify the analytic cylinder and tessellated scene separately from the schedule. The scene uses a
+`1e-7` metre sagitta limit, with at most 16,384 boundary segments per circle.
+
+Compare the saved GDL wall-hole dimensions with `WindowDoor_WallHoleDimension`. Parse the two lengths
+and allow half the unit of the last displayed digit. For the validation projects the API formats the values
+to three decimal places in metres. A library-generated cut can extend outside the listed dimensions.
+
+Compare classification systems by GUID, including the saved metadata and visible items in tree order. Compare
+element assignments by system and item GUID using `GetClassificationsOfElements`. Count matching unassigned
+elements, missing classifications and mismatched assignments separately.
+
+Compare the user-defined property catalog by group and definition GUID, including type, description, enumeration
+labels in display order and the set of available classification item GUIDs. Compare supported scalar defaults in
+SI units and enumeration defaults by their displayed choice. Track undefined and expression defaults separately
+from literal values. Join classification availability with saved element assignments and compare the resulting
+pairs with `GetAllPropertyIdsOfElements`.
+Compare explicit overrides against `GetPropertyValuesOfElements` by element and definition GUID. Count values that
+match the definition default, unavailable properties and values that require an override separately.
+
+Compare layout book GUIDs, parent links, type labels and depth-first order with `GetNavigatorItemTree`.
+Compare the names and identifiers of subsets, layouts, master layouts and placed drawings. Compare paper
+dimensions with `GetLayoutSettings` using an absolute tolerance of `1e-7` metres after converting the API's
+millimetres. Check each layout's master assignment through reciprocal database links and compare the inherited
+dimensions with those returned for the layout. Compare drawing source GUIDs directly with the navigator tree.
+Saved drawing source paths have their own file field and are reported when available.
+Compare revision IDs and the issued and open status flags with `GetLayoutSettings` by layout GUID. Record
+known absence separately from null IDs and unavailable summaries. Check issued history order and transmittal metadata
+against the native layout revision history. Check open IDs on saved copies with edited layout numbering, with and
+without a transmittal override, and after a previous override has been issued.
+
+Compare beam elevations against the four `General_*Elevation*` properties and the 3D box against
+`Get3DBoundingBoxes`. Horizontal beams with unresolved plan extents can still be checked by their box Z limits.
+At an inclined butt joint, check the box and schedule properties separately because the latter can include a
+vertical limit from the adjoining beam.
+Compare beam net volumes against `General_NetVolume` to `1e-8` cubic metres. Account for API values that are
+missing separately from reader gaps.
+
+Compare beam reference-axis inclination with `Beam_SlantAngle`. Check the endpoints and circular sweep against
+the independently saved axis and end frames. Compare authored length to listing lengths in cases where cleanup
+preserves that span. A listing length can change with intersection geometry.
+
+For a supported wall reference plan, project the two signed face offsets from each reference line endpoint.
+Compare the resulting XY limits with `Get3DBoundingBoxes` in cases where junction cleanup preserves those limits.
+Validate the direction and individual face offsets against the independently saved wall rectangle.
+
+Compare the material and composite catalogs by GUID and project-local index against
+`GetBuildingMaterialAttributes`, `GetCompositeAttributes` and `GetAttributesIndices`. Check skin order, building
+material references, role flags and thickness at `1e-7` metres. Compare wall and slab assignments by the
+composite name and the component material properties where available.
+
+Compare the complex profile catalog by GUID and project-local index through `GetAttributesIndices` and
+`GetProfileAttributes`. Check names, enabled element types, core and stretch flags exactly, and the default and minimum
+widths and heights to `1e-7` metres. Compare the named offset modifiers as a multiset and their default values to the
+same tolerance. Verify the reciprocal links, the anchor and dimension records, and the undeformed contours,
+arcs and stretch intervals against the saved definition.
+
+Compare each placed complex wall, beam and column profile index through `GetAttributesIndices`, `GetProfileAttributes` and
+`Construction_ProfileName`. Compare the component counts and the material names, IDs, roles and cross-section
+areas against `GetComponentsOfElements` and `GetPropertyValuesOfElementComponents`. Match components as a multiset
+because the saved drawing order can differ from API enumeration. The area tolerance is `1e-7` square metres.
+Compare local vertices and arc endpoints against the saved section. Track unresolved catalog indices and API components
+with role `None` and zero returned area separately from comparable materials, roles and areas.
+
+Slab area comparisons propagate the coordinate tolerance by multiplying it by the relevant boundary perimeter, with
+a minimum of one metre. Volume comparisons multiply the area tolerance by slab thickness and add the thickness
+tolerance of `1e-7` metres times the area, with a minimum of one square metre. Compare supported slab volumes with
+`General_NetVolume`. Compare `TopAreaWithOpenings` and `BottomAreaWithOpenings` against
+`Slab_GrossTopSurfaceAreaWithHoles` and `Slab_GrossBottomSurfaceAreaWithHoles`.
+Compare the saved slab boundary lengths against `General_FloorPlanPerimeter` and `General_FloorPlanHolesPerimeter`
+with an absolute tolerance of `1e-7` metres. For a curved slab outline, compare the extents reconstructed from all vertices and arc extrema with
+`Get3DBoundingBoxes`. Verify analytic `OutlineArea` by independently integrating the saved circular edges.
+Track differences from Archicad's scheduled face quantities separately.
+
+Compare each Opening profile against `Opening_Shape`, `General_Width` and `General_Height`. Use exact shape names
+and the same `1e-7` metre tolerance for widths and heights. Check Opening elevations in both reference systems.
+Verify associated hosts and cut targets from both ends of the saved relationships. The Archicad JSON API supplies
+the compared profile and elevation values.
+Compare Door width, height and sill height relative to its anchor against `General_Width`, `General_Height`
+and `WindowDoor_SillHeightFromAnchor` at the same tolerance. Verify the Door wall GUID from the reciprocal
+relations and compare the wall's Element ID against `IdAndCategories_ParentId`.
+Compare Opening project profile bounds against `Get2DBoundingBoxes` at the coordinate tolerance above. Use
+`General_NetVolume` for evaluated Opening cut volumes with a tolerance of `2e-9` cubic metres on the validation set.
+For a slab with verified straight-edged through Openings, check the void topology, compare the cut boundaries with
+the native profile positions and verify the slab's aggregate net areas and volume.
+
+Regressions for confirmed layouts belong in synthetic tests. The private input files, API exports and project-specific
+results stay outside the repository.
diff --git a/docs/scene.md b/docs/scene.md
index b86ba40..8deb03c 100644
--- a/docs/scene.md
+++ b/docs/scene.md
@@ -1,42 +1,69 @@
# The scene adapter
-`PlaIO.Scene` (namespace `PlaIO.Scene`) turns an Archicad container read by PlaIO into an `IOScene`
-[`SceneDocument`](https://github.com/IOExtend/IOScene/blob/main/docs/contract.md) — the neutral scene model that
-[IOViewer](https://github.com/IOExtend/IOViewer) and the coordination tools consume. The adapter uses only the public
-API of the `PlaIO` library and depends on the exact `PlaIO` version it ships with.
+`PlaIO.Scene` converts a PLN or PLA file into the
+[`SceneDocument`](https://github.com/IOExtend/IOScene/blob/main/docs/contract.md) used by
+[IOViewer](https://github.com/IOExtend/IOViewer) and coordination tools. The adapter uses the public PlaIO API.
-## What the scene holds today
+## Contents
-- One `SceneModel` for the file: `Key` and `Name` (see [Frozen derivations](#frozen-derivations)), `SourceFormat`
- (`pla` or `pln`, the lower-case file extension) and `Producer` (`PlaIO.Scene `).
-- No elements, no geometry, no property sets: the container reader does not decode element contents yet. Mode 2 (LZ)
- payloads, the meaning of the object directory records and the class names are research items (repository issues #7,
- #8, #9). The scene holds no guesses: what cannot be read exactly is not written, and the `container-only` diagnostic
- says so.
+- One model and one scene element for each recognized Archicad element. The native type is the category and the
+ saved Element ID is the display name when present. Otherwise the category supplies the display name.
+- Saved storeys and their elevations. Scene elements reference their home storey when it resolves to a saved level.
+- Verified straight and circular grid axes in project coordinates and metres. The adapter uses the saved home
+ story elevation plus the axis offset to place each axis. Straight axes carry their full endpoints and circular
+ axes carry ordered paths with at most 1 mm of arc-to-chord error. The scene retains saved axis labels and uses
+ the full reference geometry for axes shown in segments or hidden on the Archicad floor plan.
+- A containment parent for a Door whose verified host is a Wall. Other host and cut-target GUIDs are occurrence
+ properties.
+- Supported element, location, classification and quantity properties. Dimensioned numeric values use SI units.
+- Verified Door placement adds reference point X and Y in project coordinates, directed distance along the
+ host wall, and the nominal sill relative to project zero and the wall's home story when available.
+- Verified Door instance tables supply the saved GDL wall-hole width and height.
+- Applicable user-defined literal values grouped by their saved property group. A linked override takes precedence
+ over the default. Unavailable, undefined and expression values are omitted. Single-choice values use the saved
+ choice label.
+- Closed triangle meshes for verified vertical slab solids with straight edges. The mesh uses the saved contours and
+ the footprint of supported through cuts from rectangular columns or separate straight-edged Opening elements.
+ A slab can have holes and multiple connected parts, with one geometry instance per part. Geometry instances use
+ project coordinates in metres with Z up.
+- Closed triangle meshes for verified straight vertical walls with rectangular or straight-edged complex sections.
+ Rectangular walls can include supported through cuts from simple Door openings.
+ When a profile has several material fills, the exterior solid uses their combined section. Each disconnected
+ section yields a geometry instance. The scene property `archicad:wall-net-volume` gives the solid volume.
+- Closed triangle meshes for supported vertical columns, including rectangular sections with planar caps and
+ straight-edged single-fill profiles. A circular section with horizontal caps is tessellated with a sagitta of
+ at most `1e-7` metres, retaining the four axis extrema. A beam cut through the entire section can leave several
+ mesh instances for one column. Supported cuts by horizontal or inclined beams can remove part of a profiled
+ column section and produce a closed cut mesh.
+ The scene property `archicad:column-net-volume` gives the listing volume. Circular columns also expose
+ their analytic volume as `archicad:column-geometric-volume`.
-A geometry-free scene file is a valid scene document: a consumer that reads it shows the model with no content to draw.
+Mesh support is pending for curved slab edges or Opening profiles, partial-depth slab cuts, combinations of Opening
+and structural cuts, joined and cut walls, curved wall sections, wrapped columns and general partial column cuts.
## Frozen derivations
-The consumers of a scene store `SceneModel.Key` together with the source id of an element, so a change of the
-derivation is a breaking release of `PlaIO.Scene`:
+Consumers persist element identity using `SceneModel.Key` and `SceneElement.SourceId`.
- `Key` is `PlaSceneOptions.ModelKey` when given; otherwise the file name with its extension, without its directory.
-- The key never switches to a better identifier. A better identifier, once the format gives the adapter one, goes into
- a new `SceneModel` member, not into the key.
+- `SourceId` is the saved element GUID in lower-case D format.
-The identity tests of the derivation are in `tests/PlaIO.Tests/PlaSceneReaderTests.cs`.
+The adapter uses `archicad:instance` for intrinsic properties. A saved user-defined group has the key
+`archicad:group:` and its definitions use `archicad:property:`. A classification in
+`archicad:classifications` uses `archicad:classification:` and carries the item GUID as text.
## Diagnostics
| Severity | Code | Meaning |
|---|---|---|
-| Info | `container-only` | The reader decodes the container only: elements, properties and geometry are not read yet, so the scene has no elements. |
+| Info | `container-only` | The container has no decoded model elements or grid axes. |
+| Info | `geometry-incomplete` | Reports how many decoded elements have no triangle mesh. |
+| Info | `grid-elevation-unavailable` | Reports grid axes omitted because their elevation relative to project zero is unavailable. |
+| Info | `grid-tessellation-unavailable` | Reports circular grid axes omitted because a path could not be sampled within the error and vertex limits. |
+
+A malformed or ambiguous indexed object class table, invalid grid store or invalid recognized story table raises an error.
## Publication
-The project is `IsPackable=false` and is not published on NuGet: it ships on a `PlaIO` release tag, with an exact
-`[X.Y.Z]` dependency on `PlaIO` and an `IOScene [0.1.1, 0.2.0-0.0)` range, when the reader decodes elements and
-geometry — the adapter trigger of the [target architecture](https://github.com/IOExtend/.github/blob/main/profile/README.md)
-("PlaIO decodes geometry / has elements to export / has a writer"). Until then nothing publishes, so no consumer can
-build on an empty mapping.
+The adapter is available as a project reference. Its project currently has `IsPackable=false`.
+The package configuration specifies an exact PlaIO dependency and an `IOScene [0.1.2, 0.2.0-0.0)` range.
diff --git a/docs/toc.yml b/docs/toc.yml
index 21511c5..7e553a4 100644
--- a/docs/toc.yml
+++ b/docs/toc.yml
@@ -5,6 +5,8 @@
items:
- name: Public API
href: public-api.md
+ - name: Reader parity with RvtIO
+ href: reader-parity.md
- name: Command line and exit codes
href: cli.md
- name: Scene adapter
diff --git a/src/PlaIO.Cli/Cli.cs b/src/PlaIO.Cli/Cli.cs
index aa86abf..7f4eb8d 100644
--- a/src/PlaIO.Cli/Cli.cs
+++ b/src/PlaIO.Cli/Cli.cs
@@ -1,6 +1,7 @@
using PlaIO.Model;
using System.Globalization;
using System.Reflection;
+using System.Text.Json;
namespace PlaIO.CommandLine;
@@ -11,11 +12,21 @@ internal static class Cli
public const int ExitOk = 0;
public const int ExitUsage = 1;
public const int ExitInput = 2;
+ private static readonly JsonSerializerOptions ModelJson = new(JsonSerializerDefaults.Web) { WriteIndented = true };
internal const string UsageText = """
Usage: plaio info
plaio blocks
plaio directory [--out ]
+ plaio elements
+ plaio stories
+ plaio grids
+ plaio layers
+ plaio materials
+ plaio profiles
+ plaio classifications
+ plaio properties
+ plaio layouts
plaio --help | --version
info Kind and length. FDB: header fields (hex), raw header bytes 32..63 (hex),
@@ -26,6 +37,15 @@ offset tag id kind ver flags class mode packed unpacked extra payloadOffset guid
directory FDB only. Searches raw blocks for object directories; prints one summary line
per directory (blockOffset recordOffset phase records abutting overlapping duplicates);
with --out also writes all records as JSON.
+ elements FDB only. Writes recognized elements and available basic parameters as JSON.
+ stories FDB only. Writes the saved project stories as JSON.
+ grids FDB only. Writes supported straight and circular grid axes as JSON.
+ layers FDB only. Writes the saved project layer attributes as JSON.
+ materials FDB only. Writes building materials and composite definitions as JSON.
+ profiles FDB only. Writes complex profile definitions as JSON.
+ classifications FDB only. Writes project classification systems and items as JSON.
+ properties FDB only. Writes user-defined property groups and definitions as JSON.
+ layouts FDB only. Writes the layout book and placed drawing entries as JSON.
Exit codes: 0 done; 1 usage error (no/unknown command or option, missing, empty or extra argument,
--out given twice or without a value);
@@ -46,7 +66,8 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)
string version = typeof(Cli).Assembly.GetCustomAttribute()?.InformationalVersion ?? "unknown";
stdout.WriteLine($"plaio {version.Split('+')[0]}");
return ExitOk;
- case "info" or "blocks" or "directory":
+ case "info" or "blocks" or "directory" or "elements" or "stories" or "grids" or "layers" or "materials" or "profiles"
+ or "classifications" or "properties" or "layouts":
break;
default:
return Usage(stderr, command.StartsWith('-') ? $"Unknown option '{command}'." : $"Unknown command '{command}'.");
@@ -89,6 +110,42 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)
case "blocks":
BlocksCommand(file, stdout);
break;
+ case "elements":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { elements = document.ReadElements() }, ModelJson));
+ break;
+ case "stories":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { stories = document.ReadStories() }, ModelJson));
+ break;
+ case "grids":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { grids = document.ReadGridAxes() }, ModelJson));
+ break;
+ case "layers":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { layers = document.ReadLayers() }, ModelJson));
+ break;
+ case "materials":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(document.ReadMaterialCatalog(), ModelJson));
+ break;
+ case "profiles":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { profiles = document.ReadProfileCatalog() }, ModelJson));
+ break;
+ case "classifications":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { classificationSystems = document.ReadClassificationSystems() }, ModelJson));
+ break;
+ case "properties":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(document.ReadPropertyCatalog(), ModelJson));
+ break;
+ case "layouts":
+ using (var document = PlaDocument.Open(file))
+ stdout.WriteLine(JsonSerializer.Serialize(new { layoutBook = document.ReadLayoutBook() }, ModelJson));
+ break;
default:
DirectoryCommand(file, output, stdout);
break;
diff --git a/src/PlaIO.Scene/PlaExtrusionMesh.cs b/src/PlaIO.Scene/PlaExtrusionMesh.cs
new file mode 100644
index 0000000..c622854
--- /dev/null
+++ b/src/PlaIO.Scene/PlaExtrusionMesh.cs
@@ -0,0 +1,258 @@
+using IOScene;
+using PlaIO.Model;
+
+namespace PlaIO.Scene;
+
+internal static class PlaExtrusionMesh
+{
+ internal static void Add(SceneDocument scene, long elementId, IReadOnlyList prisms,
+ double bottom, double top) =>
+ Add(scene, elementId, prisms.Select(p => p.Rings), new(bottom, 0, 0), new(top, 0, 0), Transform3d.Identity);
+
+ internal static void Add(SceneDocument scene, long elementId, PlaColumnExtrusion column)
+ {
+ var frame = Transform3d.Identity with { Translation = new Vector3d(column.Origin.X, column.Origin.Y, 0) };
+ if (column.CircularRadius is { } radius)
+ {
+ if (CircularBoundary(radius) is { } boundary)
+ Add(scene, elementId, [[boundary]], column.LowerPlane, column.UpperPlane, frame, convex: true);
+ return;
+ }
+ var contours = column.Sections.Select(section => section.Rings);
+ if (column.Spans is null)
+ Add(scene, elementId, contours, column.LowerPlane, column.UpperPlane, frame);
+ else
+ foreach (var span in column.Spans)
+ Add(scene, elementId, contours, new(span.Bottom, 0, 0), new(span.Top, 0, 0), frame);
+ }
+
+ internal static void Add(SceneDocument scene, long elementId, PlaWallExtrusion wall)
+ {
+ double dx = wall.End.X - wall.Start.X, dy = wall.End.Y - wall.Start.Y;
+ double length = double.Hypot(dx, dy);
+ var along = new Vector3d(-dx / length, -dy / length, 0);
+ var right = new Vector3d(dy / length, -dx / length, 0);
+ // Right and up form a right-handed frame when the cap sweep goes from the wall end to its start.
+ var frame = new Transform3d(right, Vector3d.UnitZ, along, new Vector3d(wall.End.X, wall.End.Y, wall.BaseElevation));
+ Add(scene, elementId, wall.Sections.Select(section => (IReadOnlyList>)
+ section.Rings.Select(ring => (IReadOnlyList)ring.Select(p => new PlaPlanPoint(p.U, p.Z)).ToArray()).ToArray()),
+ new(0, 0, 0), new(length, 0, 0), frame);
+ }
+
+ private static void Add(SceneDocument scene, long elementId, IEnumerable>> contours,
+ PlaColumnEndPlane lower, PlaColumnEndPlane upper, Transform3d frame, bool convex = false)
+ {
+ var parts = new List<(Vector3d Origin, Vector3d[] Vertices, List Indices)>();
+ foreach (var rings in contours)
+ {
+ if (Tessellate(rings, lower, upper, convex) is not { } part) return;
+ parts.Add(part);
+ }
+
+ foreach (var (origin, vertices, indices) in parts)
+ {
+ int id = scene.Geometries.Count + 1;
+ scene.Geometries.Add(new SceneGeometry { Id = id, Vertices = vertices, Indices = indices });
+ scene.Instances.Add(new SceneInstance
+ {
+ ElementId = elementId,
+ GeometryId = id,
+ Transform = frame with { Translation = frame.Apply(origin) },
+ });
+ }
+ }
+
+ private static (Vector3d Origin, Vector3d[] Vertices, List Indices)? Tessellate(
+ IReadOnlyList> rings, PlaColumnEndPlane lower, PlaColumnEndPlane upper, bool convex)
+ {
+ var origin = rings[0][0];
+ var points = rings.SelectMany(r => r.Select(p => new PlaPlanPoint(p.X - origin.X, p.Y - origin.Y))).ToArray();
+ var ends = new int[rings.Count + 1];
+ for (int i = 0; i < rings.Count; i++)
+ ends[i + 1] = ends[i] + rings[i].Count;
+
+ var boundary = Enumerable.Range(0, ends[1]).ToList();
+ var holes = Enumerable.Range(1, rings.Count - 1).Select(ring =>
+ (Ring: ring, Vertex: Enumerable.Range(ends[ring], rings[ring].Count).MaxBy(i => points[i].X)));
+ foreach (var (ring, vertex) in holes.OrderByDescending(h => points[h.Vertex].X))
+ if (!BridgeHole(points, ends, boundary, ring, vertex)) return null;
+ if ((convex ? TriangleFan(points.Length) : Triangulate(points, boundary)) is not { } cap) return null;
+
+ int count = points.Length;
+ double bottom = HeightAt(lower, origin);
+ double height = HeightAt(upper, origin) - bottom;
+ var vertices = new Vector3d[2 * count];
+ var indices = new List(cap.Count * 2 + count * 6);
+ for (int i = 0; i < count; i++)
+ {
+ var point = points[i];
+ vertices[i] = new Vector3d(point.X, point.Y, lower.SlopeX * point.X + lower.SlopeY * point.Y);
+ vertices[i + count] = new Vector3d(point.X, point.Y, height + upper.SlopeX * point.X + upper.SlopeY * point.Y);
+ }
+
+ for (int ring = 0; ring < rings.Count; ring++)
+ {
+ for (int i = ends[ring]; i < ends[ring + 1]; i++)
+ {
+ int next = i + 1 < ends[ring + 1] ? i + 1 : ends[ring];
+ indices.Add(i);
+ indices.Add(next);
+ indices.Add(next + count);
+ indices.Add(i);
+ indices.Add(next + count);
+ indices.Add(i + count);
+ }
+ }
+ for (int i = 0; i < cap.Count; i += 3)
+ {
+ indices.Add(cap[i] + count);
+ indices.Add(cap[i + 1] + count);
+ indices.Add(cap[i + 2] + count);
+ indices.Add(cap[i + 2]);
+ indices.Add(cap[i + 1]);
+ indices.Add(cap[i]);
+ }
+
+ return (new Vector3d(origin.X, origin.Y, bottom), vertices, indices);
+ }
+
+ private static PlaPlanPoint[]? CircularBoundary(double radius)
+ {
+ const double maximumSagitta = 1e-7;
+ // Keep the four axis extrema exact. Use the half-angle form for narrow chords.
+ double quarters = Math.Max(4, Math.Ceiling(Math.PI / (8 * Math.Asin(Math.Sqrt(Math.Min(0.5, maximumSagitta / radius / 2))))));
+ if (!(quarters <= 4096)) return null;
+ int steps = (int)quarters;
+ var ring = new PlaPlanPoint[4 * steps];
+ for (int i = 0; i < steps; i++)
+ {
+ var (sin, cos) = Math.SinCos(Math.PI / 2 * i / steps);
+ double x = radius * cos, y = radius * sin;
+ ring[i] = new PlaPlanPoint(x, y);
+ ring[steps + i] = new PlaPlanPoint(-y, x);
+ ring[2 * steps + i] = new PlaPlanPoint(-x, -y);
+ ring[3 * steps + i] = new PlaPlanPoint(y, -x);
+ }
+ return ring;
+ }
+
+ private static List TriangleFan(int count)
+ {
+ var triangles = new List((count - 2) * 3);
+ for (int i = 1; i + 1 < count; i++)
+ {
+ triangles.Add(0);
+ triangles.Add(i);
+ triangles.Add(i + 1);
+ }
+ return triangles;
+ }
+
+ // Open each hole with two opposed edges. They share vertex IDs and disappear inside the triangulated cap.
+ private static bool BridgeHole(PlaPlanPoint[] points, int[] ends, List boundary, int ring, int vertex)
+ {
+ var hole = points[vertex];
+ int best = -1;
+ double bestDistance = double.PositiveInfinity;
+ for (int i = 0; i < boundary.Count; i++)
+ {
+ var target = points[boundary[i]];
+ double distance = double.Hypot(target.X - hole.X, target.Y - hole.Y);
+ if (distance >= bestDistance) continue;
+
+ // A bridge endpoint can occur twice in the boundary. Only one occurrence faces the new hole.
+ var previous = points[boundary[(i + boundary.Count - 1) % boundary.Count]];
+ var next = points[boundary[(i + 1) % boundary.Count]];
+ double left = Cross(previous, target, hole), right = Cross(target, next, hole);
+ bool facesHole = Cross(previous, target, next) >= 0 ? left >= 0 && right >= 0 : left > 0 || right > 0;
+ if (facesHole && IsVisible(points, ends, boundary, hole, target))
+ {
+ best = i;
+ bestDistance = distance;
+ }
+ }
+ if (best < 0) return false;
+
+ int length = ends[ring + 1] - ends[ring];
+ var path = new int[length + 2];
+ for (int i = 0; i <= length; i++)
+ path[i] = ends[ring] + (vertex - ends[ring] + i) % length;
+ path[^1] = boundary[best];
+ boundary.InsertRange(best + 1, path);
+ return true;
+ }
+
+ private static bool IsVisible(PlaPlanPoint[] points, int[] ends, List boundary, PlaPlanPoint a, PlaPlanPoint b)
+ {
+ var midpoint = new PlaPlanPoint(a.X + (b.X - a.X) / 2, a.Y + (b.Y - a.Y) / 2);
+ for (int ring = 0; ring < ends.Length - 1; ring++)
+ {
+ bool inside = false;
+ for (int i = ends[ring], last = ends[ring + 1] - 1; i < ends[ring + 1]; last = i++)
+ {
+ var c = points[last];
+ var d = points[i];
+ if (BlocksBridge(a, b, c, d)) return false;
+ if ((c.Y > midpoint.Y) != (d.Y > midpoint.Y) &&
+ midpoint.X < c.X + (midpoint.Y - c.Y) * (d.X - c.X) / (d.Y - c.Y))
+ inside = !inside;
+ }
+ if (inside != (ring == 0)) return false;
+ }
+ // The joined boundary also contains the previously added bridges.
+ for (int i = 0; i < boundary.Count; i++)
+ if (BlocksBridge(a, b, points[boundary[i]], points[boundary[(i + 1) % boundary.Count]])) return false;
+ return true;
+ }
+
+ private static bool BlocksBridge(PlaPlanPoint a, PlaPlanPoint b, PlaPlanPoint c, PlaPlanPoint d)
+ {
+ if (a == c || a == d) return SharesRay(a, b, a == c ? d : c);
+ if (b == c || b == d) return SharesRay(b, a, b == c ? d : c);
+ if (Math.Max(a.X, b.X) < Math.Min(c.X, d.X) || Math.Max(c.X, d.X) < Math.Min(a.X, b.X) ||
+ Math.Max(a.Y, b.Y) < Math.Min(c.Y, d.Y) || Math.Max(c.Y, d.Y) < Math.Min(a.Y, b.Y)) return false;
+ return Opposite(Cross(a, b, c), Cross(a, b, d)) && Opposite(Cross(c, d, a), Cross(c, d, b));
+
+ static bool SharesRay(PlaPlanPoint origin, PlaPlanPoint p, PlaPlanPoint q) =>
+ Cross(origin, p, q) == 0 && (p.X - origin.X) * (q.X - origin.X) + (p.Y - origin.Y) * (q.Y - origin.Y) > 0;
+
+ static bool Opposite(double x, double y) => (x <= 0 && y >= 0) || (x >= 0 && y <= 0);
+ }
+
+ private static List? Triangulate(PlaPlanPoint[] points, List remaining)
+ {
+ var triangles = new List((remaining.Count - 2) * 3);
+ int i = 0, rejected = 0;
+ while (remaining.Count > 2)
+ {
+ int previous = remaining[(i + remaining.Count - 1) % remaining.Count];
+ int current = remaining[i];
+ int next = remaining[(i + 1) % remaining.Count];
+ var a = points[previous];
+ var b = points[current];
+ var c = points[next];
+ if (Cross(a, b, c) > 0 && !remaining.Any(p => p != previous && p != current && p != next &&
+ Cross(a, b, points[p]) >= 0 && Cross(b, c, points[p]) >= 0 && Cross(c, a, points[p]) >= 0))
+ {
+ triangles.Add(previous);
+ triangles.Add(current);
+ triangles.Add(next);
+ remaining.RemoveAt(i);
+ rejected = 0;
+ }
+ else
+ {
+ if (++rejected == remaining.Count) return null;
+ i++;
+ }
+ i %= remaining.Count;
+ }
+ return triangles;
+ }
+
+ private static double Cross(PlaPlanPoint a, PlaPlanPoint b, PlaPlanPoint p) =>
+ (b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X);
+
+ private static double HeightAt(PlaColumnEndPlane plane, PlaPlanPoint point) =>
+ plane.Elevation + plane.SlopeX * point.X + plane.SlopeY * point.Y;
+}
diff --git a/src/PlaIO.Scene/PlaIO.Scene.csproj b/src/PlaIO.Scene/PlaIO.Scene.csproj
index 99541ab..851a00a 100644
--- a/src/PlaIO.Scene/PlaIO.Scene.csproj
+++ b/src/PlaIO.Scene/PlaIO.Scene.csproj
@@ -1,11 +1,10 @@
- Turns Archicad containers read by PlaIO into IOScene scene documents. Unpublished while the reader decodes only the container; it ships when elements and geometry are read.
+ Turns Archicad elements, properties and supported geometry read by PlaIO into IOScene scene documents.
net8.0;net10.0
true
-
+
false
$(NoWarn);NU5104
diff --git a/src/PlaIO.Scene/PlaSceneOptions.cs b/src/PlaIO.Scene/PlaSceneOptions.cs
index aa58f9a..34c6fe0 100644
--- a/src/PlaIO.Scene/PlaSceneOptions.cs
+++ b/src/PlaIO.Scene/PlaSceneOptions.cs
@@ -4,7 +4,7 @@ namespace PlaIO.Scene;
public sealed class PlaSceneOptions
{
/// The key of the model in the scene (SceneModel.Key). Together with the source ids of the elements it
- /// identifies an element outside the scene once the adapter writes them, so it must stay the same for every conversion
+ /// identifies an element outside the scene, so it must stay the same for every conversion
/// of one file. Null takes the file name with its extension, without its directory.
public string? ModelKey { get; set; }
}
diff --git a/src/PlaIO.Scene/PlaSceneProperties.cs b/src/PlaIO.Scene/PlaSceneProperties.cs
new file mode 100644
index 0000000..559db3a
--- /dev/null
+++ b/src/PlaIO.Scene/PlaSceneProperties.cs
@@ -0,0 +1,176 @@
+using System.Globalization;
+using IOScene;
+using PlaIO.Model;
+
+namespace PlaIO.Scene;
+
+internal sealed class PlaSceneProperties(PlaPropertyCatalog catalog)
+{
+ private readonly Dictionary groupNames = catalog.Groups.ToDictionary(group => group.Guid, group => group.Name);
+ private readonly ILookup available = catalog.Definitions
+ .SelectMany(definition => definition.AvailableClassificationItemGuids.Select(item => (item, definition)))
+ .ToLookup(pair => pair.item, pair => pair.definition);
+
+ internal void Map(SceneDocument scene, PlaElement element, SceneElement mapped)
+ {
+ AddSet(scene, mapped, "archicad:instance", "Archicad element", NativeProperties(element));
+ if (element.Classifications is not { Count: > 0 } assignments) return;
+
+ AddSet(scene, mapped, "archicad:classifications", "Archicad classifications", assignments.Select(assignment =>
+ new SceneProperty
+ {
+ Key = $"archicad:classification:{assignment.SystemGuid:D}",
+ Name = $"Classification {assignment.SystemGuid:D}",
+ Value = SceneValue.FromText(assignment.ItemGuid.ToString("D")),
+ }).ToList());
+ var overrides = element.PropertyOverrides?.ToDictionary(entry => entry.DefinitionGuid);
+ foreach (var group in assignments.SelectMany(assignment => available[assignment.ItemGuid])
+ .DistinctBy(definition => definition.Guid).OrderBy(definition => definition.Guid)
+ .GroupBy(definition => definition.GroupGuid))
+ {
+ var properties = new List();
+ foreach (var definition in group)
+ {
+ var saved = overrides is not null && overrides.TryGetValue(definition.Guid, out var entry)
+ ? entry.Value : definition.DefaultValue;
+ if (ToSceneValue(definition, saved) is { } value)
+ properties.Add(new SceneProperty
+ {
+ Key = $"archicad:property:{definition.Guid:D}",
+ Name = definition.Name,
+ Value = value,
+ });
+ }
+ AddSet(scene, mapped, $"archicad:group:{group.Key:D}", groupNames[group.Key], properties);
+ }
+ }
+
+ private static void AddSet(SceneDocument scene, SceneElement element, string key, string name,
+ List properties)
+ {
+ if (properties.Count == 0) return;
+ int id = scene.PropertySets.Count + 1;
+ scene.PropertySets.Add(new ScenePropertySet { Id = id, Key = key, Name = name, Properties = properties });
+ element.PropertySetIds.Add(id);
+ }
+
+ private static List NativeProperties(PlaElement element)
+ {
+ var properties = new List();
+ Text("element-id", "Element ID", element.ElementId);
+ Text("layer", "Layer", element.LayerName);
+ Integer("layer-index", "Layer index", element.LayerIndex);
+ Text("home-story", "Home story", element.HomeStoryName);
+ Integer("home-story-index", "Home story index", element.HomeStoryIndex);
+ Integer("top-linked-story-index", "Top linked story index", element.TopLinkedStoryIndex);
+ Integer("building-material-index", "Building material index", element.BuildingMaterialIndex);
+ Integer("composite-index", "Composite index", element.CompositeIndex);
+ Integer("profile-index", "Profile index", element.WallProfile?.ProfileIndex ?? element.MemberProfile?.ProfileIndex);
+ Text("host-guid", "Host GUID", element.HostGuid?.ToString("D"));
+ if (element.OpeningCutElementGuids is { } cutTargets)
+ Text("opening-cut-guids", "Opening cut GUIDs", string.Join(", ", cutTargets));
+ Number("bottom-to-project-zero", "Bottom elevation to project zero", element.BottomElevationToProjectZero);
+ Number("top-to-project-zero", "Top elevation to project zero", element.TopElevationToProjectZero);
+ Number("bottom-to-home-story", "Bottom elevation to home story", element.BottomElevationToHomeStory);
+ Number("top-to-home-story", "Top elevation to home story", element.TopElevationToHomeStory);
+ Number("wall-thickness", "Wall thickness", element.WallThickness);
+ Number("wall-reference-chord", "Wall reference line chord", element.WallReferenceLineChordLength);
+ if (element.DoorDimensions is { } door)
+ {
+ Number("door-width", "Nominal door width", door.Width);
+ Number("door-height", "Nominal door height", door.Height);
+ Number("door-sill-from-anchor", "Door sill height from anchor", door.SillHeightFromAnchor);
+ }
+ if (element.DoorPlacement is { } placement)
+ {
+ Number("door-reference-x", "Door reference point X", placement.ReferencePoint.X);
+ Number("door-reference-y", "Door reference point Y", placement.ReferencePoint.Y);
+ Number("door-distance-along-wall", "Door distance along host wall", placement.DistanceAlongWall);
+ Number("door-sill-to-project-zero", "Nominal door sill to project zero", placement.SillElevationToProjectZero);
+ Number("door-sill-to-host-story", "Nominal door sill to host story", placement.SillElevationToHostStory);
+ }
+ if (element.DoorWallHoleDimensions is { } wallHole)
+ {
+ Number("door-wall-hole-width", "Saved door wall-hole width", wallHole.Width);
+ Number("door-wall-hole-height", "Saved door wall-hole height", wallHole.Height);
+ }
+ if (element.OpeningProfile is { } opening)
+ {
+ Text("opening-shape", "Opening shape", opening.Shape);
+ Number("opening-width", "Opening profile width", opening.Width);
+ Number("opening-height", "Opening profile height", opening.Height);
+ }
+ if (element.BoundingBox is { } bounds)
+ {
+ Number("bounds-min-x", "Minimum X", bounds.XMin);
+ Number("bounds-min-y", "Minimum Y", bounds.YMin);
+ Number("bounds-min-z", "Minimum Z", bounds.ZMin);
+ Number("bounds-max-x", "Maximum X", bounds.XMax);
+ Number("bounds-max-y", "Maximum Y", bounds.YMax);
+ Number("bounds-max-z", "Maximum Z", bounds.ZMax);
+ }
+ if (element.SlabGeometry is { } slab)
+ {
+ Number("slab-outline-area", "Saved slab outline area", slab.OutlineArea, SceneUnits.SquareMetre);
+ Number("slab-top-area", "Slab top area with openings", slab.TopAreaWithOpenings, SceneUnits.SquareMetre);
+ Number("slab-bottom-area", "Slab bottom area with openings", slab.BottomAreaWithOpenings, SceneUnits.SquareMetre);
+ Number("slab-perimeter", "Saved slab perimeter", slab.FloorPlanPerimeter);
+ Number("slab-hole-perimeter", "Saved slab hole perimeter", slab.FloorPlanHolesPerimeter);
+ Number("slab-net-volume", "Slab net volume", slab.Volume, SceneUnits.CubicMetre);
+ }
+ Number("wall-net-volume", "Wall net volume", element.WallExtrusion?.Volume, SceneUnits.CubicMetre);
+ if (element.ColumnExtrusion is { CircularRadius: not null } cylinder)
+ {
+ Number("column-geometric-volume", "Column geometric volume", cylinder.Volume, SceneUnits.CubicMetre);
+ Number("column-net-volume", "Column net volume", cylinder.ScheduledVolume, SceneUnits.CubicMetre);
+ }
+ else
+ Number("column-net-volume", "Column net volume", element.ColumnExtrusion?.Volume ?? element.ColumnCutMesh?.Volume, SceneUnits.CubicMetre);
+ Number("beam-net-volume", "Beam net volume", element.BeamNetVolume, SceneUnits.CubicMetre);
+ Number("beam-reference-length", "Beam reference axis length", element.BeamReferenceAxis?.Length);
+ Number("beam-inclination", "Beam inclination", element.BeamReferenceAxis?.InclinationRadians, SceneUnits.Radian);
+ Number("opening-cut-volume", "Opening cut volume", element.OpeningGeometry?.CutVolume, SceneUnits.CubicMetre);
+ return properties;
+
+ void Add(string key, string name, SceneValue value) =>
+ properties.Add(new SceneProperty { Key = "archicad:" + key, Name = name, Value = value });
+ void Text(string key, string name, string? value)
+ {
+ if (value is not null) Add(key, name, SceneValue.FromText(value));
+ }
+ void Integer(string key, string name, int? value)
+ {
+ if (value is int n) Add(key, name, IntegerValue(n));
+ }
+ void Number(string key, string name, double? value, string unit = SceneUnits.Metre)
+ {
+ if (value is double n && double.IsFinite(n)) Add(key, name, NumberValue(n, unit));
+ }
+ }
+
+ private static SceneValue? ToSceneValue(PlaPropertyDefinition definition, PlaPropertyValue? saved)
+ {
+ if (saved is not { Status: "normal" }) return null;
+ return (definition.DataType, saved.Value) switch
+ {
+ ("string", string text) => SceneValue.FromText(text),
+ ("integer", int number) => IntegerValue(number),
+ ("number", double number) when double.IsFinite(number) => NumberValue(number, null),
+ ("length", double number) when double.IsFinite(number) => NumberValue(number, SceneUnits.Metre),
+ ("area", double number) when double.IsFinite(number) => NumberValue(number, SceneUnits.SquareMetre),
+ ("volume", double number) when double.IsFinite(number) => NumberValue(number, SceneUnits.CubicMetre),
+ ("singleEnum", Guid id) when definition.Choices?.FirstOrDefault(choice => choice.Guid == id) is { } choice =>
+ SceneValue.FromText(choice.DisplayValue),
+ _ => null,
+ };
+ }
+
+ private static SceneValue IntegerValue(int value) =>
+ SceneValue.FromInteger(value, value.ToString(CultureInfo.InvariantCulture));
+
+ private static SceneValue NumberValue(double value, string? unit)
+ {
+ string text = value.ToString(CultureInfo.InvariantCulture);
+ return SceneValue.FromNumber(value, unit, unit is null ? text : $"{text} {unit}");
+ }
+}
diff --git a/src/PlaIO.Scene/PlaSceneReader.cs b/src/PlaIO.Scene/PlaSceneReader.cs
index 2a38782..15b0892 100644
--- a/src/PlaIO.Scene/PlaSceneReader.cs
+++ b/src/PlaIO.Scene/PlaSceneReader.cs
@@ -1,25 +1,22 @@
using System.Reflection;
using IOScene;
+using PlaIO.Model;
namespace PlaIO.Scene;
///
-/// Turns an Archicad container (a .pla or .pln file) into a scene (): one model for the file,
-/// without elements, properties or geometry while the container reader does not decode them yet.
+/// Turns an Archicad container (a .pla or .pln file) into a scene () with its decoded
+/// elements, levels, grids, properties and supported meshes.
///
///
-/// The model's Key is the , else the file name without its directory.
-/// The derivation is frozen: the key never switches to a better identifier, and the elements this adapter will write get
-/// their persisted identity from it. SourceFormat is the lower-case file extension (pla or pln),
-/// Producer this assembly's name and version.
-/// The scene holds no guesses: what the container reader cannot decode yet (element contents, class names, the
-/// meaning of the object directory records) is not written, and the container-only diagnostic says so.
+/// The persisted identity is the model key together with the saved Archicad element GUID in D format.
+/// The model uses the supplied or the file name with its extension.
///
public static class PlaSceneReader
{
private const int ModelId = 1;
- /// Reads the container at and turns it into a scene.
+ /// Reads the container at and converts the decoded model to a scene.
/// is empty, or is empty.
public static PlaSceneResult Read(string path, PlaSceneOptions? options = null)
{
@@ -41,15 +38,120 @@ private static PlaSceneResult Map(string path, string key)
SourceFormat = SourceFormat(path),
Producer = Producer,
});
- return new PlaSceneResult
+ bool hasClassTable = document.HasObjectClassTable;
+ var diagnostics = new List();
+ var levels = new Dictionary();
+ foreach (var story in hasClassTable ? document.ReadStories() : [])
{
- Document = scene,
- Diagnostics =
- [
- new(SceneSeverity.Info, "container-only",
- "The reader decodes the container only: elements, properties and geometry are not read yet, so the scene has no elements."),
- ],
- };
+ int id = scene.Levels.Count + 1;
+ levels.Add(story.Index, id);
+ scene.Levels.Add(new SceneLevel { Id = id, ModelId = ModelId, Name = story.Name, Elevation = story.ElevationToProjectZero });
+ }
+
+ if (hasClassTable) AddGrids(scene, document.ReadGridAxes(), diagnostics);
+ var elements = hasClassTable ? document.ReadElements() : [];
+ if (elements.Count == 0)
+ {
+ if (scene.Grids.Count == 0 && diagnostics.Count == 0)
+ diagnostics.Add(new(SceneSeverity.Info, "container-only", "The model contains no decoded elements."));
+ return new PlaSceneResult { Document = scene, Diagnostics = diagnostics.AsReadOnly() };
+ }
+
+ var properties = new PlaSceneProperties(document.ReadPropertyCatalog());
+ var byGuid = new Dictionary(elements.Count);
+ foreach (var element in elements)
+ {
+ var mapped = new SceneElement
+ {
+ Id = scene.Elements.Count + 1,
+ ModelId = ModelId,
+ SourceId = element.Guid.ToString("D"),
+ Name = string.IsNullOrEmpty(element.ElementId) ? element.Type : element.ElementId,
+ Category = element.Type,
+ LevelId = element.HomeStoryIndex is { } index && levels.TryGetValue(index, out int level) ? level : null,
+ };
+ scene.Elements.Add(mapped);
+ byGuid.Add(element.Guid, mapped);
+ properties.Map(scene, element, mapped);
+ if (element.SlabGeometry is { VerticalPrisms: { } prisms } slab)
+ PlaExtrusionMesh.Add(scene, mapped.Id, prisms, slab.Bottom, slab.Top);
+ if (element.WallExtrusion is { } wall)
+ PlaExtrusionMesh.Add(scene, mapped.Id, wall);
+ if (element.ColumnExtrusion is { } column)
+ PlaExtrusionMesh.Add(scene, mapped.Id, column);
+ if (element.ColumnCutMesh is { } cut)
+ {
+ int geometryId = scene.Geometries.Count + 1;
+ scene.Geometries.Add(new SceneGeometry
+ {
+ Id = geometryId,
+ Vertices = cut.Vertices.Select(p => new Vector3d(p.X, p.Y, p.Z)).ToArray(),
+ Indices = cut.Indices,
+ });
+ scene.Instances.Add(new SceneInstance
+ {
+ ElementId = mapped.Id,
+ GeometryId = geometryId,
+ Transform = Transform3d.Identity with { Translation = new Vector3d(cut.Origin.X, cut.Origin.Y, cut.Origin.Z) },
+ });
+ }
+ }
+
+ foreach (var element in elements)
+ {
+ if (element.Type == "Door" && element.HostGuid is { } host &&
+ byGuid.TryGetValue(host, out var parent) && parent.Category == "Wall")
+ byGuid[element.Guid].ParentId = parent.Id;
+ }
+
+ int withoutMesh = elements.Count - scene.Instances.Select(i => i.ElementId).Distinct().Count();
+ if (withoutMesh > 0)
+ diagnostics.Add(new(SceneSeverity.Info, "geometry-incomplete", FormattableString.Invariant(
+ $"Triangle meshes are unavailable for {withoutMesh} of {elements.Count} decoded elements.")));
+ return new PlaSceneResult { Document = scene, Diagnostics = diagnostics.AsReadOnly() };
+ }
+
+ private static void AddGrids(SceneDocument scene, IReadOnlyList axes, List diagnostics)
+ {
+ const double gridChordErrorMetres = 0.001;
+ var grid = new SceneGridSystem { ModelId = ModelId };
+ int missingElevation = 0, untessellated = 0;
+ foreach (var axis in axes)
+ {
+ if (axis.ElevationToProjectZero is not { } elevation)
+ {
+ missingElevation++;
+ continue;
+ }
+
+ if (axis.Arc is null)
+ {
+ grid.Lines.Add(new SceneGridLine
+ {
+ Name = axis.Label,
+ Start = new Vector3d(axis.Start.X, axis.Start.Y, elevation),
+ End = new Vector3d(axis.End.X, axis.End.Y, elevation),
+ Elevation = elevation,
+ });
+ }
+ else if (axis.Tessellate(gridChordErrorMetres) is { } samples)
+ {
+ (grid.Paths ??= []).Add(new SceneGridPath
+ {
+ Name = axis.Label,
+ Points = samples.Select(point => new Vector3d(point.X, point.Y, elevation)).ToList(),
+ });
+ }
+ else untessellated++;
+ }
+
+ if (grid.Lines.Count > 0 || grid.Paths is { Count: > 0 }) scene.Grids.Add(grid);
+ if (missingElevation > 0)
+ diagnostics.Add(new(SceneSeverity.Info, "grid-elevation-unavailable", FormattableString.Invariant(
+ $"Project elevations are unavailable for {missingElevation} of {axes.Count} decoded grid axes.")));
+ if (untessellated > 0)
+ diagnostics.Add(new(SceneSeverity.Info, "grid-tessellation-unavailable", FormattableString.Invariant(
+ $"A path could not be sampled for {untessellated} of {axes.Count} decoded grid axes.")));
}
private static string? SourceFormat(string path)
diff --git a/src/PlaIO.Scene/PlaSceneResult.cs b/src/PlaIO.Scene/PlaSceneResult.cs
index 00177bb..b5f5a10 100644
--- a/src/PlaIO.Scene/PlaSceneResult.cs
+++ b/src/PlaIO.Scene/PlaSceneResult.cs
@@ -5,10 +5,9 @@ namespace PlaIO.Scene;
/// The scene made from one Archicad container by , and what the read reported.
public sealed class PlaSceneResult
{
- /// The scene: one model, without elements while the reader decodes only the container.
+ /// The converted model and its available scene data.
public required SceneDocument Document { get; init; }
- /// What the scene does not hold yet: container-only while elements, properties and geometry are not
- /// read. Empty when the container was read whole.
+ /// Conversion diagnostics for empty scenes or incomplete mesh and grid coverage.
public IReadOnlyList Diagnostics { get; init; } = [];
}
diff --git a/src/PlaIO/Internal/BlockScanner.cs b/src/PlaIO/Internal/BlockScanner.cs
index d5cfb08..c294c13 100644
--- a/src/PlaIO/Internal/BlockScanner.cs
+++ b/src/PlaIO/Internal/BlockScanner.cs
@@ -2,7 +2,7 @@
namespace PlaIO.Internal;
-/// Builds the block index in one forward pass: from offset 32, look for a "BL" or "DY" tag, accept a block whose
+/// Builds the block index in one forward pass: from the starting offset, look for a "BL" or "DY" tag, accept a block whose
/// header passes , continue at the end of its payload (the payload is skipped, not
/// read), otherwise move one byte on. Memory is one window buffer plus the list.
/// The step is one byte: blocks are not aligned and may start at any offset, so a two-byte step would miss blocks
@@ -26,12 +26,12 @@ public BlockScanner(Stream stream, long length, int windowSize = 1 << 20, int ma
_maxBlocks = maxBlocks;
}
- public List Scan()
+ public List Scan(long startOffset = FdbFormat.FirstBlockOffset)
{
var blocks = new List();
var buffer = new byte[_windowSize + FdbFormat.MaxBlockHeaderLength];
long winStart = 0, winEnd = 0;
- long pos = FdbFormat.FirstBlockOffset;
+ long pos = startOffset;
// The next "BL" and "DY" at or after pos in the current window (searchEnd when there is none); -1 means search again.
long nextBl = -1, nextDy = -1;
while (pos + FdbFormat.MinBlockHeaderLength <= _length)
diff --git a/src/PlaIO/Internal/ElementReader.BeamArcCaps.cs b/src/PlaIO/Internal/ElementReader.BeamArcCaps.cs
new file mode 100644
index 0000000..002e625
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamArcCaps.cs
@@ -0,0 +1,155 @@
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ // In the plane of the sweep the cap follows the intersection of equal offsets of the two axes.
+ // Each point has coordinates (A + B*u, Side*sqrt(C + D*u + E*u*u)) in this local basis.
+ private readonly record struct BeamArcCap(PlaPlanPoint Center, PlaPlanPoint Direction, double A, double B,
+ double Side, double C, double D, double E)
+ {
+ public static BeamArcCap Radial(SlabEdge arc, PlaPlanPoint end, double radialSign) =>
+ new(arc.Center, UnitFrom(arc.Center, end), arc.Radius, radialSign, 0, 0, 0, 0);
+
+ public static BeamArcCap? AtJoint(SlabEdge arc, PlaBeamReferenceAxis peer, PlaPlanPoint joint, int side,
+ BeamVector ownNormal, BeamVector peerNormal)
+ {
+ double radialSign = -Math.Sign(arc.Sweep);
+ bool collinear = Math.Abs(ownNormal.X + peerNormal.X) <= JunctionTolerance &&
+ Math.Abs(ownNormal.Y + peerNormal.Y) <= JunctionTolerance;
+ if (collinear) return Radial(arc, joint, radialSign);
+
+ double b;
+ PlaPlanPoint direction;
+ if (peer.PlanSweepRadians == 0)
+ {
+ double forward = side == 0 ? 1 : -1;
+ direction = new(-forward * peerNormal.Y, forward * peerNormal.X);
+ b = 1;
+ }
+ else
+ {
+ if (ReadCircularEdge(peer.Start, peer.End, peer.PlanSweepRadians, out _) is not { } other)
+ return null;
+ double distance = Distance(arc.Center, other.Center);
+ if (distance <= JunctionTolerance) return null;
+ direction = UnitFrom(arc.Center, other.Center);
+ b = (arc.Radius * radialSign + other.Radius * Math.Sign(other.Sweep)) / distance;
+ }
+
+ var delta = new PlaPlanPoint(joint.X - arc.Center.X, joint.Y - arc.Center.Y);
+ double a = delta.X * direction.X + delta.Y * direction.Y;
+ double h = -delta.X * direction.Y + delta.Y * direction.X;
+ if (Math.Abs(h) <= JunctionTolerance) return null;
+ return new BeamArcCap(arc.Center, direction, a, b, Math.Sign(h), h * h,
+ 2 * (arc.Radius * radialSign - a * b), 1 - b * b);
+ }
+
+ public PlaPlanPoint Point(double u)
+ {
+ double x = A + B * u;
+ double y = Side * Math.Sqrt(Math.Max(0, Discriminant(u)));
+ return new(Center.X + Direction.X * x - Direction.Y * y, Center.Y + Direction.Y * x + Direction.X * y);
+ }
+
+ public bool StaysNear(PlaPlanPoint nominal, double angle, double min, double max)
+ {
+ if (!(Discriminant(min) >= 0 && Discriminant(max) >= 0)) return false;
+ double vertex = -D / (2 * E);
+ if (E > 0 && vertex > min && vertex < max && !(Discriminant(vertex) > 0)) return false;
+
+ var ray = UnitFrom(Center, nominal);
+ var first = new PlaPlanPoint(Math.Sin(angle) * ray.X - Math.Cos(angle) * ray.Y,
+ Math.Sin(angle) * ray.Y + Math.Cos(angle) * ray.X);
+ var second = new PlaPlanPoint(first.X + 2 * Math.Cos(angle) * ray.Y,
+ first.Y - 2 * Math.Cos(angle) * ray.X);
+ return StaysInside(first, min, max) && StaysInside(second, min, max);
+ }
+
+ private bool StaysInside(PlaPlanPoint normal, double min, double max)
+ {
+ foreach (double u in ExtremeOffsets(normal, min, max))
+ {
+ var point = Point(u);
+ if (!((point.X - Center.X) * normal.X + (point.Y - Center.Y) * normal.Y > JunctionTolerance))
+ return false;
+ }
+ return true;
+ }
+
+ public IEnumerable ExtremeOffsets(PlaPlanPoint projection, double min, double max)
+ {
+ yield return min;
+ yield return max;
+ if (Side == 0) yield break;
+ // Squaring the derivative gives a quadratic. Extra roots are still points on the cap.
+ double linear = B * (Direction.X * projection.X + Direction.Y * projection.Y);
+ double radical = -Direction.Y * projection.X + Direction.X * projection.Y;
+ double weight = linear * linear - radical * radical * E;
+ double a = 4 * E * weight, b = 4 * D * weight;
+ double c = 4 * linear * linear * C - radical * radical * D * D;
+ if (a == 0)
+ {
+ double root = -c / b;
+ if (root > min && root < max) yield return root;
+ yield break;
+ }
+ double square = b * b - 4 * a * c;
+ if (square < 0) yield break;
+ double numerator = -(b + Math.CopySign(Math.Sqrt(square), b)) / 2;
+ double first = numerator / a, second = c / numerator;
+ if (first > min && first < max) yield return first;
+ if (second > min && second < max) yield return second;
+ }
+
+ private double Discriminant(double u) => C + u * (D + E * u);
+
+ private static PlaPlanPoint UnitFrom(PlaPlanPoint from, PlaPlanPoint to)
+ {
+ double length = Distance(from, to);
+ return new((to.X - from.X) / length, (to.Y - from.Y) / length);
+ }
+ }
+
+ private static PlaBoundingBox? CurvedBeamPlan(SlabEdge arc, BeamArcCap start, BeamArcCap end,
+ double min, double max, Elevations height, Func survives)
+ {
+ var points = new List<(PlaPlanPoint Point, double U)>();
+ foreach (var cap in new[] { start, end })
+ {
+ foreach (double u in cap.ExtremeOffsets(new(1, 0), min, max)) points.Add((cap.Point(u), u));
+ foreach (double u in cap.ExtremeOffsets(new(0, 1), min, max)) points.Add((cap.Point(u), u));
+ }
+
+ // At an interior angle each plan coordinate is linear in the radius.
+ foreach (double u in new[] { min, max })
+ {
+ var first = start.Point(u);
+ var last = end.Point(u);
+ double angle = Math.Atan2(first.Y - arc.Center.Y, first.X - arc.Center.X);
+ double sweep = Math.Sign(arc.Sweep) * ForwardAngle(Math.Sign(arc.Sweep) *
+ (Math.Atan2(last.Y - arc.Center.Y, last.X - arc.Center.X) - angle));
+ var edge = new SlabEdge(first, last, sweep, arc.Center, arc.Radius - Math.Sign(arc.Sweep) * u);
+ for (int i = 0; i < 4; i++)
+ {
+ double cardinal = i * (Math.PI / 2);
+ double travel = ForwardAngle(Math.Sign(sweep) * (cardinal - angle));
+ if (travel <= Math.Abs(sweep)) points.Add((edge.AtAngle(cardinal), u));
+ }
+ }
+ double x0 = points.Min(p => p.Point.X), x1 = points.Max(p => p.Point.X);
+ double y0 = points.Min(p => p.Point.Y), y1 = points.Max(p => p.Point.Y);
+ return Witness(p => p.X, x0) && Witness(p => p.X, x1) && Witness(p => p.Y, y0) && Witness(p => p.Y, y1)
+ ? MakeBoundingBox((x0, y0, x1, y1), height.Bottom, height.Top) : null;
+
+ bool Witness(Func coordinate, double extreme) =>
+ points.Any(p => Math.Abs(coordinate(p.Point) - extreme) <= JunctionTolerance && survives(p.Point, p.U));
+
+ static double ForwardAngle(double radians)
+ {
+ radians %= Math.Tau;
+ return radians < 0 ? radians + Math.Tau : radians;
+ }
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamBounds.cs b/src/PlaIO/Internal/ElementReader.BeamBounds.cs
new file mode 100644
index 0000000..5906403
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamBounds.cs
@@ -0,0 +1,243 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static Elevations? ReadBeamGeometry(ReadOnlySpan record, Guid owner, ModelGeometry geometry,
+ PlaMemberProfile? profile, PlaBeamReferenceAxis? reference, double home, out PlaBoundingBox? boundingBox, out double? netVolume)
+ {
+ boundingBox = null;
+ netVolume = null;
+ if (reference is { PlanSweepRadians: not 0 } axis && profile is not null)
+ return ReadCurvedBeamGeometry(record, owner, geometry, axis, profile, home, out boundingBox);
+
+ Guid id = ReadBeamPrismMemo(record, owner, geometry);
+ if (geometry.Read(id, BeamMemoClass) is not { } memo ||
+ ReadStraightBeamAxis(geometry, id, memo, 0, out var planes) is not { } beam || beam.Owner != owner)
+ return null;
+
+ var hatch = ReadBeamHatch(geometry, id, memo);
+ if (planes.HasSquareHorizontalEnds(beam))
+ {
+ boundingBox = ReadBeamBoundingBox(geometry, id, memo, beam, hatch, out netVolume);
+ if (boundingBox is null && profile is not null && BeamProfileIsFullyCovered(geometry, id, memo, beam, profile))
+ {
+ netVolume = 0;
+ return null;
+ }
+ return boundingBox is { } box ? CheckedElevations(box.ZMin - home, box.ZMax - home)
+ : ReadBeamElevations(geometry, id, memo, beam, planes, hatch, profile, home, null, out boundingBox);
+ }
+ if (ProjectBeamCaps(beam, planes, hatch, profile) is not { } caps) return null;
+ if (planes.Rise == 0)
+ return ReadBeamElevations(geometry, id, memo, beam, planes, hatch, profile, home, caps, out boundingBox);
+
+ uint priority = ReadBeamSectionPriority(geometry, hatch, profile);
+ bool keepsVolume = true;
+ bool hasButtJoint = false;
+ if (!HasOnlyBeamTargetContact(memo, Guid.Empty, Guid.Empty, owner, KeepsEndPlanes)) return null;
+ boundingBox = caps.Bounds;
+ if (keepsVolume && planes.StartNormal + planes.EndNormal == default)
+ {
+ double area = profile?.Components is [{ Arcs: null } component] ? component.CrossSectionArea
+ : ReadBeamRectangle(hatch) is { } rectangle ? 2 * rectangle.HalfWidth * rectangle.Depth : 0;
+ double volume = area * double.Hypot(beam.Length, planes.Rise);
+ if (double.IsFinite(volume) && volume > 0) netVolume = volume;
+ }
+ // Schedule elevations at an inclined butt joint can include a limit from the adjoining beam.
+ return hasButtJoint ? null : CheckedElevations(caps.Bounds.ZMin - home, caps.Bounds.ZMax - home);
+
+ bool KeepsEndPlanes(Guid relation, Guid junction)
+ {
+ if (relation == BeamColumnRelation && TryReadBeamColumnCut(geometry, id, junction, priority, out var plan))
+ return plan is null || BeamPlanIsDisjoint(plan.Value, caps.Bounds);
+ if (relation == BeamWallRelation || relation == BeamSlabRelation)
+ {
+ if (priority > 0 && BeamWinsContact(geometry, id, relation, junction, priority)) return true;
+ keepsVolume = false;
+ return relation == BeamWallRelation && ProfileWallLeavesBeamCaps(geometry, id, beam.Layer, junction, priority, caps);
+ }
+ keepsVolume = false;
+ hasButtJoint = true;
+ if (!IsBeamEndRelation(relation) || ReadBeamAxisJunction(geometry, id, relation, junction) is not { } joint ||
+ !IsBeamEndRelation(joint.Reciprocal) || geometry.Read(joint.Peer, BeamMemoClass) is not { } peerMemo ||
+ ReadStraightBeamAxis(geometry, joint.Peer, peerMemo, 0, out var peerPlanes) is not { } peer ||
+ !SameIntersectionGroup(geometry, beam.Layer, peer.Layer) ||
+ !BeamsMeetAtVerticalButt(beam, planes, peer, peerPlanes, joint.X, joint.Y))
+ return false;
+
+ return HasOnlyBeamTargetContact(peerMemo, joint.Reciprocal, junction, peer.Owner, KeepsButtPlane);
+
+ bool KeepsButtPlane(Guid role, Guid otherJunction)
+ {
+ if (role == BeamSlabRelation || role == BeamWallRelation || role == BeamColumnRelation) return true;
+ if (ReadBeamAxisJunction(geometry, joint.Peer, role, otherJunction) is not { } other) return false;
+ if (other.Peer == id)
+ return role == joint.Reciprocal && other.Reciprocal == relation &&
+ Math.Abs(other.X - joint.X) <= JunctionTolerance && Math.Abs(other.Y - joint.Y) <= JunctionTolerance &&
+ HasGeometryRelation(memo, relation, otherJunction);
+ if (!IsBeamEndRelation(role) || !IsOnBeamJoint(peer, other.X, other.Y, end: true) ||
+ geometry.Read(other.Peer, BeamMemoClass) is not { } beyondMemo ||
+ !HasGeometryRelation(beyondMemo, other.Reciprocal, otherJunction) ||
+ ReadBeamPrism(geometry, other.Peer, beyondMemo, 0) is not { } beyond ||
+ !SameIntersectionGroup(geometry, peer.Layer, beyond.Layer) ||
+ !IsOnBeamJoint(beyond, other.X, other.Y, IsBeamEndRelation(other.Reciprocal)) ||
+ ReadBeamContactExtents(geometry, joint.Peer, peerMemo, peer) is not { } peerSection ||
+ ReadBeamContactExtents(geometry, other.Peer, beyondMemo, beyond) is not { } outside ||
+ ProjectBeamJunctionInterval(peer, beyond, other.X, other.Y, peerSection.Left, peerSection.Right,
+ outside.Left, outside.Right) is not { } reach)
+ return false;
+ double commonEnd = (joint.X - peer.X) * peer.Dx + (joint.Y - peer.Y) * peer.Dy;
+ return commonEnd < reach.Min - JunctionTolerance || commonEnd > reach.Max + JunctionTolerance;
+ }
+ }
+ }
+
+ private static PlaBoundingBox? ReadBeamBoundingBox(ModelGeometry geometry, Guid id, byte[] memo, BeamPrism beam,
+ ReadOnlySpan hatch, out double? netVolume)
+ {
+ netVolume = null;
+ if (BeamSectionExtents(beam, hatch) is not { } section) return null;
+ var rectangle = ReadBeamRectangle(hatch);
+ int material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]);
+ double start = 0, stop = beam.Length;
+ double startClear = 0, stopClear = beam.Length, interiorStart = beam.Length, interiorStop = 0;
+ bool startJoined = false, stopJoined = false;
+ double volumeLength = beam.Length;
+ bool volumeSupported = true;
+ if (!HasOnlyBeamTargetContact(memo, Guid.Empty, Guid.Empty, beam.Owner, ReadContact) ||
+ startClear >= stopClear || interiorStart < startClear || interiorStop > stopClear)
+ return null;
+
+ var box = MakeBeamBox(beam, section, start, stop);
+ if (box is not null && volumeSupported && rectangle is { } rectangular)
+ {
+ double value = 2 * rectangular.HalfWidth * rectangular.Depth * volumeLength;
+ if (double.IsFinite(value) && value > 0) netVolume = value;
+ }
+ return box;
+
+ bool ReadContact(Guid relation, Guid junction)
+ {
+ if (geometry.Attributes.Material.GetValueOrDefault(material) is not (> 0 and { } priority)) return false;
+ if (relation == BeamSlabRelation || relation == BeamWallRelation || relation == BeamColumnRelation)
+ return BeamWinsContact(geometry, id, relation, junction, priority);
+ if (rectangle is not { } own || Math.Abs(beam.SinRoll) > JunctionTolerance ||
+ ReadBeamAxisJunction(geometry, id, relation, junction) is not { } joint ||
+ geometry.Read(joint.Peer, BeamMemoClass) is not { } otherMemo ||
+ !HasGeometryRelation(otherMemo, joint.Reciprocal, junction) ||
+ ReadBeamPrism(geometry, joint.Peer, otherMemo, 0) is not { } other ||
+ Math.Abs(other.SinRoll) > JunctionTolerance || !SameIntersectionGroup(geometry, beam.Layer, other.Layer))
+ return false;
+
+ var otherHatch = ReadBeamHatch(geometry, joint.Peer, otherMemo);
+ if (ReadBeamRectangle(otherHatch) is not { } peer ||
+ geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(otherHatch[18..])) != priority ||
+ Math.Abs(beam.Z - other.Z) > JunctionTolerance || Math.Abs(own.Depth - peer.Depth) > JunctionTolerance)
+ return false;
+
+ bool atEnd = IsBeamEndRelation(relation), peerEnd = IsBeamEndRelation(joint.Reciprocal);
+ if (!IsOnBeamJoint(beam, joint.X, joint.Y, atEnd) || !IsOnBeamJoint(other, joint.X, joint.Y, peerEnd))
+ return false;
+ double along = (joint.X - beam.X) * beam.Dx + (joint.Y - beam.Y) * beam.Dy;
+ double peerAlong = (joint.X - other.X) * other.Dx + (joint.Y - other.Y) * other.Dy;
+ double dot = beam.Dx * other.Dx + beam.Dy * other.Dy;
+ if (Math.Abs(dot) > JunctionTolerance)
+ {
+ // A collinear butt joint keeps both ends when the members point away from the joint.
+ if (!atEnd || !peerEnd || Math.Abs(Math.Abs(dot) - 1) > JunctionTolerance ||
+ Math.Abs(own.HalfWidth - peer.HalfWidth) > JunctionTolerance ||
+ (beam.Length / 2 - along) * (other.Length / 2 - peerAlong) * dot >= 0)
+ return false;
+ return SetEnd(along, 0);
+ }
+
+ if (!atEnd)
+ {
+ volumeSupported &= peerEnd && other.Length > own.HalfWidth + JunctionTolerance && PeerKeepsContact();
+ interiorStart = Math.Min(interiorStart, along - peer.HalfWidth);
+ interiorStop = Math.Max(interiorStop, along + peer.HalfWidth);
+ return interiorStart > JunctionTolerance && interiorStop < beam.Length - JunctionTolerance;
+ }
+ // A second contact on the peer can change the face used to clean up this end.
+ if (!PeerKeepsContact()) return false;
+ if (peerEnd)
+ return (Math.Abs(beam.Dx) <= JunctionTolerance || Math.Abs(beam.Dy) <= JunctionTolerance) &&
+ other.Length > own.HalfWidth + JunctionTolerance &&
+ SetEnd(along, -peer.HalfWidth);
+ return peerAlong > own.HalfWidth + JunctionTolerance && peerAlong < other.Length - own.HalfWidth - JunctionTolerance &&
+ SetEnd(along, peer.HalfWidth);
+
+ bool PeerKeepsContact() => HasOnlyBeamTargetContact(otherMemo, joint.Reciprocal, junction, other.Owner,
+ (key, contact) => (key == BeamSlabRelation || key == BeamWallRelation || key == BeamColumnRelation) &&
+ BeamWinsContact(geometry, joint.Peer, key, contact, priority));
+ }
+
+ bool SetEnd(double along, double inward)
+ {
+ // A symmetric miter replaces the wedge it removes. A butt cut removes the whole section.
+ volumeLength -= Math.Max(0, inward);
+ if (along < beam.Length / 2)
+ {
+ if (startJoined) return false;
+ startJoined = true;
+ start = inward;
+ startClear = Math.Abs(inward);
+ }
+ else
+ {
+ if (stopJoined) return false;
+ stopJoined = true;
+ stop = beam.Length - inward;
+ stopClear = beam.Length - Math.Abs(inward);
+ }
+ return true;
+ }
+ }
+
+ private static PlaBoundingBox? MakeBeamBox(BeamPrism beam, (Elevations Height, double Left, double Right) section,
+ double start, double stop)
+ {
+ double x0 = beam.X + beam.Dx * start, x1 = beam.X + beam.Dx * stop;
+ double y0 = beam.Y + beam.Dy * start, y1 = beam.Y + beam.Dy * stop;
+ double firstX = beam.Dy * section.Left, secondX = beam.Dy * section.Right;
+ double firstY = -beam.Dx * section.Left, secondY = -beam.Dx * section.Right;
+ return MakeBoundingBox((Math.Min(x0, x1) + Math.Min(firstX, secondX), Math.Min(y0, y1) + Math.Min(firstY, secondY),
+ Math.Max(x0, x1) + Math.Max(firstX, secondX), Math.Max(y0, y1) + Math.Max(firstY, secondY)),
+ section.Height.Bottom, section.Height.Top);
+ }
+
+ private static (Guid Id, byte[] Body)? ReadBeamStructuralNeighbor(ModelGeometry geometry, Guid beam, Guid relation, Guid junction)
+ {
+ var (kind, peerRole, peerClass) = relation == BeamSlabRelation ? (BeamSlabJunctionClass, SlabBeamRelation, SlabClass) :
+ relation == BeamWallRelation ? (WallBeamJunctionClass, WallBeamRelation, WallClass) :
+ (BeamColumnJunctionClass, ColumnBeamRelation, ColumnMemoClass);
+ if (geometry.Read(junction, kind) is not { } contact ||
+ ReadSingleRelation(contact, relation, requireSection: true) != beam)
+ return null;
+ Guid peer = ReadSingleRelation(contact, peerRole, requireSection: true);
+ return geometry.Read(peer, peerClass) is { } body && HasGeometryRelation(body, peerRole, junction) ? (peer, body) : null;
+ }
+
+ private static bool BeamWinsContact(ModelGeometry geometry, Guid id, Guid relation, Guid junction, uint priority)
+ {
+ if (ReadBeamStructuralNeighbor(geometry, id, relation, junction) is not { } neighbor) return false;
+ var (peer, memo) = neighbor;
+ if (relation == BeamSlabRelation)
+ return ReadConnectedSlabPriority(geometry, peer, junction) is > 0 and { } slab && slab <= priority;
+ if (relation == BeamWallRelation)
+ return ReadWallPriority(geometry, peer, memo) is > 0 and { } p && p <= priority;
+ Guid owner = ReadSingleRelation(memo, ColumnMemoRelation, requireSection: true);
+ return geometry.Read(owner, ColumnClass) is { } body &&
+ ReadColumnPrismMemo(body.AsSpan(FindClassFrame(body, ColumnClass)), owner, geometry) == peer &&
+ ReadColumnSection(memo, owner, out var junctions) is { } sectionId &&
+ junctions is not null && junctions.All(c => c.Key != ColumnWallRelation) &&
+ geometry.Read(sectionId, RectangularSectionClass) is { } section &&
+ ReadSingleRelation(section, SectionProfileRelation, requireSection: true) == peer &&
+ ReadCenteredRectangle(section, out int material) is not null &&
+ geometry.Attributes.Material.GetValueOrDefault(material) is > 0 and { } column &&
+ column < priority;
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamCoverage.cs b/src/PlaIO/Internal/ElementReader.BeamCoverage.cs
new file mode 100644
index 0000000..c669f1e
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamCoverage.cs
@@ -0,0 +1,200 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static bool BeamProfileIsFullyCovered(ModelGeometry geometry, Guid id, byte[] memo, BeamPrism beam, PlaMemberProfile profile)
+ {
+ if (ProjectBeamProfile(beam, profile) is not { } section) return false;
+ var materials = geometry.Attributes.Material;
+ if (HighestProfilePriority(profile) is not { } highest) return false;
+ var covered = new List<(double Start, double End)>();
+ var candidates = new List<(Guid Relation, Guid Junction, Guid Peer, Guid Reciprocal, byte[] Memo, PlaPlanPoint? Point)>();
+ var required = (Start: 0.0, End: beam.Length);
+ if (!HasOnlyBeamTargetContact(memo, Guid.Empty, Guid.Empty, beam.Owner, ReadContact)) return false;
+ foreach (var (role, junction, peer, reciprocal, peerMemo, point) in candidates)
+ AddCover(role, junction, peer, reciprocal, peerMemo, point);
+ double through = required.Start;
+ foreach (var (start, end) in covered.OrderBy(interval => interval.Start))
+ {
+ if (start > through + JunctionTolerance) return false;
+ through = Math.Max(through, end);
+ if (through >= required.End - JunctionTolerance) return true;
+ }
+ return false;
+
+ uint? HighestProfilePriority(PlaMemberProfile placed)
+ {
+ uint maximum = 0;
+ foreach (var component in placed.Components)
+ {
+ if (materials.GetValueOrDefault(component.BuildingMaterialIndex) is not (> 0 and { } value)) return null;
+ maximum = Math.Max(maximum, value);
+ }
+ return maximum;
+ }
+
+ uint? HighestBeamPriority(Guid id, byte[] beamMemo)
+ {
+ var hatch = ReadBeamHatch(geometry, id, beamMemo);
+ if (!hatch.IsEmpty) return materials.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]));
+ Guid owner = ReadSingleRelation(beamMemo, BeamMemoRelation, requireSection: true);
+ return geometry.Read(owner, BeamClass) is { } body &&
+ ReadMemberProfile(body.AsSpan(FindClassFrame(body, BeamClass)), owner, beam: true, geometry) is { } other
+ ? HighestProfilePriority(other) : null;
+ }
+
+ bool ReadContact(Guid relation, Guid junction)
+ {
+ if (relation == BeamSlabRelation || relation == BeamWallRelation || relation == BeamColumnRelation)
+ return ReadBeamStructuralNeighbor(geometry, id, relation, junction) is not null;
+ var overlap = ReadBeamAxisJunction(geometry, id, relation, junction, withoutPoint: true);
+ if ((overlap ?? ReadBeamAxisJunction(geometry, id, relation, junction)) is not { } joint ||
+ geometry.Read(joint.Peer, BeamMemoClass) is not { } peerMemo ||
+ !HasGeometryRelation(peerMemo, joint.Reciprocal, junction))
+ return false;
+ if (IsBeamEndRelation(relation))
+ {
+ if (ReadBeamPrism(geometry, joint.Peer, peerMemo, 0) is not { } joined ||
+ !SameIntersectionGroup(geometry, beam.Layer, joined.Layer) ||
+ !IsOnBeamJoint(beam, joint.X, joint.Y, end: true) ||
+ !IsOnBeamJoint(joined, joint.X, joint.Y, IsBeamEndRelation(joint.Reciprocal)) ||
+ ReadBeamContactExtents(geometry, joint.Peer, peerMemo, joined) is not { } tip)
+ return false;
+ double at = (joint.X - beam.X) * beam.Dx + (joint.Y - beam.Y) * beam.Dy;
+ if (ProjectBeamJunctionInterval(beam, joined, joint.X, joint.Y, section.Left, section.Right,
+ tip.Left, tip.Right) is not { } reach)
+ {
+ double peerAt = (joint.X - joined.X) * joined.Dx + (joint.Y - joined.Y) * joined.Dy;
+ double direction = beam.Dx * joined.Dx + beam.Dy * joined.Dy;
+ return IsBeamEndRelation(joint.Reciprocal) &&
+ (beam.Length / 2 - at) * (joined.Length / 2 - peerAt) * direction < 0;
+ }
+ if (at < beam.Length / 2) required.Start = Math.Min(required.Start, reach.Min);
+ else required.End = Math.Max(required.End, reach.Max);
+ return true;
+ }
+ if (overlap is null && !IsOnBeamJoint(beam, joint.X, joint.Y, end: false)) return false;
+ candidates.Add((relation, junction, joint.Peer, joint.Reciprocal, peerMemo,
+ overlap is null ? new PlaPlanPoint(joint.X, joint.Y) : null));
+ return true;
+ }
+
+ void AddCover(Guid relation, Guid junction, Guid peerId, Guid reciprocal, byte[] peerMemo, PlaPlanPoint? point)
+ {
+ if (ReadBeamPrism(geometry, peerId, peerMemo, 0) is not { } peer ||
+ !SameIntersectionGroup(geometry, beam.Layer, peer.Layer) || Math.Abs(peer.SinRoll) > JunctionTolerance ||
+ point is { } contact && (IsBeamEndRelation(reciprocal) || !IsOnBeamJoint(peer, contact.X, contact.Y, end: false)))
+ return;
+
+ var hatch = ReadBeamHatch(geometry, peerId, peerMemo);
+ if (ReadBeamRectangle(hatch) is not { } rectangle ||
+ materials.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } priority ||
+ priority <= highest ||
+ section.Height.Bottom < peer.Z - rectangle.Depth - JunctionTolerance || section.Height.Top > peer.Z + JunctionTolerance)
+ return;
+
+ // Find the stations at which the peer contains the whole transverse section.
+ double dx = beam.X - peer.X, dy = beam.Y - peer.Y;
+ double along = dx * peer.Dx + dy * peer.Dy, across = dx * peer.Dy - dy * peer.Dx;
+ double cos = beam.Dx * peer.Dx + beam.Dy * peer.Dy, sin = beam.Dx * peer.Dy - beam.Dy * peer.Dx;
+ double near = Math.Min(-sin * section.Left, -sin * section.Right);
+ double far = Math.Max(-sin * section.Left, -sin * section.Right);
+ var interval = required;
+ var cuts = new List<(double Start, double End)>();
+ if (!LimitBeamStations(ref interval, along, cos, -near, peer.Length - far) ||
+ !LimitBeamStations(ref interval, across, sin,
+ -rectangle.HalfWidth - Math.Min(cos * section.Left, cos * section.Right),
+ rectangle.HalfWidth - Math.Max(cos * section.Left, cos * section.Right)) ||
+ !HasOnlyBeamTargetContact(peerMemo, reciprocal, junction, peer.Owner, KeepsCover))
+ return;
+
+ double start = interval.Start;
+ foreach (var cut in cuts.OrderBy(c => c.Start))
+ {
+ if (cut.Start > start + JunctionTolerance) covered.Add((start, cut.Start));
+ start = Math.Max(start, cut.End);
+ }
+ if (start < interval.End - JunctionTolerance) covered.Add((start, interval.End));
+
+ bool AddCut(double low, double high)
+ {
+ var affected = interval;
+ if (LimitBeamStations(ref affected, along, cos, low - far, high - near))
+ cuts.Add(affected);
+ return true;
+ }
+
+ bool KeepsCover(Guid key, Guid otherJunction)
+ {
+ if (key == BeamSlabRelation || key == BeamWallRelation || key == BeamColumnRelation)
+ {
+ if (BeamWinsContact(geometry, peerId, key, otherJunction, priority)) return true;
+ if (MakeBeamBox(beam, section, required.Start, required.End) is not { } target) return false;
+ if (key == BeamSlabRelation && ReadBeamSlabCutBox(geometry, peerId, otherJunction, section.Height, out var slab))
+ return slab is null || AddPlanCut((slab.XMin, slab.YMin, slab.XMax, slab.YMax));
+ return key == BeamColumnRelation &&
+ TryReadBeamColumnCut(geometry, peerId, otherJunction, priority, out var plan) &&
+ (plan is null || AddPlanCut(plan.Value));
+
+ bool AddPlanCut((double X0, double Y0, double X1, double Y1) plan)
+ {
+ if (BeamPlanIsDisjoint(plan, target)) return true;
+ var span = ProjectRectangle(plan, peer.X, peer.Y, peer.Dx, peer.Dy);
+ return AddCut(span.Min, span.Max);
+ }
+ }
+
+ if (ReadBeamAxisJunction(geometry, peerId, key, otherJunction, withoutPoint: true) is { } overlap)
+ {
+ if (overlap.Peer == id)
+ return overlap.Reciprocal == relation && key == reciprocal &&
+ HasGeometryRelation(memo, relation, otherJunction);
+ if (geometry.Read(overlap.Peer, BeamMemoClass) is not { } overlapMemo ||
+ !HasGeometryRelation(overlapMemo, overlap.Reciprocal, otherJunction))
+ return false;
+ return HighestBeamPriority(overlap.Peer, overlapMemo) is > 0 and { } p && p < priority;
+ }
+
+ // A join outside the covered interval can only affect the part of the prism within its peer's strip.
+ if (ReadBeamAxisJunction(geometry, peerId, key, otherJunction) is not { } endpoint ||
+ geometry.Read(endpoint.Peer, BeamMemoClass) is not { } endMemo ||
+ !HasGeometryRelation(endMemo, endpoint.Reciprocal, otherJunction))
+ return false;
+ if (endpoint.Peer == id)
+ return point is not null && key == reciprocal && endpoint.Reciprocal == relation &&
+ IsOnBeamJoint(beam, endpoint.X, endpoint.Y, end: false) &&
+ IsOnBeamJoint(peer, endpoint.X, endpoint.Y, end: false);
+ if (ReadBeamPrism(geometry, endpoint.Peer, endMemo, 0) is not { } endPeer ||
+ !SameIntersectionGroup(geometry, peer.Layer, endPeer.Layer) ||
+ !IsOnBeamJoint(peer, endpoint.X, endpoint.Y, IsBeamEndRelation(key)) ||
+ !IsOnBeamJoint(endPeer, endpoint.X, endpoint.Y, IsBeamEndRelation(endpoint.Reciprocal)) ||
+ ReadBeamContactExtents(geometry, endpoint.Peer, endMemo, endPeer) is not { } endSection)
+ return false;
+ if (!IsBeamEndRelation(key) && (DisjointHeights(endSection.Height.Bottom, endSection.Height.Top, section.Height) ||
+ HighestBeamPriority(endpoint.Peer, endMemo) is > 0 and { } p3 && p3 < priority))
+ return true;
+ if (ProjectBeamJunctionInterval(peer, endPeer, endpoint.X, endpoint.Y, -rectangle.HalfWidth,
+ rectangle.HalfWidth, endSection.Left, endSection.Right) is { } reach)
+ return AddCut(reach.Min, reach.Max);
+ double peerAt = (endpoint.X - peer.X) * peer.Dx + (endpoint.Y - peer.Y) * peer.Dy;
+ double otherAt = (endpoint.X - endPeer.X) * endPeer.Dx + (endpoint.Y - endPeer.Y) * endPeer.Dy;
+ double direction = peer.Dx * endPeer.Dx + peer.Dy * endPeer.Dy;
+ return IsBeamEndRelation(key) && IsBeamEndRelation(endpoint.Reciprocal) &&
+ (peer.Length / 2 - peerAt) * (endPeer.Length / 2 - otherAt) * direction < 0;
+ }
+ }
+ }
+
+ private static bool LimitBeamStations(ref (double Start, double End) interval,
+ double origin, double slope, double min, double max)
+ {
+ if (!(min <= max + JunctionTolerance)) return false;
+ if (slope == 0) return origin >= min - JunctionTolerance && origin <= max + JunctionTolerance;
+ double a = (min - origin) / slope, b = (max - origin) / slope;
+ interval = (Math.Max(interval.Start, Math.Min(a, b)), Math.Min(interval.End, Math.Max(a, b)));
+ return interval.Start <= interval.End;
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamCuts.cs b/src/PlaIO/Internal/ElementReader.BeamCuts.cs
new file mode 100644
index 0000000..353f6bf
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamCuts.cs
@@ -0,0 +1,498 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid BeamMemoRelation = new("d5762ca7-d920-455d-a373-28ba6d47152a");
+ private static readonly Guid PlanContourRelation = new("e6e5e667-9577-41ca-bf4a-da75b917513f");
+ private static readonly Guid BeamBeamJunctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37");
+ private static readonly Guid FirstBeamCollisionRelation = new("89d11bdb-3a78-48ad-96e7-5b69836c591d");
+ private static readonly Guid SecondBeamCollisionRelation = new("1d381463-2edc-4aad-91b0-027291e8da94");
+ private static readonly Guid FirstBeamEndRelation = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73");
+ private static readonly Guid SecondBeamEndRelation = new("1dae4518-b353-42bc-bcb1-d037bcc603d6");
+ private const double JunctionTolerance = 1e-8;
+
+ private readonly record struct BeamBand(double Bottom, double Top, double X0, double Y0, double X1, double Y1);
+ private readonly record struct BeamMember(BeamPrism Beam, BeamBand Band, byte[] Memo, Guid TargetJunction);
+
+ private static Elevations? ClipByBeamUnion(ModelGeometry geometry, List<(Guid Memo, Guid Junction)> contacts,
+ Guid targetRelation, ElementLocation target, double home, (double X0, double Y0, double X1, double Y1) footprint, Elevations bounds,
+ double lowerMax, double upperMin, bool joinedSlabWall = false)
+ {
+ if (joinedSlabWall && (footprint.X1 - footprint.X0 <= 2 * JunctionTolerance ||
+ footprint.Y1 - footprint.Y0 <= 2 * JunctionTolerance))
+ return null;
+ var bands = new List();
+ var members = new Dictionary();
+ foreach (var (id, junction) in contacts)
+ {
+ if (geometry.Read(id, BeamMemoClass) is not { } memo ||
+ ReadBeamPrism(geometry, id, memo, home) is not { } beam ||
+ !SameIntersectionGroup(geometry, beam.Layer, target.LayerIndex))
+ return null;
+ var hatch = ReadBeamHatch(geometry, id, memo);
+ if (BeamSectionElevations(beam, hatch) is not { } height) return null;
+ if (height.Bottom >= bounds.Top || height.Top <= bounds.Bottom) continue;
+ if (lowerMax != bounds.Bottom && height.Bottom < lowerMax || upperMin != bounds.Top && height.Top > upperMin)
+ return null;
+ if (beam.SinRoll != 0 || BeamPlanBand(beam, hatch) is not { } band ||
+ !members.TryAdd(id, new BeamMember(beam, band, memo, junction)))
+ return null;
+ }
+ foreach (var (id, member) in members)
+ {
+ BeamBand? extended = null;
+ if (!HasOnlyBeamTargetContact(member.Memo, targetRelation, member.TargetJunction, member.Beam.Owner,
+ (key, joint) => IsInternalParallelBeamCollision(geometry, members, id, key, joint) ||
+ KeepsTransverseBeamUnion(geometry, members, id, key, joint, home, footprint,
+ targetRelation == BeamColumnRelation, joinedSlabWall, ref extended) ||
+ joinedSlabWall && (key == BeamWallRelation || key == BeamSlabRelation)))
+ return null;
+ var band = extended ?? member.Band;
+ if (band.X0 < footprint.X1 && band.X1 > footprint.X0 && band.Y0 < footprint.Y1 && band.Y1 > footprint.Y0)
+ bands.Add(band);
+ }
+
+ // Coverage is constant between successive beam faces.
+ var levels = bands.SelectMany(b => new[] { b.Bottom, b.Top })
+ .Where(z => z > bounds.Bottom && z < bounds.Top)
+ .Append(bounds.Bottom).Append(bounds.Top).Distinct().Order().ToArray();
+ double? bottom = null, top = null;
+ for (int i = 1; i < levels.Length; i++)
+ {
+ double low = levels[i - 1], high = levels[i];
+ var active = bands.Where(b => b.Bottom <= low && b.Top >= high).ToArray();
+ if (CoversSection(footprint, active, joinedSlabWall ? JunctionTolerance : 0)) continue;
+ bottom ??= low;
+ top = high;
+ }
+ return bottom is { } lo && top is { } hi ? CheckedElevations(lo, hi) : null;
+ }
+
+ private static bool IsInternalParallelBeamCollision(ModelGeometry geometry,
+ Dictionary members, Guid id, Guid key, Guid junction)
+ {
+ if (key != FirstBeamCollisionRelation && key != SecondBeamCollisionRelation) return false;
+ if (geometry.Read(junction, BeamBeamJunctionClass) is not { } contact ||
+ ReadSingleRelation(contact, key, requireSection: true) != id) return false;
+ Guid reciprocal = key == FirstBeamCollisionRelation ? SecondBeamCollisionRelation : FirstBeamCollisionRelation;
+ Guid otherId = ReadSingleRelation(contact, reciprocal, requireSection: true);
+ if (!members.TryGetValue(otherId, out var other) || !HasGeometryRelation(other.Memo, reciprocal, junction)) return false;
+ var (beam, band, _, _) = members[id];
+ if (band.Bottom != other.Band.Bottom || band.Top != other.Band.Top) return false;
+ // With parallel, separate axes and matching ends, cleanup only partitions the shared cross-section.
+ return beam.Dx == 0 && other.Beam.Dx == 0 && beam.X != other.Beam.X &&
+ Math.Abs(band.Y0 - other.Band.Y0) <= JunctionTolerance && Math.Abs(band.Y1 - other.Band.Y1) <= JunctionTolerance ||
+ beam.Dy == 0 && other.Beam.Dy == 0 && beam.Y != other.Beam.Y &&
+ Math.Abs(band.X0 - other.Band.X0) <= JunctionTolerance && Math.Abs(band.X1 - other.Band.X1) <= JunctionTolerance;
+ }
+
+ private static bool KeepsTransverseBeamUnion(ModelGeometry geometry, Dictionary members, Guid id,
+ Guid relation, Guid junction, double home, (double X0, double Y0, double X1, double Y1) footprint,
+ bool columnTarget, bool joinedSlabWall, ref BeamBand? extended)
+ {
+ if (ReadBeamAxisJunction(geometry, id, relation, junction) is not { } joint) return false;
+ var (neighbor, reciprocal, x, y) = joint;
+ var (beam, band, ownMemo, targetJunction) = members[id];
+ if (geometry.Read(neighbor, BeamMemoClass) is not { } memo ||
+ !HasGeometryRelation(memo, reciprocal, junction) ||
+ ReadBeamPrism(geometry, neighbor, memo, home) is not { } other || !SameIntersectionGroup(geometry, other.Layer, beam.Layer) ||
+ other.SinRoll != 0 ||
+ !(beam.Dx == 0 && other.Dy == 0 || beam.Dy == 0 && other.Dx == 0))
+ return false;
+ var otherHatch = ReadBeamHatch(geometry, neighbor, memo);
+ if (BeamPlanBand(other, otherHatch) is not { } otherBand) return false;
+ bool ownEnd = IsBeamEndRelation(relation), otherEnd = IsBeamEndRelation(reciprocal);
+ if (!IsOnBeamJoint(beam, x, y, ownEnd) || !IsOnBeamJoint(other, x, y, otherEnd))
+ return false;
+ var (left, right) = ProjectRectangle(footprint, other.X, other.Y, other.Dy, -other.Dx);
+ double halfWidth = other.Dx == 0 ? (otherBand.X1 - otherBand.X0) / 2 : (otherBand.Y1 - otherBand.Y0) / 2;
+ if (right < -halfWidth - JunctionTolerance || left > halfWidth + JunctionTolerance)
+ return true;
+ if (band.Bottom != otherBand.Bottom || band.Top != otherBand.Top) return false;
+ if (ownEnd && otherEnd)
+ {
+ if (!joinedSlabWall || !members.ContainsKey(neighbor)) return false;
+ var miterHatch = ReadBeamHatch(geometry, id, ownMemo);
+ if (ReadBeamRectangle(miterHatch) is not { } ownSection ||
+ beam.Length <= halfWidth + JunctionTolerance || other.Length <= ownSection.HalfWidth + JunctionTolerance)
+ return false;
+ var horizontal = beam.Dy == 0 ? beam : other;
+ var vertical = beam.Dx == 0 ? beam : other;
+ bool outsideX = horizontal.X + horizontal.Dx * horizontal.Length / 2 < x
+ ? footprint.X1 > x + JunctionTolerance : footprint.X0 < x - JunctionTolerance;
+ bool outsideY = vertical.Y + vertical.Dy * vertical.Length / 2 < y
+ ? footprint.Y1 > y + JunctionTolerance : footprint.Y0 < y - JunctionTolerance;
+ // The miter can extend the nominal union outside both arms at the corner.
+ if (outsideX && outsideY) return false;
+ return geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(miterHatch[18..])) is { } priority &&
+ priority == geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(otherHatch[18..]));
+ }
+ if (ownEnd == otherEnd) return false;
+ var host = ownEnd ? other : beam;
+ var branch = ownEnd ? band : otherBand;
+ var (start, stop) = ProjectRectangle((branch.X0, branch.Y0, branch.X1, branch.Y1), host.X, host.Y, host.Dx, host.Dy);
+ if (start <= JunctionTolerance || stop >= host.Length - JunctionTolerance) return false;
+ // With two cutters, the through beam contains any change to the joined end.
+ if (members.ContainsKey(neighbor)) return true;
+ if (!columnTarget || members.Count != 1 || extended is not null ||
+ ReadBeamHatch(geometry, id, ownMemo) is not { Length: >= 22 } ownHatch ||
+ geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(ownHatch[18..])) is not { } ownPriority ||
+ geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(otherHatch[18..])) is not { } otherPriority ||
+ ownPriority <= otherPriority ||
+ geometry.Read(targetJunction, BeamColumnJunctionClass) is not { } target)
+ return false;
+ Guid column = ReadSingleRelation(target, ColumnBeamRelation, requireSection: true);
+ if (column == Guid.Empty ||
+ !HasOnlyBeamTargetContact(memo, reciprocal, junction, other.Owner, (key, joint) =>
+ key == BeamColumnRelation && geometry.Read(joint, BeamColumnJunctionClass) is { } beamColumn &&
+ ReadSingleRelation(beamColumn, BeamColumnRelation, requireSection: true) == neighbor &&
+ ReadSingleRelation(beamColumn, ColumnBeamRelation, requireSection: true) == column))
+ return false;
+ if (!ownEnd) return true;
+ // The stronger branch occupies its strip to the far face of the through beam.
+ extended = beam.Dx == 0
+ ? band with { Y0 = Math.Min(band.Y0, otherBand.Y0), Y1 = Math.Max(band.Y1, otherBand.Y1) }
+ : band with { X0 = Math.Min(band.X0, otherBand.X0), X1 = Math.Max(band.X1, otherBand.X1) };
+ return true;
+ }
+
+ private static (Guid Peer, Guid Reciprocal, double X, double Y)? ReadBeamAxisJunction(ModelGeometry geometry, Guid id,
+ Guid relation, Guid junction, bool withoutPoint = false)
+ {
+ if (relation != FirstBeamCollisionRelation && relation != SecondBeamCollisionRelation && !IsBeamEndRelation(relation) ||
+ geometry.Read(junction, BeamBeamJunctionClass) is not { Length: >= 67 } contact ||
+ !contact.AsSpan(35).StartsWith(new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }) ||
+ contact[66] != (withoutPoint ? 0 : 1) || ReadSingleRelation(contact, relation, requireSection: true) != id)
+ return null;
+ bool first = relation == FirstBeamEndRelation || relation == SecondBeamCollisionRelation;
+ Guid end = first ? SecondBeamEndRelation : FirstBeamEndRelation;
+ Guid interior = first ? FirstBeamCollisionRelation : SecondBeamCollisionRelation;
+ Guid endNeighbor = ReadSingleRelation(contact, end, requireSection: true);
+ Guid interiorNeighbor = ReadSingleRelation(contact, interior, requireSection: true);
+ if ((endNeighbor == Guid.Empty) == (interiorNeighbor == Guid.Empty)) return null;
+ Guid peer = endNeighbor == Guid.Empty ? interiorNeighbor : endNeighbor;
+ Guid reciprocal = endNeighbor == Guid.Empty ? interior : end;
+ double x = ReadDouble(contact, 50), y = ReadDouble(contact, 58);
+ if (peer == id || withoutPoint && (IsBeamEndRelation(relation) || IsBeamEndRelation(reciprocal) || x != 0 || y != 0))
+ return null;
+ return (peer, reciprocal, x, y);
+ }
+
+ private static bool IsOnBeamJoint(BeamPrism beam, double x, double y, bool end)
+ {
+ double along = (x - beam.X) * beam.Dx + (y - beam.Y) * beam.Dy;
+ double across = (x - beam.X) * beam.Dy - (y - beam.Y) * beam.Dx;
+ return Math.Abs(across) <= JunctionTolerance && (end
+ ? Math.Abs(along) <= JunctionTolerance || Math.Abs(along - beam.Length) <= JunctionTolerance
+ : along > JunctionTolerance && along < beam.Length - JunctionTolerance);
+ }
+
+ private static bool IsBeamEndRelation(Guid relation) => relation == FirstBeamEndRelation || relation == SecondBeamEndRelation;
+
+ private static BeamBand? BeamPlanBand(BeamPrism beam, ReadOnlySpan hatch)
+ {
+ if (ReadBeamRectangle(hatch) is not { } section) return null;
+ double half = section.HalfWidth;
+ double along = beam.Length * beam.Dx, across = beam.Length * beam.Dy;
+ // The plan sweep below is for beams whose section is parallel to a project axis.
+ if (along == 0)
+ return new BeamBand(beam.Z - section.Depth, beam.Z, beam.X - half, beam.Y + Math.Min(0, across),
+ beam.X + half, beam.Y + Math.Max(0, across));
+ if (across == 0)
+ return new BeamBand(beam.Z - section.Depth, beam.Z, beam.X + Math.Min(0, along), beam.Y - half,
+ beam.X + Math.Max(0, along), beam.Y + half);
+ return null;
+ }
+
+ private static bool CoversSection((double X0, double Y0, double X1, double Y1) footprint, BeamBand[] active, double tolerance)
+ {
+ if (active.Length == 0) return false;
+ var edges = active.SelectMany(b => new[] { b.X0, b.X1 }).Where(x => x > footprint.X0 && x < footprint.X1)
+ .Append(footprint.X0).Append(footprint.X1).Distinct().Order().ToArray();
+ Array.Sort(active, (a, b) => a.Y0.CompareTo(b.Y0));
+ for (int i = 1; i < edges.Length; i++)
+ {
+ double y = footprint.Y0;
+ foreach (var b in active)
+ {
+ if (b.Y0 > y + tolerance) break;
+ if (b.X0 <= edges[i - 1] + tolerance && b.X1 >= edges[i] - tolerance)
+ y = Math.Max(y, b.Y1);
+ }
+ if (y < footprint.Y1 - tolerance) return false;
+ }
+ return true;
+ }
+
+ private static Elevations? ClipByBeam(ModelGeometry geometry, Guid beamId, Guid junction, Guid targetRelation, ElementLocation target,
+ double home, (double X0, double Y0, double X1, double Y1) footprint, Elevations bounds, double lowerMax, double upperMin)
+ {
+ if (geometry.Read(beamId, BeamMemoClass) is not { } memo ||
+ ReadBeamPrism(geometry, beamId, memo, home) is not { } prism || !SameIntersectionGroup(geometry, prism.Layer, target.LayerIndex) ||
+ targetRelation == BeamWallRelation && prism.SinRoll != 0)
+ return null;
+ var hatch = ReadBeamHatch(geometry, beamId, memo);
+ if (ReadBeamRectangle(hatch) is not { } section) return null;
+ var (owner, _, x, y, z, ux, uy, length, sine, cosine) = prism;
+ double zSpan = Math.Abs(sine) * section.HalfWidth;
+ double tSpan = Math.Abs(cosine) * section.HalfWidth;
+ double tOffset = sine * section.Depth;
+ var (t0, t1) = ProjectRectangle(footprint, x, y, uy, -ux);
+ double prismBottom = z - cosine * section.Depth - zSpan, prismTop = z + zSpan;
+ if (prismTop <= bounds.Bottom + JunctionTolerance || prismBottom >= bounds.Top - JunctionTolerance ||
+ t1 <= Math.Min(0, tOffset) - tSpan || t0 >= Math.Max(0, tOffset) + tSpan)
+ return bounds;
+
+ if (prismBottom > lowerMax + JunctionTolerance && prismTop < upperMin - JunctionTolerance) return bounds;
+ double tiltedLow = z + Math.Min(sine * t0, sine * t1) / cosine;
+ double tiltedHigh = z + Math.Max(sine * t0, sine * t1) / cosine;
+ double depth = section.Depth / cosine;
+
+ var (s0, s1) = ProjectRectangle(footprint, x, y, ux, uy);
+ if (s0 <= JunctionTolerance || s1 >= length - JunctionTolerance ||
+ !HasOnlyBeamTargetContact(memo, targetRelation, junction, owner))
+ return null;
+ if (t0 >= -tSpan && t1 <= tSpan && FaceFits(bounds.Bottom, lowerMax) && tiltedLow >= lowerMax &&
+ tiltedHigh < upperMin)
+ return CheckedElevations(tiltedLow, bounds.Top);
+ if (t0 >= tOffset - tSpan && t1 <= tOffset + tSpan && FaceFits(upperMin, bounds.Top) && tiltedHigh - depth <= upperMin &&
+ tiltedLow - depth > lowerMax)
+ return CheckedElevations(bounds.Bottom, tiltedHigh - depth);
+ return null;
+
+ bool FaceFits(double bottom, double top) =>
+ Fits(t0, bottom) && Fits(t0, top) && Fits(t1, bottom) && Fits(t1, top);
+
+ bool Fits(double across, double elevation)
+ {
+ double tz = elevation - z;
+ double localX = cosine * across + sine * tz, localZ = cosine * tz - sine * across;
+ return Math.Abs(localX) <= section.HalfWidth && localZ <= JunctionTolerance &&
+ localZ >= -section.Depth - JunctionTolerance;
+ }
+ }
+
+ private readonly record struct BeamPrism(Guid Owner, int? Layer, double X, double Y, double Z, double Dx, double Dy,
+ double Length, double SinRoll, double CosRoll);
+
+ private readonly record struct BeamEndPlanes(double Rise, BeamVector StartNormal, BeamVector EndNormal)
+ {
+ public bool HasSquareHorizontalEnds(BeamPrism axis) => Rise == 0 &&
+ AlongAxis(StartNormal, -axis.Dx, -axis.Dy) && AlongAxis(EndNormal, axis.Dx, axis.Dy);
+ }
+
+ private static BeamPrism? ReadBeamPrism(ModelGeometry geometry, Guid beamId, ReadOnlySpan memo, double home) =>
+ ReadStraightBeamAxis(geometry, beamId, memo, home, out var planes) is { } axis && planes.HasSquareHorizontalEnds(axis)
+ ? axis : null;
+
+ private static Guid ReadBeamPrismMemo(ReadOnlySpan beam, Guid owner, ModelGeometry geometry, bool readAnnotations = false) =>
+ ReadPrismMemo(beam, BeamMemoRelation,
+ acceptsReference: (role, target) => IsPrismAnnotation(geometry, owner, role, target, readAnnotations));
+
+ private static BeamPrism? ReadStraightBeamAxis(ModelGeometry geometry, Guid beamId, ReadOnlySpan memo,
+ double home, out BeamEndPlanes planes, bool readAnnotations = false)
+ {
+ planes = default;
+ Guid owner = ReadSingleRelation(memo, BeamMemoRelation, requireSection: true);
+ if (geometry.Read(owner, BeamClass) is not { } body) return null;
+ var beam = body.AsSpan(FindClassFrame(body, BeamClass));
+ if (ReadBeamPrismMemo(beam, owner, geometry, readAnnotations) != beamId ||
+ ReadBeamAxisFrame(beam, owner, geometry) is not { Sweep: 0 } frame)
+ return null;
+ planes = frame.Planes;
+ double z = frame.Axis.Z + (frame.Story - home);
+ return double.IsFinite(z) && double.IsFinite(z + planes.Rise) ? frame.Axis with { Z = z } : null;
+ }
+
+ private readonly record struct BeamAxisFrame(BeamPrism Axis, BeamEndPlanes Planes, double EndX, double EndY,
+ double EndZ, double Story, double Sweep);
+
+ private static BeamAxisFrame? ReadBeamAxisFrame(ReadOnlySpan beam, Guid owner, ModelGeometry geometry)
+ {
+ if (beam.Length < 735 || !beam[721..].StartsWith(ElementIdFrame) ||
+ !beam.Slice(304, ColumnEndPlaneFrame.Length).SequenceEqual(ColumnEndPlaneFrame) ||
+ BinaryPrimitives.ReadUInt16LittleEndian(beam[368..]) != 1)
+ return null;
+
+ var location = ReadElementLocation(beam, "Beam", 0);
+ if (geometry.StoryElevation(location.HomeStoryIndex) is not { } level) return null;
+ var settings = AfterCountedString(beam, 735);
+ if (settings.Length < 254 || ReadDouble(settings, 1) != 0 ||
+ ReadDouble(settings, 133) != 1 || ReadDouble(settings, 238) != 1)
+ return null;
+ double x = ReadDouble(beam, 312), y = ReadDouble(beam, 320), z = ReadDouble(beam, 328);
+ double x1 = ReadDouble(beam, 370), y1 = ReadDouble(beam, 378), endZ = ReadDouble(beam, 386);
+ double dx = x1 - x, dy = y1 - y, length = Math.Sqrt(dx * dx + dy * dy);
+ if (!double.IsFinite(length) || !(length > 0) || !double.IsFinite(z) || !double.IsFinite(endZ) ||
+ !MatchesBeamAxisPoint(settings[17..], x, y) || !MatchesBeamAxisPoint(settings[33..], x1, y1))
+ return null;
+ double ux = dx / length, uy = dy / length;
+ double roll = ReadDouble(settings, 155), cosine = Math.Cos(roll);
+ if (roll != ReadDouble(settings, 246) || !(cosine > JunctionTolerance)) return null;
+ double rise = endZ - z, sweep = ReadDouble(settings, 49);
+ if (!double.IsFinite(rise) || !(Math.Abs(sweep) < Math.Tau)) return null;
+ var planes = new BeamEndPlanes(rise, ReadBeamVector(beam, 336), ReadBeamVector(beam, 394));
+ var axis = new BeamPrism(owner, location.LayerIndex, x, y, z, ux, uy, length, Math.Sin(roll), cosine);
+ return new BeamAxisFrame(axis, planes, x1, y1, endZ, level, sweep);
+ }
+
+ private static PlaBeamReferenceAxis? ReadBeamReferenceAxis(ReadOnlySpan beam, Guid owner, ModelGeometry geometry)
+ {
+ if (ReadBeamAxisFrame(beam, owner, geometry) is not { } frame) return null;
+ Guid memoId = ReadSingleRelation(beam, BeamMemoRelation, 0x11, requireSection: true);
+ if (geometry.Read(memoId, BeamMemoClass) is not { } memo ||
+ ReadSingleRelation(memo, BeamMemoRelation, requireSection: true) != owner)
+ return null;
+
+ var axis = frame.Axis;
+ double sweep = frame.Sweep;
+ if (sweep != 0)
+ {
+ if (frame.Planes.Rise != 0) return null;
+ // Radial cap planes independently confirm the tangents of the saved circular axis.
+ double c = Math.Cos(sweep / 2), s = Math.Sin(sweep / 2);
+ if (!MatchesTangent(frame.Planes.StartNormal, -axis.Dx * c - axis.Dy * s, -axis.Dy * c + axis.Dx * s) ||
+ !MatchesTangent(frame.Planes.EndNormal, axis.Dx * c - axis.Dy * s, axis.Dy * c + axis.Dx * s))
+ return null;
+ }
+ double start = axis.Z + frame.Story, end = frame.EndZ + frame.Story;
+ var reference = new PlaBeamReferenceAxis(new(axis.X, axis.Y), new(frame.EndX, frame.EndY), start, end, sweep);
+ return double.IsFinite(start) && double.IsFinite(end) && double.IsFinite(reference.Length) ? reference : null;
+
+ static bool MatchesTangent(BeamVector normal, double x, double y) =>
+ Math.Abs(normal.Z) <= JunctionTolerance && AlongAxis(normal with { Z = 0 }, x, y);
+ }
+
+ private static bool BeamLeavesWallSection(ModelGeometry geometry, Guid beamId, ReadOnlySpan memo,
+ ReadOnlySpan hatch, ElementLocation wall, Elevations bounds,
+ WallStrip? strip, List blocked)
+ {
+ if (geometry.StoryElevation(wall.HomeStoryIndex) is not { } home ||
+ ReadBeamPrism(geometry, beamId, memo, home) is not { } beam ||
+ BeamSectionExtents(beam, hatch) is not { } section)
+ return false;
+ if (MissesEndFaces(section.Height.Bottom, section.Height.Top, bounds, bounds.Bottom, bounds.Top))
+ return true;
+ if (strip is not { } s) return false;
+ double along = s.AlongX ? beam.Dy : -beam.Dx;
+ double across = s.AlongX ? -beam.Dx : beam.Dy;
+ double originAlong = s.AlongX ? beam.X : beam.Y, originAcross = s.AlongX ? beam.Y : beam.X;
+ double a = (s.AcrossMin - originAcross) * across, b = (s.AcrossMax - originAcross) * across;
+ if (along == 0)
+ return Math.Max(a, b) <= section.Left || Math.Min(a, b) >= section.Right;
+ double start = originAlong + (section.Left - Math.Max(a, b)) / along;
+ double end = originAlong + (section.Right - Math.Min(a, b)) / along;
+ if (!double.IsFinite(start) || !double.IsFinite(end)) return false;
+ blocked.Add(new((Math.Min(start, end), Math.Max(start, end)), section.Height));
+ return true;
+ }
+
+ private static Elevations? BeamSectionElevations(BeamPrism beam, ReadOnlySpan hatch) =>
+ BeamSectionExtents(beam, hatch)?.Height;
+
+ private static (Elevations Height, double Left, double Right)? BeamSectionExtents(BeamPrism beam, ReadOnlySpan hatch)
+ {
+ var points = StraightSectionVertices(hatch);
+ if (points.IsEmpty) return null;
+ double z0 = double.PositiveInfinity, z1 = double.NegativeInfinity;
+ double t0 = double.PositiveInfinity, t1 = double.NegativeInfinity;
+ for (int i = 0; i < points.Length; i += 16)
+ {
+ double x = ReadDouble(points, i), z = ReadDouble(points, i + 8);
+ double elevation = beam.Z + beam.SinRoll * x + beam.CosRoll * z;
+ double across = beam.CosRoll * x - beam.SinRoll * z;
+ z0 = Math.Min(z0, elevation);
+ z1 = Math.Max(z1, elevation);
+ t0 = Math.Min(t0, across);
+ t1 = Math.Max(t1, across);
+ }
+ return z1 > z0 && t1 > t0 && double.IsFinite(t0) && double.IsFinite(t1) && CheckedElevations(z0, z1) is { } height
+ ? (height, t0, t1) : null;
+ }
+
+ private static bool BeamCannotCutColumnEnds(ModelGeometry geometry, Guid beamId, double home,
+ Elevations bounds, double lowerMax, double upperMin)
+ {
+ return geometry.Read(beamId, BeamMemoClass) is { } memo &&
+ ReadBeamPrism(geometry, beamId, memo, home) is { } beam &&
+ BeamSectionElevations(beam, ReadBeamHatch(geometry, beamId, memo)) is { } section &&
+ MissesEndFaces(section.Bottom, section.Top, bounds, lowerMax, upperMin);
+ }
+
+ private static double ReadDouble(ReadOnlySpan record, int offset) =>
+ BinaryPrimitives.ReadDoubleLittleEndian(record[offset..]);
+
+ private static bool AlongAxis(BeamVector normal, double x, double y) =>
+ Math.Abs(normal.X - x) <= JunctionTolerance && Math.Abs(normal.Y - y) <= JunctionTolerance && normal.Z == 0;
+
+ private static bool MatchesBeamAxisPoint(ReadOnlySpan setting, double x, double y) =>
+ Math.Abs(ReadDouble(setting, 0) - x) <= JunctionTolerance &&
+ Math.Abs(ReadDouble(setting, 8) - y) <= JunctionTolerance;
+
+ private static (double Min, double Max) ProjectRectangle((double X0, double Y0, double X1, double Y1) xy,
+ double x, double y, double dx, double dy)
+ {
+ double x0 = (xy.X0 - x) * dx, x1 = (xy.X1 - x) * dx;
+ double y0 = (xy.Y0 - y) * dy, y1 = (xy.Y1 - y) * dy;
+ return (Math.Min(x0, x1) + Math.Min(y0, y1), Math.Max(x0, x1) + Math.Max(y0, y1));
+ }
+
+ private static (double HalfWidth, double Depth)? ReadBeamRectangle(ReadOnlySpan hatch)
+ {
+ if (hatch.Length < 161 || BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]) != 6) return null;
+ var points = hatch[59..];
+ if (BinaryPrimitives.ReadUInt16LittleEndian(points[96..]) != 1 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(points[98..]) != 0 ||
+ points[..16].IndexOfAnyExcept((byte)0) >= 0 || !points.Slice(16, 16).SequenceEqual(points.Slice(80, 16)))
+ return null;
+ double halfWidth = Math.Abs(ReadDouble(points, 16));
+ double depth = -Math.Min(ReadDouble(points, 24), Math.Min(ReadDouble(points, 40), ReadDouble(points, 56)));
+ if (!(halfWidth > 0 && double.IsFinite(halfWidth) && depth > 0 && double.IsFinite(depth))) return null;
+ uint corners = 0;
+ for (int i = 16; i < 80; i += 16)
+ {
+ double x = ReadDouble(points, i), y = ReadDouble(points, i + 8);
+ if (Math.Abs(x) != halfWidth || (y != 0 && y != -depth)) return null;
+ corners |= 1u << ((x < 0 ? 0 : 1) + (y == 0 ? 0 : 2));
+ if (i != 16 && ReadDouble(points, i - 16) != x && ReadDouble(points, i - 8) != y) return null;
+ }
+ return corners == 15 && (ReadDouble(points, 64) == ReadDouble(points, 16) ||
+ ReadDouble(points, 72) == ReadDouble(points, 24)) ? (halfWidth, depth) : null;
+ }
+
+ private static bool HasOnlyBeamTargetContact(ReadOnlySpan memo, Guid targetRelation, Guid junction, Guid beam,
+ Func? acceptsExtraContact = null)
+ {
+ int start = FindRelationshipSection(memo, memo.Length);
+ if (start < 0) return false;
+ var data = memo[start..];
+ bool found = false;
+ while (data.Length >= 17)
+ {
+ var entry = data;
+ if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid target)) return false;
+ if ((tag is 1 or 0x11) && key == DrawingRelation ||
+ tag == 0x11 && (key == SectionProfileRelation || key == PlanContourRelation) ||
+ tag == 0x12 && key == BeamMemoRelation && target == beam ||
+ tag == 0x11 && (key == FirstColumnPartRelation || key == SecondColumnPartRelation))
+ continue;
+ if (tag is not (1 or 0x11)) return false;
+ var ids = ReadRelationIds(entry, data, tag);
+ if (ids.IsEmpty) return false;
+ for (int i = 0; i < ids.Length; i += 16)
+ {
+ var other = new Guid(ids.Slice(i, 16));
+ if (other == Guid.Empty) return false;
+ if (key == targetRelation && other == junction && !found)
+ found = true;
+ else if (other == junction || acceptsExtraContact is null || !acceptsExtraContact(key, other))
+ return false;
+ }
+ }
+ // shortcut: other beam contacts can alter the cutter, resolve their geometry before accepting it.
+ return (found || targetRelation == Guid.Empty) && data is [0];
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamElevations.cs b/src/PlaIO/Internal/ElementReader.BeamElevations.cs
new file mode 100644
index 0000000..6e0e744
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamElevations.cs
@@ -0,0 +1,233 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static Elevations? ReadBeamElevations(ModelGeometry geometry, Guid id, byte[] memo, BeamPrism beam, BeamEndPlanes planes,
+ ReadOnlySpan hatch, PlaMemberProfile? profile, double home, BeamCaps? caps, out PlaBoundingBox? boundingBox)
+ {
+ boundingBox = null;
+ var extents = profile is null ? BeamSectionExtents(beam, hatch) : ProjectBeamProfile(beam, profile);
+ if (extents is not { } section) return null;
+ uint priority = ReadBeamSectionPriority(geometry, hatch, profile);
+ bool keepsPlan = true;
+ var blocked = new List<(double Start, double End)>();
+ if (!HasOnlyBeamTargetContact(memo, Guid.Empty, Guid.Empty, beam.Owner, ReadContact)) return null;
+ // A full transverse section outside the union of all possible cuts retains both vertical extrema.
+ double covered = caps?.FullSectionStart ?? 0;
+ foreach (var (start, end) in blocked.OrderBy(c => c.Start))
+ {
+ if (start > covered + JunctionTolerance) break;
+ covered = Math.Max(covered, end);
+ }
+ if (covered >= (caps?.FullSectionEnd ?? beam.Length) - JunctionTolerance) return null;
+ if (keepsPlan)
+ boundingBox = caps?.Bounds ?? MakeBeamBox(beam, section, 0, beam.Length);
+ return CheckedElevations(section.Height.Bottom - home, section.Height.Top - home);
+
+ bool ReadContact(Guid relation, Guid junction)
+ {
+ if (relation == BeamWallRelation || relation == BeamSlabRelation || relation == BeamColumnRelation)
+ {
+ if (priority > 0 && BeamWinsContact(geometry, id, relation, junction, priority)) return true;
+ if (relation == BeamWallRelation) return false;
+ return ReadStructuralContact(relation, junction);
+ }
+
+ if (ReadBeamAxisJunction(geometry, id, relation, junction) is not { } joint ||
+ geometry.Read(joint.Peer, BeamMemoClass) is not { } otherMemo ||
+ ReadStraightBeamAxis(geometry, joint.Peer, otherMemo, 0, out var otherPlanes) is not { } other ||
+ !otherPlanes.StartNormal.IsUnit || !otherPlanes.EndNormal.IsUnit ||
+ !HasOnlyBeamTargetContact(otherMemo, joint.Reciprocal, junction, other.Owner,
+ (key, _) => IsBeamEndRelation(key) || key == FirstBeamCollisionRelation || key == SecondBeamCollisionRelation ||
+ key == BeamSlabRelation || key == BeamWallRelation || key == BeamColumnRelation) ||
+ !SameIntersectionGroup(geometry, beam.Layer, other.Layer) ||
+ !IsOnBeamJoint(beam, joint.X, joint.Y, IsBeamEndRelation(relation)) ||
+ !IsOnBeamJoint(other, joint.X, joint.Y, IsBeamEndRelation(joint.Reciprocal)) ||
+ ReadBeamContactExtents(geometry, joint.Peer, otherMemo, other) is not { } outline)
+ return false;
+
+ double slope = beam.Dx * other.Dy - beam.Dy * other.Dx;
+ double across = beam.Dx * other.Dx + beam.Dy * other.Dy;
+ double along = (joint.X - beam.X) * beam.Dx + (joint.Y - beam.Y) * beam.Dy;
+ if (Math.Abs(slope) <= JunctionTolerance)
+ {
+ double peerAlong = (joint.X - other.X) * other.Dx + (joint.Y - other.Y) * other.Dy;
+ if (!IsBeamEndRelation(relation) || !IsBeamEndRelation(joint.Reciprocal) ||
+ (beam.Length / 2 - along) * (other.Length / 2 - peerAlong) * across >= 0)
+ return false;
+ if (!planes.HasSquareHorizontalEnds(beam) || !otherPlanes.HasSquareHorizontalEnds(other))
+ {
+ keepsPlan = false;
+ return BeamsMeetAtVerticalButt(beam, planes, other, otherPlanes, joint.X, joint.Y);
+ }
+ double left = across > 0 ? outline.Left : -outline.Right;
+ double right = across > 0 ? outline.Right : -outline.Left;
+ keepsPlan &= Math.Abs(section.Left - left) <= JunctionTolerance && Math.Abs(section.Right - right) <= JunctionTolerance &&
+ Math.Abs(section.Height.Bottom - outline.Height.Bottom) <= JunctionTolerance &&
+ Math.Abs(section.Height.Top - outline.Height.Top) <= JunctionTolerance;
+ return true;
+ }
+ keepsPlan = false;
+ return ProjectBeamJunctionInterval(beam, other, joint.X, joint.Y, section.Left, section.Right,
+ outline.Left, outline.Right) is { } reach && Block(reach.Min, reach.Max);
+ }
+
+ bool ReadStructuralContact(Guid relation, Guid junction)
+ {
+ (double X0, double Y0, double X1, double Y1)? plan;
+ if (relation == BeamSlabRelation)
+ {
+ if (!ReadBeamSlabCutBox(geometry, id, junction, section.Height, out var slab)) return false;
+ plan = slab is { } box ? (box.XMin, box.YMin, box.XMax, box.YMax) : null;
+ }
+ else if (!TryReadBeamColumnCut(geometry, id, junction, priority, out plan)) return false;
+
+ if (plan is not { } rectangle) return true;
+ var transverse = ProjectRectangle(rectangle, beam.X, beam.Y, beam.Dy, -beam.Dx);
+ if (transverse.Max <= section.Left || transverse.Min >= section.Right) return true;
+ var axial = ProjectRectangle(rectangle, beam.X, beam.Y, beam.Dx, beam.Dy);
+ keepsPlan &= caps is { } saved ? BeamPlanIsDisjoint(rectangle, saved.Bounds)
+ : axial.Max <= 0 || axial.Min >= beam.Length;
+ return Block(axial.Min, axial.Max);
+ }
+
+ bool Block(double start, double end)
+ {
+ if (!double.IsFinite(start) || !double.IsFinite(end)) return false;
+ blocked.Add((Math.Min(start, end), Math.Max(start, end)));
+ return true;
+ }
+ }
+
+ private static bool ReadBeamSlabCutBox(ModelGeometry geometry, Guid id, Guid junction, Elevations height,
+ out PlaBoundingBox? bounds)
+ {
+ bounds = null;
+ if (ReadBeamStructuralNeighbor(geometry, id, BeamSlabRelation, junction) is not { } slab)
+ return false;
+ var framed = slab.Body.AsSpan(FindClassFrame(slab.Body, SlabClass));
+ if (!HasSupportedSlabContacts(framed, Guid.Empty, Guid.Empty,
+ (key, _) => key == SlabBeamRelation || key == SlabColumnRelation || key == SlabWallRelation ||
+ key == SlabLevelDimensionRelation || key == CutElementRelation || key == OpeningHostRelation) ||
+ ReadElevations(framed, "Slab") is not { } planes ||
+ ReadFloorBox(framed, "Slab", planes, geometry.StoryElevation(ReadElementLocation(framed, "Slab", 0).HomeStoryIndex))
+ is not { } box)
+ return false;
+ if (DisjointHeights(box.ZMin, box.ZMax, height)) return true;
+ var outline = ReadSlabOutline(AfterCountedString(framed, ClassElementIdOffset("Slab")));
+ if (ReadAfterVerticalSlabEdges(outline).IsEmpty) return false;
+ bounds = box;
+ return true;
+ }
+
+ private static uint ReadBeamSectionPriority(ModelGeometry geometry, ReadOnlySpan hatch, PlaMemberProfile? profile) =>
+ profile is null ? geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) ?? 0
+ : profile.Components.Min(c => geometry.Attributes.Material.GetValueOrDefault(c.BuildingMaterialIndex) ?? 0);
+
+ private static (double Min, double Max)? ProjectBeamJunctionInterval(BeamPrism axis, BeamPrism peer, double x, double y,
+ double left, double right, double peerLeft, double peerRight)
+ {
+ double slope = axis.Dx * peer.Dy - axis.Dy * peer.Dx;
+ if (Math.Abs(slope) <= JunctionTolerance) return null;
+ // The peer's strip bounds its reach even when the joint changes its length.
+ double across = axis.Dx * peer.Dx + axis.Dy * peer.Dy;
+ double along = (x - axis.X) * axis.Dx + (y - axis.Y) * axis.Dy;
+ double a = along + (peerLeft - Math.Max(left * across, right * across)) / slope;
+ double b = along + (peerRight - Math.Min(left * across, right * across)) / slope;
+ return double.IsFinite(a) && double.IsFinite(b) ? (Math.Min(a, b), Math.Max(a, b)) : null;
+ }
+
+ private static bool TryReadBeamColumnCut(ModelGeometry geometry, Guid beamId, Guid junction, uint priority,
+ out (double X0, double Y0, double X1, double Y1)? plan, bool allowVerifiedNonWrappingWalls = false)
+ {
+ plan = null;
+ if (geometry.Read(junction, BeamColumnJunctionClass) is not { } contact ||
+ ReadSingleRelation(contact, BeamColumnRelation, requireSection: true) != beamId)
+ return false;
+ Guid peer = ReadSingleRelation(contact, ColumnBeamRelation, requireSection: true);
+ var hatch = ReadColumnContactSection(geometry, peer, ColumnBeamRelation, junction, out var column);
+ if (hatch.IsEmpty || geometry.Read(peer, ColumnMemoClass) is not { } memo ||
+ ReadColumnSection(memo, ReadSingleRelation(memo, ColumnMemoRelation, requireSection: true),
+ out var contacts) is not { } sectionId)
+ return false;
+ // Complex-profile columns do not receive wrapping from wall skins.
+ if (geometry.Read(sectionId, ComplexSectionClass) is null &&
+ contacts?.Any(c => c.Key == ColumnWallRelation && (!allowVerifiedNonWrappingWalls || !WallKeepsColumnOutline(c.Id))) == true)
+ return false;
+ int material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]);
+ if (geometry.Attributes.Material.GetValueOrDefault(material) is > 0 and { } p && p < priority)
+ return true;
+ var settings = AfterCountedString(column, 735);
+ if (settings.Length < 95 || ReadDouble(settings, 28) != 0) return false;
+ plan = ReadColumnFootprint(column, hatch, ReadDouble(settings, 87));
+ return plan is not null;
+
+ bool WallKeepsColumnOutline(Guid id)
+ {
+ if (geometry.Read(id, WallColumnJunctionClass) is not { } joint ||
+ ReadSingleRelation(joint, ColumnWallRelation, requireSection: true) != peer ||
+ geometry.Read(ReadSingleRelation(joint, WallColumnRelation, requireSection: true), WallClass) is not { } wall ||
+ !HasGeometryRelation(wall, WallColumnRelation, id))
+ return false;
+ var wallSettings = ReadWallSettings(wall);
+ return wallSettings.Length >= 231 && BinaryPrimitives.ReadUInt16LittleEndian(wallSettings[225..]) is 1 or 2 or 3 &&
+ !WallMayWrapColumn(geometry.Attributes, wallSettings);
+ }
+ }
+
+ private static bool BeamPlanIsDisjoint((double X0, double Y0, double X1, double Y1) plan, PlaBoundingBox beam) =>
+ plan.X1 <= beam.XMin || plan.X0 >= beam.XMax || plan.Y1 <= beam.YMin || plan.Y0 >= beam.YMax;
+
+ private static (Elevations Height, double Left, double Right)? ReadBeamContactExtents(ModelGeometry geometry,
+ Guid id, byte[] memo, BeamPrism beam)
+ {
+ if (BeamSectionExtents(beam, ReadBeamHatch(geometry, id, memo)) is { } straight) return straight;
+ if (geometry.Read(beam.Owner, BeamClass) is not { } body) return null;
+ var framed = body.AsSpan(FindClassFrame(body, BeamClass));
+ return ReadMemberProfile(framed, beam.Owner, beam: true, geometry) is { } profile
+ ? ProjectBeamProfile(beam, profile) : null;
+ }
+
+ private static (Elevations Height, double Left, double Right)? ProjectBeamProfile(BeamPrism beam, PlaMemberProfile profile)
+ {
+ double z0 = double.PositiveInfinity, z1 = double.NegativeInfinity;
+ double t0 = double.PositiveInfinity, t1 = double.NegativeInfinity;
+ double vertical = Math.Atan2(beam.CosRoll, beam.SinRoll);
+ foreach (var component in profile.Components)
+ {
+ var ring = component.Rings[0];
+ foreach (var point in ring) Include(point.U, point.Z);
+ foreach (var arc in component.Arcs ?? [])
+ {
+ if (arc.RingIndex != 0) continue;
+ var p = ring[arc.StartVertexIndex];
+ var q = ring[(arc.StartVertexIndex + 1) % ring.Count];
+ if (ReadCircularEdge(new(p.U, p.Z), new(q.U, q.Z), arc.SweepRadians, out _) is not { } edge) return null;
+ for (int i = 0; i < 4; i++)
+ {
+ double angle = vertical + i * Math.PI / 2;
+ if (edge.IncludesAngle(angle))
+ {
+ var point = edge.AtAngle(angle);
+ Include(point.X, point.Y);
+ }
+ }
+ }
+ }
+ return z1 > z0 && t1 > t0 && double.IsFinite(t0) && double.IsFinite(t1) && CheckedElevations(z0, z1) is { } height
+ ? (height, t0, t1) : null;
+
+ void Include(double u, double z)
+ {
+ double level = beam.Z + beam.SinRoll * u + beam.CosRoll * z;
+ double across = beam.CosRoll * u - beam.SinRoll * z;
+ z0 = Math.Min(z0, level);
+ z1 = Math.Max(z1, level);
+ t0 = Math.Min(t0, across);
+ t1 = Math.Max(t1, across);
+ }
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamEndPlanes.cs b/src/PlaIO/Internal/ElementReader.BeamEndPlanes.cs
new file mode 100644
index 0000000..66440bc
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamEndPlanes.cs
@@ -0,0 +1,129 @@
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private readonly record struct BeamVector(double X, double Y, double Z)
+ {
+ public bool IsUnit => Math.Abs(Dot(this) - 1) <= JunctionTolerance;
+ public double Dot(BeamVector other) => X * other.X + Y * other.Y + Z * other.Z;
+ public static BeamVector operator +(BeamVector a, BeamVector b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ public static BeamVector operator *(BeamVector a, double scale) => new(a.X * scale, a.Y * scale, a.Z * scale);
+ }
+
+ private readonly record struct BeamCaps(PlaBoundingBox Bounds, PlaBoundingBox First, PlaBoundingBox Last,
+ double FullSectionStart, double FullSectionEnd);
+
+ private static BeamVector ReadBeamVector(ReadOnlySpan record, int offset) =>
+ new(ReadDouble(record, offset), ReadDouble(record, offset + 8), ReadDouble(record, offset + 16));
+
+ private static bool BeamsMeetAtVerticalButt(BeamPrism first, BeamEndPlanes firstPlanes,
+ BeamPrism second, BeamEndPlanes secondPlanes, double x, double y)
+ {
+ if (!IsOnBeamJoint(first, x, y, end: true) || !IsOnBeamJoint(second, x, y, end: true)) return false;
+ bool firstStart = AtStart(first), secondStart = AtStart(second);
+ var a = firstStart ? firstPlanes.StartNormal : firstPlanes.EndNormal;
+ var b = secondStart ? secondPlanes.StartNormal : secondPlanes.EndNormal;
+ double firstSign = firstStart ? -1 : 1, secondSign = secondStart ? -1 : 1;
+ return AlongAxis(a, firstSign * first.Dx, firstSign * first.Dy) &&
+ AlongAxis(b, secondSign * second.Dx, secondSign * second.Dy) &&
+ Math.Abs(a.X + b.X) <= JunctionTolerance && Math.Abs(a.Y + b.Y) <= JunctionTolerance;
+
+ bool AtStart(BeamPrism beam) => Math.Abs((x - beam.X) * beam.Dx + (y - beam.Y) * beam.Dy) <= JunctionTolerance;
+ }
+
+ private static BeamCaps? ProjectBeamCaps(BeamPrism axis, BeamEndPlanes planes,
+ ReadOnlySpan hatch, PlaMemberProfile? profile)
+ {
+ var vertices = profile is null ? StraightSectionVertices(hatch) : default;
+ if (profile is null && vertices.IsEmpty) return null;
+ double length = double.Hypot(axis.Length, planes.Rise);
+ if (!double.IsFinite(length)) return null;
+ double cos = axis.Length / length, sin = planes.Rise / length;
+ var tangent = new BeamVector(cos * axis.Dx, cos * axis.Dy, sin);
+ var right = new BeamVector(axis.Dy, -axis.Dx, 0);
+ var up = new BeamVector(-sin * axis.Dx, -sin * axis.Dy, cos);
+ var u = right * axis.CosRoll + up * axis.SinRoll;
+ var v = right * -axis.SinRoll + up * axis.CosRoll;
+ double startDot = planes.StartNormal.Dot(tangent), endDot = planes.EndNormal.Dot(tangent);
+ if (!planes.StartNormal.IsUnit || !planes.EndNormal.IsUnit ||
+ !(startDot < -JunctionTolerance && endDot > JunctionTolerance))
+ return null;
+
+ var origin = new BeamVector(axis.X, axis.Y, axis.Z);
+ var end = new BeamVector(axis.X + axis.Dx * axis.Length, axis.Y + axis.Dy * axis.Length, axis.Z + planes.Rise);
+ var heading = new BeamVector(axis.Dx, axis.Dy, 0);
+ if (ProjectEnd(vertices, planes.StartNormal, startDot, origin, out double startInset) is not { } first ||
+ ProjectEnd(vertices, planes.EndNormal, endDot, end, out double endInset, beginning: false) is not { } last ||
+ !(axis.Length + endInset - startInset > JunctionTolerance))
+ return null;
+
+ var box = MakeBoundingBox((Math.Min(first.XMin, last.XMin), Math.Min(first.YMin, last.YMin),
+ Math.Max(first.XMax, last.XMax), Math.Max(first.YMax, last.YMax)),
+ Math.Min(first.ZMin, last.ZMin), Math.Max(first.ZMax, last.ZMax));
+ return box is null ? null : new BeamCaps(box, first, last, startInset, axis.Length + endInset);
+
+ PlaBoundingBox? ProjectEnd(ReadOnlySpan points, BeamVector normal, double axisDot, BeamVector point,
+ out double inset, bool beginning = true)
+ {
+ inset = 0;
+ // Slide each profile coordinate along its generator until it meets the saved plane.
+ var a = u + tangent * (-normal.Dot(u) / axisDot);
+ var b = v + tangent * (-normal.Dot(v) / axisDot);
+ var axial = ProjectBeamSection(points, profile?.Components, a.Dot(heading), b.Dot(heading));
+ var x = ProjectBeamSection(points, profile?.Components, a.X, b.X);
+ var y = ProjectBeamSection(points, profile?.Components, a.Y, b.Y);
+ var z = ProjectBeamSection(points, profile?.Components, a.Z, b.Z);
+ if (axial is not { } shifts || x is not { } px || y is not { } py || z is not { } pz) return null;
+ inset = beginning ? shifts.Max : shifts.Min;
+ return new PlaBoundingBox(point.X + px.Min, point.Y + py.Min, point.Z + pz.Min,
+ point.X + px.Max, point.Y + py.Max, point.Z + pz.Max);
+ }
+ }
+
+ private static (double Min, double Max)? ProjectBeamSection(ReadOnlySpan vertices, IReadOnlyList? components,
+ double u, double z)
+ {
+ double min = double.PositiveInfinity, max = double.NegativeInfinity;
+ if (components is null)
+ {
+ for (int i = 0; i < vertices.Length; i += 16) Include(ReadDouble(vertices, i), ReadDouble(vertices, i + 8));
+ }
+ else
+ {
+ double angle = Math.Atan2(z, u);
+ foreach (var component in components)
+ {
+ var ring = component.Rings[0];
+ foreach (var point in ring) Include(point.U, point.Z);
+ foreach (var arc in component.Arcs ?? [])
+ {
+ if (arc.RingIndex != 0) continue;
+ var p = ring[arc.StartVertexIndex];
+ var q = ring[(arc.StartVertexIndex + 1) % ring.Count];
+ if (ReadCircularEdge(new(p.U, p.Z), new(q.U, q.Z), arc.SweepRadians, out _) is not { } edge)
+ return null;
+ if (edge.IncludesAngle(angle))
+ {
+ var point = edge.AtAngle(angle);
+ Include(point.X, point.Y);
+ }
+ if (edge.IncludesAngle(angle + Math.PI))
+ {
+ var point = edge.AtAngle(angle + Math.PI);
+ Include(point.X, point.Y);
+ }
+ }
+ }
+ }
+ return double.IsFinite(min) && double.IsFinite(max) ? (min, max) : null;
+
+ void Include(double x, double y)
+ {
+ double value = u * x + z * y;
+ min = Math.Min(min, value);
+ max = Math.Max(max, value);
+ }
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.BeamWallCuts.cs b/src/PlaIO/Internal/ElementReader.BeamWallCuts.cs
new file mode 100644
index 0000000..cd17ab0
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.BeamWallCuts.cs
@@ -0,0 +1,134 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid ElementLabelClass = new("1601b50c-a61f-447c-8b74-0f578c003d88");
+ private static readonly Guid WallLabelRelation = new("5dd68b40-d2b2-4e13-9238-8343cdb6c423");
+ private static readonly Guid ColumnLabelRelation = new("f73ad2dc-973b-4e70-9787-a3c6fee4a2bf");
+
+ private sealed record SavedLabels(Dictionary<(Guid Label, Guid Role), Guid> Owners, HashSet Indexed);
+
+ private static SavedLabels ReadLabelOwners(PlaDocument document,
+ Dictionary> records, HashSet labelClasses)
+ {
+ var owners = new Dictionary<(Guid Label, Guid Role), Guid>();
+ var indexed = records.Values.SelectMany(bucket => bucket).Select(record => record.ObjectId).ToHashSet();
+ if (indexed.Count != 0)
+ {
+ foreach (var pool in document.FindCompressedPools())
+ {
+ if (pool.TotalDecompressed % ExtentUnit != 0 ||
+ !records.TryGetValue((ulong)(pool.TotalDecompressed / ExtentUnit), out var matches)) continue;
+ var bytes = pool.Decode();
+ foreach (var record in matches)
+ if (ReadIndexedPayload(bytes, record) is { } body) AddLabel(record.ObjectId, body);
+ }
+ }
+ foreach (var block in document.Blocks)
+ if (block.Tag == "BL" && block.Version == 1 && block.Guid is { } id && labelClasses.Contains(block.Kind))
+ AddLabel(id, document.ReadPayload(block));
+ return new SavedLabels(owners, indexed);
+
+ void AddLabel(Guid id, byte[] body)
+ {
+ bool validClass = body.Length >= 16 && new Guid(body.AsSpan(0, 16)) == ElementLabelClass;
+ AddOwner(id, validClass ? ReadSingleRelation(body, WallLabelRelation, 0x12, requireSection: true) : Guid.Empty,
+ WallLabelRelation);
+ AddOwner(id, validClass ? ReadSingleRelation(body, ColumnLabelRelation, 0x12, requireSection: true) : Guid.Empty,
+ ColumnLabelRelation);
+ }
+
+ void AddOwner(Guid label, Guid owner, Guid role)
+ {
+ if (!owners.TryAdd((label, role), owner) && owners[(label, role)] != owner)
+ owners[(label, role)] = Guid.Empty;
+ }
+ }
+
+ private static bool ProfileWallLeavesBeamCaps(ModelGeometry geometry, Guid beamId, int? layer, Guid junction,
+ uint priority, BeamCaps caps)
+ {
+ if (priority == 0 || geometry.Read(junction, WallBeamJunctionClass) is not { } contact ||
+ ReadSingleRelation(contact, BeamWallRelation, requireSection: true) != beamId)
+ return false;
+ Guid wallId = ReadSingleRelation(contact, WallBeamRelation, requireSection: true);
+ if (geometry.Read(wallId, WallClass) is not { } body || !HasGeometryRelation(body, WallBeamRelation, junction))
+ return false;
+ return ProfileWallMissesBoxes(geometry, wallId, body, layer, priority, [caps.First, caps.Last]);
+ }
+
+ private static bool ProfileWallMissesBoxes(ModelGeometry geometry, Guid wallId, byte[] body, int? layer, uint priority,
+ IReadOnlyList boxes, bool allowPartialPlan = false)
+ {
+ var record = body.AsSpan(FindClassFrame(body, WallClass));
+ var location = ReadElementLocation(record, "Wall", 0);
+ var settings = AfterCountedString(record, 197);
+ if (settings.Length < 503 || settings[184] != 0 || settings[238] > 1 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(settings[239..]) != 0 || ReadDouble(settings, 243) != 0 ||
+ location.TopStoryPartition != Guid.Empty || !SameIntersectionGroup(geometry, layer, location.LayerIndex) ||
+ geometry.StoryElevation(location.HomeStoryIndex) is not { } story ||
+ ReadWallProfile(record, settings, wallId, geometry) is not { } profile ||
+ !HasSupportedSlabContacts(record, Guid.Empty, Guid.Empty, (key, id) =>
+ UnjoinedWallChildRelations.Contains(key) || key == WallProfileRelation || key == PlanContourRelation ||
+ key == FirstWallEndRelation || key == SecondWallEndRelation || key == WallColumnRelation ||
+ key == WallSlabRelation || key == WallBeamRelation || key == WallLabelRelation && geometry.OwnsLabel(wallId, id, key)))
+ return false;
+ double originZ = story + ReadDouble(settings, 161);
+ double x = ReadDouble(settings, 0), y = ReadDouble(settings, 8), x1 = ReadDouble(settings, 16), y1 = ReadDouble(settings, 24);
+ double length = double.Hypot(x1 - x, y1 - y);
+ if (!double.IsFinite(originZ) || !double.IsFinite(length) || length <= JunctionTolerance ||
+ ProjectBeamSection(default, profile.Components, 1, 0) is not { } extent)
+ return false;
+ double rx = (y1 - y) / length, ry = (x - x1) / length;
+ var start = new PlaPlanPoint(x, y);
+ var end = new PlaPlanPoint(x1, y1);
+ bool direct = ReadProfileWallRectangle(settings, start, end, extent.Min, extent.Max, allowPartialPlan) is not null;
+ bool reflected = ReadProfileWallRectangle(settings, start, end, -extent.Max, -extent.Min, allowPartialPlan) is not null;
+ if (!direct && !reflected) return false;
+ foreach (var component in profile.Components)
+ {
+ if (geometry.Attributes.Material.GetValueOrDefault(component.BuildingMaterialIndex) is not (> 0 and { } p))
+ return false;
+ if (p <= priority) continue;
+ if (direct && !boxes.All(box => MissesBox(component, box, 1)) ||
+ reflected && !boxes.All(box => MissesBox(component, box, -1)))
+ return false;
+ }
+ return true;
+
+ // An unbounded sweep of the placed wall section also covers possible axial extensions at joins.
+ bool MissesBox(PlaProfileComponent component, PlaBoundingBox cap, int sign)
+ {
+ var (min, max) = ProjectRectangle((cap.XMin, cap.YMin, cap.XMax, cap.YMax), x, y, sign * rx, sign * ry);
+ return ProfileMissesRectangle(component, min - JunctionTolerance, max + JunctionTolerance,
+ cap.ZMin - originZ - JunctionTolerance, cap.ZMax - originZ + JunctionTolerance);
+ }
+ }
+
+ private static bool ProfileMissesRectangle(PlaProfileComponent component, double left, double right, double bottom, double top)
+ {
+ if (!double.IsFinite(left) || !double.IsFinite(right) || !double.IsFinite(bottom) || !double.IsFinite(top) ||
+ !(left < right && bottom < top))
+ return false;
+ var ring = component.Rings[0].Select(p => new PlaPlanPoint(p.U, p.Z)).ToArray();
+ var arced = (component.Arcs ?? []).Where(a => a.RingIndex == 0).ToDictionary(a => a.StartVertexIndex, a => a.SweepRadians);
+ var edges = new SlabEdge[ring.Length];
+ PlaPlanPoint[] corners = [new(left, bottom), new(right, bottom), new(right, top), new(left, top)];
+ for (int i = 0; i < edges.Length; i++)
+ {
+ var start = ring[i];
+ var end = ring[(i + 1) % ring.Length];
+ if (start.X >= left && start.X <= right && start.Y >= bottom && start.Y <= top) return false;
+ if (!arced.TryGetValue(i, out double sweep)) edges[i] = new SlabEdge(start, end, 0);
+ else if (ReadCircularEdge(start, end, sweep, out _) is { } arc) edges[i] = arc;
+ else return false;
+ for (int j = 0; j < corners.Length; j++)
+ if (SlabEdgesIntersect(edges[i], new SlabEdge(corners[j], corners[(j + 1) % corners.Length], 0), null))
+ return false;
+ }
+ return !CurvedRingContainsPoint(ring, edges, corners[0]);
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.Bounds.cs b/src/PlaIO/Internal/ElementReader.Bounds.cs
new file mode 100644
index 0000000..2a618d9
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.Bounds.cs
@@ -0,0 +1,152 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static ReadOnlySpan SlabOutlineFrame => [2, 0, 2, 1];
+
+ private static PlaBoundingBox? ReadSavedWallBox(ReadOnlySpan settings)
+ {
+ if (!HasWallBoxFrame(settings)) return null;
+ return MakeBoundingBox((ReadDouble(settings, 515), ReadDouble(settings, 523),
+ ReadDouble(settings, 531), ReadDouble(settings, 539)), ReadDouble(settings, 547), ReadDouble(settings, 555));
+ }
+
+ private static bool HasWallBoxFrame(ReadOnlySpan settings) =>
+ settings.Length >= 563 && settings[489..].StartsWith(new byte[] { 1, 0, 1, 0, 0, 0 }) &&
+ settings[495..511].IndexOfAnyExcept((byte)0) < 0;
+
+ private static bool HasEmptyWallPlanCache(ReadOnlySpan settings) =>
+ HasWallBoxFrame(settings) && settings[515..547].IndexOfAnyExcept((byte)0) < 0;
+
+ private static PlaBoundingBox? ReadWallBoxWithoutPlanCache(ReadOnlySpan settings, ElementLocation location,
+ (double X0, double Y0, double X1, double Y1)? footprint, PlaWallProfile? profile, Elevations planes, double home)
+ {
+ if (!HasEmptyWallPlanCache(settings)) return null;
+ if (footprint is { } rectangle)
+ {
+ if (settings[547..563].IndexOfAnyExcept((byte)0) < 0) return ProjectBoundingBox(rectangle, planes, home);
+ double lower = ReadDouble(settings, 547), upper = ReadDouble(settings, 555);
+ return Math.Abs(lower - (home + planes.Bottom)) <= JunctionTolerance &&
+ Math.Abs(upper - (home + planes.Top)) <= JunctionTolerance
+ ? MakeBoundingBox(rectangle, lower, upper) : null;
+ }
+
+ if (profile is null || location.TopStoryPartition != Guid.Empty || settings[184] != 0 ||
+ settings[238] > 1 || BinaryPrimitives.ReadUInt32LittleEndian(settings[239..]) != 0 ||
+ ReadDouble(settings, 243) != 0 || settings[547..563].IndexOfAnyExcept((byte)0) >= 0 ||
+ ProjectBeamSection(default, profile.Components, 1, 0) is not { } width ||
+ ProjectBeamSection(default, profile.Components, 0, 1) is not { } height ||
+ Math.Abs(width.Max - width.Min - ReadDouble(settings, 77)) > JunctionTolerance ||
+ ReadDouble(settings, 77) != ReadDouble(settings, 85) ||
+ Math.Abs(height.Max - height.Min - (planes.Top - planes.Bottom)) > JunctionTolerance)
+ return null;
+
+ var start = new PlaPlanPoint(ReadDouble(settings, 0), ReadDouble(settings, 8));
+ var end = new PlaPlanPoint(ReadDouble(settings, 16), ReadDouble(settings, 24));
+ var direct = ReadProfileWallRectangle(settings, start, end, width.Min, width.Max, allowPartial: true);
+ var reflected = ReadProfileWallRectangle(settings, start, end, -width.Max, -width.Min, allowPartial: true);
+ if (direct.HasValue && reflected.HasValue && direct != reflected) return null;
+ return (direct ?? reflected) is { } plan
+ ? MakeBoundingBox(plan, home + planes.Bottom + height.Min, home + planes.Bottom + height.Max) : null;
+ }
+
+ private static PlaBoundingBox? ReadFloorBox(ReadOnlySpan record, string type, Elevations planes, double? story)
+ {
+ ReadOnlySpan polygon;
+ if (type == "Slab")
+ {
+ var settings = AfterCountedString(record, ClassElementIdOffset(type));
+ polygon = ReadSlabOutline(settings);
+ }
+ else
+ {
+ var settings = ReadZoneSettings(record);
+ if (settings.Length < 56 || settings[52] != 0 || settings[53] is not (0 or 1) ||
+ settings[54] != 2 || settings[55] != 1)
+ return null;
+ polygon = settings[52..];
+ }
+
+ return ReadOutlineBounds(polygon) is { } plan ? ProjectBoundingBox(plan, planes, story) : null;
+ }
+
+ private static ReadOnlySpan ReadSlabOutline(ReadOnlySpan settings)
+ {
+ if (settings.Length >= 166 && settings[166..].StartsWith(SlabOutlineFrame))
+ return settings[166..];
+ if (settings.Length >= 270 && settings[165..].StartsWith(new byte[] { 20, 0, 0, 0 }) &&
+ settings[270..].StartsWith(SlabOutlineFrame))
+ return settings[270..];
+ return default;
+ }
+
+ private static (double X0, double Y0, double X1, double Y1)? ReadOutlineBounds(ReadOnlySpan polygon)
+ {
+ const int headerSize = 71;
+ if (polygon.Length < headerSize || !polygon[8..].StartsWith(new byte[] { 1, 31, 0 }))
+ return null;
+
+ uint size = BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..]);
+ uint points = BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]);
+ uint arcs = BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]);
+ uint rings = BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]);
+ if (size < headerSize || size > polygon.Length || points < 4 || points > (size - headerSize) / 16 ||
+ rings == 0 || rings > points / 4 || arcs > points - rings)
+ return null;
+
+ var (x0, y0, x1, y1) = (ReadDouble(polygon, 11), ReadDouble(polygon, 19), ReadDouble(polygon, 27), ReadDouble(polygon, 35));
+ int footer = headerSize + 16 * (int)points;
+ for (int offset = 0; offset < points; offset++)
+ {
+ double x = ReadDouble(polygon, headerSize + 16 * offset), y = ReadDouble(polygon, headerSize + 16 * offset + 8);
+ if (!(x >= x0 - JunctionTolerance && x <= x1 + JunctionTolerance &&
+ y >= y0 - JunctionTolerance && y <= y1 + JunctionTolerance))
+ return null;
+ }
+
+ if (arcs > 0)
+ {
+ if (size - footer < 16 || arcs > (size - footer - 16) / 16 ||
+ polygon.Slice(footer, 16).IndexOfAnyExcept((byte)0) >= 0)
+ return null;
+ footer += 16;
+ for (int i = 0; i < arcs; i++, footer += 16)
+ {
+ uint start = BinaryPrimitives.ReadUInt32LittleEndian(polygon[footer..]);
+ uint end = BinaryPrimitives.ReadUInt32LittleEndian(polygon[(footer + 4)..]);
+ if (start == 0 || start >= points || end > points || end != start + 1 ||
+ !double.IsFinite(ReadDouble(polygon, footer + 8)))
+ return null;
+ }
+ }
+
+ if (size - footer < 4 * (rings + 1) || BinaryPrimitives.ReadUInt32LittleEndian(polygon[footer..]) != 0)
+ return null;
+ uint first = 0;
+ for (int ring = 1; ring <= rings; ring++)
+ {
+ uint last = BinaryPrimitives.ReadUInt32LittleEndian(polygon[(footer + 4 * ring)..]);
+ if (last > points || last < first + 4 ||
+ !polygon.Slice(headerSize + 16 * (int)first, 16).SequenceEqual(polygon.Slice(headerSize + 16 * ((int)last - 1), 16)))
+ return null;
+ first = last;
+ }
+
+ return first == points ? (x0, y0, x1, y1) : null;
+ }
+
+ private static PlaBoundingBox? ProjectBoundingBox((double X0, double Y0, double X1, double Y1) plan,
+ Elevations planes, double? story) =>
+ story is { } level ? MakeBoundingBox(plan, planes.Bottom + level, planes.Top + level) : null;
+
+ private static PlaBoundingBox? MakeBoundingBox((double X0, double Y0, double X1, double Y1) plan, double low, double high)
+ {
+ var (x0, y0, x1, y1) = plan;
+ return double.IsFinite(x0) && double.IsFinite(y0) && double.IsFinite(x1) && double.IsFinite(y1) &&
+ double.IsFinite(low) && double.IsFinite(high) && x0 < x1 && y0 < y1 && low <= high
+ ? new PlaBoundingBox(x0, y0, low, x1, y1, high) : null;
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.CircularColumns.cs b/src/PlaIO/Internal/ElementReader.CircularColumns.cs
new file mode 100644
index 0000000..ea10ea4
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.CircularColumns.cs
@@ -0,0 +1,77 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid CircularColumnSectionClass = new("d6c12939-d905-40e0-aa57-f7c8d687dc7b");
+
+ private static Elevations? ReadCircularColumn(Guid memo, ReadOnlySpan section, ReadOnlySpan lower,
+ ReadOnlySpan upper, PlaPlanPoint origin, ElementLocation location, ModelGeometry geometry,
+ List<(Guid Key, Guid Id)>? junctions, out PlaBoundingBox? boundingBox, out PlaColumnExtrusion? extrusion)
+ {
+ boundingBox = null;
+ extrusion = null;
+ if (ReadSingleRelation(section, SectionProfileRelation, requireSection: true) != memo ||
+ ReadCircularColumnSection(section, out int material) is not { } radius ||
+ !IsHorizontal(lower) || !IsHorizontal(upper) || !(ReadDouble(lower, 40) < 0 && ReadDouble(upper, 40) > 0) ||
+ CheckedElevations(ReadDouble(lower, 16), ReadDouble(upper, 16)) is not { } nominal || nominal.Bottom >= nominal.Top)
+ return null;
+
+ var plan = (origin.X - radius, origin.Y - radius, origin.X + radius, origin.Y + radius);
+ bool solid = true;
+ var heights = junctions is null ? nominal : ResolveColumnJunctions(geometry, memo, junctions, location, material,
+ nominal, plan, nominal.Bottom, nominal.Top, profiled: false, checkSolid: true, out _, out solid);
+ if (solid && heights is { } span && geometry.StoryElevation(location.HomeStoryIndex) is { } home &&
+ ProjectBoundingBox(plan, span, home) is { } box && box.ZMin < box.ZMax &&
+ Math.PI * radius * radius * (span.Top - span.Bottom) is > 0 and { } volume && double.IsFinite(volume))
+ {
+ var (capArea, perimeter) = CircularScheduleSection(radius);
+ double lateralArea = perimeter * (span.Top - span.Bottom);
+ boundingBox = box;
+ extrusion = new PlaColumnExtrusion(origin, [], new(box.ZMin, 0, 0), new(box.ZMax, 0, 0), box, volume)
+ {
+ CircularRadius = radius,
+ ScheduledCapArea = capArea,
+ ScheduledLateralArea = double.IsFinite(lateralArea) ? lateralArea : null,
+ };
+ }
+ return heights;
+ }
+
+ private static (double Area, double Perimeter) CircularScheduleSection(double radius)
+ {
+ // Listing quantities use equal subdivisions of each quadrant with a 1 mm sagitta.
+ const double sagitta = 0.001;
+ double halfStep = 2 * Math.Asin(Math.Sqrt(Math.Min(0.5, sagitta / radius / 2)));
+ double quadrantSegments = Math.Max(2, Math.Ceiling(Math.PI / (4 * halfStep)));
+ double step = Math.PI / (2 * quadrantSegments);
+ return (Math.PI * radius * radius * (Math.Sin(step) / step),
+ Math.Tau * radius * (Math.Sin(step / 2) / (step / 2)));
+ }
+
+ private static double? ReadCircularColumnSection(ReadOnlySpan section, out int material)
+ {
+ material = 0;
+ var hatch = ReadSectionHatch(section, 141, 482);
+ if (hatch.Length < 175 || BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]) != 4) return null;
+ double diameter = ReadDouble(section, 91);
+ double radius = diameter / 2;
+ if (!double.IsFinite(radius) || radius <= 0 || diameter != ReadDouble(section, 99)) return null;
+
+ var points = hatch[59..];
+ if (points[..16].IndexOfAnyExcept((byte)0) >= 0 || !IsCorner(points[16..], -radius, 0) ||
+ !IsCorner(points[32..], radius, 0) || !points.Slice(16, 16).SequenceEqual(points.Slice(48, 16))) return null;
+
+ // Two semicircles close the only contour, between the two stored ends of a diameter.
+ var arcs = points[64..];
+ if (!arcs.StartsWith(new byte[] { 1, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0 }) ||
+ ReadDouble(arcs, 14) != Math.PI || BinaryPrimitives.ReadUInt32LittleEndian(arcs[22..]) != 2 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(arcs[26..]) != 3 || ReadDouble(arcs, 30) != Math.PI ||
+ !arcs[38..].StartsWith(new byte[] { 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0 })) return null;
+
+ material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]);
+ return radius;
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.Classifications.cs b/src/PlaIO/Internal/ElementReader.Classifications.cs
new file mode 100644
index 0000000..13c8393
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.Classifications.cs
@@ -0,0 +1,141 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid ClassificationSystemClass = new("420f4c27-70b8-43c2-9d9d-f74ef1ee9b47");
+ private static readonly Guid ClassificationItemClass = new("9be1f9d1-13d9-45ff-813e-01c7846cd0c2");
+ private static readonly Guid ClassificationRootLink = new("e88a0cef-00c8-45d1-ae13-80c6616ad0f8");
+ private static readonly Guid ClassificationParentChildLink = new("8d79244e-35bb-412f-8148-2b4a8839159a");
+ private static readonly Guid ClassificationAssignmentLink = new("9534032d-da8d-4c44-b42b-6363688cafc6");
+
+ internal static (IReadOnlyList Systems, Dictionary> Assignments)
+ ReadClassificationCatalog(PlaDocument document, IReadOnlyList classes,
+ Dictionary? elements = null)
+ {
+ var kinds = classes.Where(c => c.Guid == ClassificationSystemClass || c.Guid == ClassificationItemClass)
+ .ToDictionary(c => c.Number, c => c.Guid);
+ var assignments = new Dictionary>();
+ if (!kinds.ContainsValue(ClassificationSystemClass)) return ([], assignments);
+ var bodies = ReadClassRecords(document, kinds);
+
+ var systems = new List();
+ var visited = new HashSet();
+ foreach (var (systemId, body) in bodies.OrderBy(pair => pair.Key))
+ {
+ if (new Guid(body.AsSpan(0, 16)) != ClassificationSystemClass) continue;
+ var fields = ReadClassificationFrame(body, 1, out var relations);
+ if (fields.IsEmpty) continue;
+ string name = ReadFramedText(ref fields);
+ string version = ReadFramedText(ref fields);
+ DateOnly? date = ReadClassificationDate(ref fields);
+ string description = ReadFramedText(ref fields);
+ string source = ReadFramedText(ref fields);
+ CheckClassificationFieldEnd(fields);
+ var links = ReadClassificationLinks(relations, rootTag: 0x11);
+ var root = ReadItem(links.Root);
+ if (root.Links.Root != systemId || root.Links.Parent != Guid.Empty || !visited.Add(links.Root))
+ throw new InvalidDataException("The classification system and its root have conflicting links.");
+
+ var items = new List();
+ var classified = new HashSet();
+ var pending = new Stack<(Guid Id, Guid Parent)>();
+ QueueChildren(links.Root, root.Links.Children);
+ while (pending.TryPop(out var entry))
+ {
+ if (!visited.Add(entry.Id)) throw new InvalidDataException("The classification tree repeats an item.");
+ var item = ReadItem(entry.Id);
+ if (item.Links.Parent != entry.Parent || item.Links.Root != Guid.Empty)
+ throw new InvalidDataException("A classification item and its parent have conflicting links.");
+ items.Add(new PlaClassificationItem(entry.Id, entry.Parent == links.Root ? null : entry.Parent,
+ item.Id, item.Name, item.Description));
+ QueueChildren(entry.Id, item.Links.Children);
+
+ if (elements is null) continue;
+ foreach (Guid element in item.Links.Elements)
+ {
+ if (!elements.ContainsKey(element)) continue;
+ if (!classified.Add(element))
+ throw new InvalidDataException("An element has conflicting assignments within a classification system.");
+ if (!assignments.TryGetValue(element, out var saved)) assignments.Add(element, saved = []);
+ saved.Add(new PlaClassificationAssignment(systemId, entry.Id));
+ }
+ }
+ systems.Add(new PlaClassificationSystem(systemId, name, description, source, version, date, items.AsReadOnly()));
+
+ void QueueChildren(Guid parent, Guid[] children)
+ {
+ for (int i = children.Length - 1; i >= 0; i--)
+ pending.Push((children[i], parent));
+ }
+ }
+ return (systems.AsReadOnly(), assignments);
+
+ (string Id, string Name, string Description, ClassificationLinks Links) ReadItem(Guid id)
+ {
+ if (!bodies.TryGetValue(id, out var body) || new Guid(body.AsSpan(0, 16)) != ClassificationItemClass)
+ throw new InvalidDataException($"Classification item {id} is missing.");
+ var fields = ReadClassificationFrame(body, 3, out var relations);
+ string code = ReadFramedText(ref fields);
+ string name = ReadFramedText(ref fields);
+ string description = ReadFramedText(ref fields);
+ CheckClassificationFieldEnd(fields);
+ return (code, name, description, ReadClassificationLinks(relations, rootTag: 0x12));
+ }
+ }
+
+ private static ReadOnlySpan ReadClassificationFrame(ReadOnlySpan body, ushort fieldKind,
+ out ReadOnlySpan relations)
+ {
+ relations = default;
+ if (body.Length < 59 || BinaryPrimitives.ReadUInt16LittleEndian(body[39..]) != 1 ||
+ body[41] is not (0x82 or 0x83) || !body[42..].StartsWith(RecordFrameTail) ||
+ BinaryPrimitives.ReadUInt16LittleEndian(body[57..]) != fieldKind) return default;
+ return ReadRecordFields(body, 59, out relations);
+ }
+
+ private static DateOnly? ReadClassificationDate(ref ReadOnlySpan fields)
+ {
+ if (fields.Length < 6) throw new InvalidDataException("The classification date is truncated.");
+ int year = BinaryPrimitives.ReadUInt16LittleEndian(fields);
+ int month = BinaryPrimitives.ReadUInt16LittleEndian(fields[2..]);
+ int day = BinaryPrimitives.ReadUInt16LittleEndian(fields[4..]);
+ fields = fields[6..];
+ if (year == 0 && month == 0 && day == 0) return null;
+ if (year is < 1 or > 9999 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month))
+ throw new InvalidDataException("The classification date is invalid.");
+ return new DateOnly(year, month, day);
+ }
+
+ private static void CheckClassificationFieldEnd(ReadOnlySpan fields)
+ {
+ if (fields.Length != 1 || fields[0] > 1)
+ throw new InvalidDataException("The classification field frame has an invalid final flag.");
+ }
+
+ private static ClassificationLinks ReadClassificationLinks(ReadOnlySpan data, byte rootTag)
+ {
+ Guid root = Guid.Empty, parent = Guid.Empty;
+ Guid[]? children = null, elements = null;
+ while (data.Length >= 17)
+ {
+ var targets = ReadRelationshipEntry(ref data, out byte tag, out Guid key);
+ if (key == ClassificationRootLink && tag == rootTag && root == Guid.Empty)
+ root = ReadRelationshipTarget(targets);
+ else if (key == ClassificationParentChildLink && tag == 0x12 && parent == Guid.Empty)
+ parent = ReadRelationshipTarget(targets);
+ else if (key == ClassificationParentChildLink && tag is (1 or 0x11) && children is null)
+ children = ReadRelationshipTargets(targets);
+ else if (key == ClassificationAssignmentLink && tag is (2 or 0x12) && elements is null)
+ elements = ReadRelationshipTargets(targets);
+ else if (key == ClassificationRootLink || key == ClassificationParentChildLink || key == ClassificationAssignmentLink)
+ throw new InvalidDataException("A classification record has conflicting relationship roles.");
+ }
+ CheckRelationshipEnd(data);
+ return new ClassificationLinks(root, parent, children ?? [], elements ?? []);
+ }
+
+ private readonly record struct ClassificationLinks(Guid Root, Guid Parent, Guid[] Children, Guid[] Elements);
+}
diff --git a/src/PlaIO/Internal/ElementReader.ColumnCuts.cs b/src/PlaIO/Internal/ElementReader.ColumnCuts.cs
new file mode 100644
index 0000000..375c48a
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.ColumnCuts.cs
@@ -0,0 +1,481 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private readonly record struct RectangularColumnPlan(PlaPlanPoint Origin, double HalfWidth, double HalfDepth, double Angle);
+
+ private static bool JoinedBeamClearsColumn(ModelGeometry geometry, Guid beam, Guid junction,
+ ElementLocation location, double home, RectangularColumnPlan plan)
+ {
+ if (geometry.Read(beam, BeamMemoClass) is not { } memo ||
+ ReadBeamPrism(geometry, beam, memo, home) is not { SinRoll: 0 } axis ||
+ !SameIntersectionGroup(geometry, axis.Layer, location.LayerIndex)) return false;
+ var hatch = ReadBeamHatch(geometry, beam, memo);
+ if (ReadBeamRectangle(hatch) is not { } rectangle ||
+ geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not (> 0 and { } priority))
+ return false;
+
+ var (sin, cos) = Math.SinCos(plan.Angle);
+ var ring = new List(4)
+ {
+ Project(-plan.HalfWidth, -plan.HalfDepth), Project(plan.HalfWidth, -plan.HalfDepth),
+ Project(plan.HalfWidth, plan.HalfDepth), Project(-plan.HalfWidth, plan.HalfDepth),
+ };
+ double half = rectangle.HalfWidth;
+ ring = ClipHalfPlane(ring, xAxis: false, -half - JunctionTolerance, keepBelow: false);
+ ring = ClipHalfPlane(ring, xAxis: false, half + JunctionTolerance, keepBelow: true);
+ double start = 0, end = axis.Length;
+ double first = ring.Count == 0 ? double.PositiveInfinity : ring.Min(p => p.X);
+ double last = ring.Count == 0 ? double.NegativeInfinity : ring.Max(p => p.X);
+ bool OutsideCaps() => last < start - JunctionTolerance || first > end + JunctionTolerance;
+ return OutsideCaps() && HasOnlyBeamTargetContact(memo, BeamColumnRelation, junction, axis.Owner, BoundContact) && OutsideCaps();
+
+ PlaPlanPoint Project(double u, double v)
+ {
+ double x = (plan.Origin.X - axis.X) + (cos * u - sin * v);
+ double y = (plan.Origin.Y - axis.Y) + (sin * u + cos * v);
+ return new(x * axis.Dx + y * axis.Dy, x * axis.Dy - y * axis.Dx);
+ }
+
+ bool BoundContact(Guid role, Guid contact)
+ {
+ if (role == BeamColumnRelation || role == BeamSlabRelation || role == BeamWallRelation)
+ // Structural cuts can only remove material from this beam.
+ return ReadBeamStructuralNeighbor(geometry, beam, role, contact) is not null;
+
+ var collision = ReadBeamAxisJunction(geometry, beam, role, contact, withoutPoint: true);
+ if ((collision ?? ReadBeamAxisJunction(geometry, beam, role, contact)) is not { } join ||
+ geometry.Read(join.Peer, BeamMemoClass) is not { } peerMemo || !HasGeometryRelation(peerMemo, join.Reciprocal, contact) ||
+ ReadBeamPrism(geometry, join.Peer, peerMemo, home) is not { SinRoll: 0 } peer ||
+ !SameIntersectionGroup(geometry, axis.Layer, peer.Layer) ||
+ ReadBeamContactExtents(geometry, join.Peer, peerMemo, peer) is not { } section ||
+ Math.Abs(section.Left + half) > JunctionTolerance || Math.Abs(section.Right - half) > JunctionTolerance ||
+ Math.Abs(section.Height.Bottom - (axis.Z - rectangle.Depth)) > JunctionTolerance ||
+ Math.Abs(section.Height.Top - axis.Z) > JunctionTolerance)
+ return false;
+
+ if (collision is not null)
+ {
+ // Bound the point-free crossing by both section strips in the cutter's coordinates.
+ double slope = axis.Dx * peer.Dy - axis.Dy * peer.Dx;
+ if (Math.Abs(slope) <= JunctionTolerance) return false;
+ double station = ((peer.X - axis.X) * peer.Dy - (peer.Y - axis.Y) * peer.Dx) / slope;
+ var crossing = ProjectBeamJunctionInterval(axis, peer, axis.X + station * axis.Dx, axis.Y + station * axis.Dy,
+ -half, half, section.Left, section.Right);
+ return crossing is { } bounds && bounds.Min > JunctionTolerance && bounds.Max < axis.Length - JunctionTolerance;
+ }
+
+ // The same join can be recorded with an end role in several evaluation contexts. Use the axis endpoints.
+ bool ownEnd = IsOnBeamJoint(axis, join.X, join.Y, end: true);
+ bool peerEnd = IsOnBeamJoint(peer, join.X, join.Y, end: true);
+ if ((!ownEnd && !IsOnBeamJoint(axis, join.X, join.Y, end: false)) ||
+ (!peerEnd && !IsOnBeamJoint(peer, join.X, join.Y, end: false))) return false;
+
+ double dot = axis.Dx * peer.Dx + axis.Dy * peer.Dy;
+ if (Math.Abs(axis.Dx * peer.Dy - axis.Dy * peer.Dx) <= JunctionTolerance)
+ {
+ var peerHatch = ReadBeamHatch(geometry, join.Peer, peerMemo);
+ return ownEnd && peerEnd && dot > 0 && Math.Abs(axis.Length - peer.Length) <= JunctionTolerance &&
+ double.Hypot(axis.X - peer.X, axis.Y - peer.Y) <= JunctionTolerance && !peerHatch.IsEmpty &&
+ geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(peerHatch[18..])) is > 0 and { } p &&
+ p < priority;
+ }
+
+ // A joined cap stays within the intersection of the matching section strips.
+ if (ProjectBeamJunctionInterval(axis, peer, join.X, join.Y, -half, half, section.Left, section.Right) is not { } reach)
+ return false;
+ start = Math.Min(start, reach.Min);
+ end = Math.Max(end, reach.Max);
+ return true;
+ }
+ }
+
+ private static List<(Guid Memo, Guid Junction, uint Priority)>? ReadColumnBeamCutters(ModelGeometry geometry,
+ Guid memoId, List<(Guid Key, Guid Id)> contacts, ElementLocation location, uint priority, Elevations range, bool profiled)
+ {
+ var cutters = new List<(Guid Memo, Guid Junction, uint Priority)>();
+ foreach (var (key, id) in contacts)
+ {
+ var (kind, role) = key == ColumnBeamRelation ? (BeamColumnJunctionClass, BeamColumnRelation) :
+ key == ColumnSlabRelation ? (SlabColumnJunctionClass, SlabColumnRelation) : (WallColumnJunctionClass, WallColumnRelation);
+ if (geometry.Read(id, kind) is not { } joint || ReadSingleRelation(joint, key, requireSection: true) != memoId)
+ return null;
+ Guid peer = ReadSingleRelation(joint, role, requireSection: true);
+ if (key == ColumnBeamRelation)
+ {
+ if (ReadBeamPriority(geometry, peer, id) is not (> 0 and { } beamPriority)) return null;
+ if (!profiled && geometry.Read(peer, BeamMemoClass) is { } beamMemo &&
+ geometry.Read(ReadSingleRelation(beamMemo, SectionProfileRelation, 0x11, requireSection: true), RectangularSectionClass) is null)
+ {
+ if (ReadBeamPrism(geometry, peer, beamMemo, 0) is not { } axis ||
+ ReadColumnCutterEnvelope(geometry, peer, beamMemo, axis) is not { } envelope) return null;
+ beamPriority = envelope.Priority;
+ }
+ if (beamPriority > priority) cutters.Add((peer, id, beamPriority));
+ }
+ else if (key == ColumnSlabRelation)
+ {
+ if (geometry.Read(peer, SlabClass) is not { } body || !HasGeometryRelation(body, role, id)) return null;
+ var record = body.AsSpan(FindClassFrame(body, SlabClass));
+ var settings = AfterCountedString(record, ClassElementIdOffset("Slab"));
+ if (ReadSlabPriority(settings, geometry.Attributes) is not (> 0 and { } slabPriority) || slabPriority > priority &&
+ !SlabKeepsPlanes(geometry, record, settings, location, priority, range.Top, range.Bottom, range, checkSkins: true))
+ return null;
+ }
+ else if (geometry.Read(peer, WallClass) is not { } wall || !HasGeometryRelation(wall, role, id) ||
+ ReadWallPriority(geometry, peer, wall) is not (> 0 and { } wallPriority) || wallPriority > priority ||
+ !profiled && WallMayWrapColumn(geometry.Attributes, ReadWallSettings(wall)))
+ return null;
+ }
+ return cutters;
+ }
+
+ private static Elevations[]? ReadColumnBeamBands(ModelGeometry geometry, Guid memoId, List<(Guid Key, Guid Id)> contacts,
+ ElementLocation location, uint priority, double home, Elevations range,
+ (double X0, double Y0, double X1, double Y1) section, PlaPlanPoint origin, out List? partialMasks)
+ {
+ partialMasks = null;
+ if (ReadColumnBeamCutters(geometry, memoId, contacts, location, priority, range, profiled: true) is not { } cutters)
+ return null;
+ var active = cutters.Select(c => c.Memo).ToHashSet();
+ var bounds = new Dictionary();
+ var throughSpans = new List<(Guid Memo, double Start, double End)>();
+ var cuts = new List();
+ var masks = new List();
+ bool partial = false;
+ foreach (var (peer, id, beamPriority) in cutters)
+ {
+ if (geometry.Read(peer, BeamMemoClass) is not { } memo ||
+ ReadBeamPrism(geometry, peer, memo, home) is not { } axis ||
+ !SameIntersectionGroup(geometry, axis.Layer, location.LayerIndex)) return null;
+ var hatch = ReadBeamHatch(geometry, peer, memo);
+ if (BeamSectionElevations(axis, hatch) is not { } beam) return null;
+ if (DisjointHeights(beam.Bottom, beam.Top, range)) continue;
+ var limits = (Start: (Right: 0.0, Left: 0.0), End: (Right: axis.Length, Left: axis.Length));
+ var miters = new List();
+ var requiredMiters = new List();
+ if (axis.SinRoll != 0 || ReadBeamRectangle(hatch) is not { } rectangle ||
+ !HasOnlyBeamTargetContact(memo, BeamColumnRelation, id, axis.Owner, (r, j) =>
+ BeamKeepsColumnBand(geometry, peer, axis, r, j, home, section, beamPriority, priority,
+ rectangle, active, throughSpans, miters, requiredMiters, ref limits)) ||
+ requiredMiters.Any(required => !miters.Any(required.Matches)))
+ return null;
+
+ double fullStart = Math.Max(limits.Start.Right, limits.Start.Left);
+ double fullEnd = Math.Min(limits.End.Right, limits.End.Left);
+ if (fullEnd - fullStart <= JunctionTolerance) return null;
+ bounds[peer] = (fullStart, fullEnd);
+ var (start, end) = ProjectRectangle(section, axis.X, axis.Y, axis.Dx, axis.Dy);
+ var (left, right) = ProjectRectangle(section, axis.X, axis.Y, axis.Dy, -axis.Dx);
+ if (end <= Math.Min(limits.Start.Right, limits.Start.Left) + JunctionTolerance ||
+ start >= Math.Max(limits.End.Right, limits.End.Left) - JunctionTolerance ||
+ right <= -rectangle.HalfWidth + JunctionTolerance || left >= rectangle.HalfWidth - JunctionTolerance)
+ continue;
+ if (start < fullStart - JunctionTolerance || end > fullEnd + JunctionTolerance ||
+ left < -rectangle.HalfWidth - JunctionTolerance || right > rectangle.HalfWidth + JunctionTolerance)
+ partial = true;
+ var cut = new Elevations(Math.Max(range.Bottom, beam.Bottom), Math.Min(range.Top, beam.Top));
+ cuts.Add(cut);
+ double x = axis.X - origin.X, y = axis.Y - origin.Y;
+ double width = rectangle.HalfWidth;
+ masks.Add(new ColumnBeamMask(cut.Bottom, cut.Top,
+ [At(limits.Start.Right, width), At(limits.End.Right, width),
+ At(limits.End.Left, -width), At(limits.Start.Left, -width)]));
+
+ PlaPlanPoint At(double station, double across) =>
+ new(x + axis.Dx * station + axis.Dy * across, y + axis.Dy * station - axis.Dx * across);
+ }
+
+ if (throughSpans.Any(s => !bounds.TryGetValue(s.Memo, out var span) ||
+ s.Start < span.Start - JunctionTolerance || s.End > span.End + JunctionTolerance))
+ return null;
+ if (partial)
+ {
+ partialMasks = masks;
+ return null;
+ }
+ var bands = new List();
+ double cursor = range.Bottom;
+ foreach (var cut in cuts.OrderBy(c => c.Bottom))
+ {
+ if (cut.Bottom > cursor + JunctionTolerance) bands.Add(new Elevations(cursor, cut.Bottom));
+ cursor = Math.Max(cursor, cut.Top);
+ }
+ if (range.Top > cursor + JunctionTolerance) bands.Add(new Elevations(cursor, range.Top));
+ return bands.Count > 0 ? bands.ToArray() : null;
+ }
+
+ private static List? ReadCoextensiveColumnBeamCut(ModelGeometry geometry, Guid memoId,
+ List<(Guid Key, Guid Id)> contacts, ElementLocation location, uint priority, double home, Elevations range,
+ PlaPlanPoint origin, PlaPlanPoint[] ring)
+ {
+ if (ReadColumnBeamCutters(geometry, memoId, contacts, location, priority, range, profiled: false) is not { Count: > 0 } cutters)
+ return null;
+ var strongest = cutters.MaxBy(c => c.Priority);
+ if (geometry.Read(strongest.Memo, BeamMemoClass) is not { } mainMemo ||
+ ReadBeamPrism(geometry, strongest.Memo, mainMemo, home) is not { SinRoll: 0 } main ||
+ !SameIntersectionGroup(geometry, location.LayerIndex, main.Layer) ||
+ geometry.Read(ReadSingleRelation(mainMemo, SectionProfileRelation, 0x11, requireSection: true), RectangularSectionClass) is null ||
+ ReadBeamRectangle(ReadBeamHatch(geometry, strongest.Memo, mainMemo)) is not { } rectangle)
+ return null;
+
+ double bottom = main.Z - rectangle.Depth, top = main.Z, half = rectangle.HalfWidth;
+ if (DisjointHeights(bottom, top, range)) return null;
+ var group = cutters.Select(c => c.Memo).ToHashSet();
+ foreach (var (id, junction, _) in cutters)
+ {
+ if (id == strongest.Memo)
+ {
+ if (!HasOnlyBeamTargetContact(mainMemo, BeamColumnRelation, junction, main.Owner,
+ (role, contact) => PreservesCut(id, main, role, contact))) return null;
+ continue;
+ }
+
+ if (geometry.Read(id, BeamMemoClass) is not { } memo ||
+ ReadBeamPrism(geometry, id, memo, home) is not { SinRoll: 0 } axis ||
+ !SameIntersectionGroup(geometry, main.Layer, axis.Layer) ||
+ double.Hypot(axis.X - main.X, axis.Y - main.Y) > JunctionTolerance ||
+ double.Hypot(axis.Dx * axis.Length - main.Dx * main.Length, axis.Dy * axis.Length - main.Dy * main.Length) > JunctionTolerance ||
+ ReadColumnCutterEnvelope(geometry, id, memo, axis) is not { } section || section.Priority >= strongest.Priority ||
+ section.Left < -half - JunctionTolerance || section.Right > half + JunctionTolerance ||
+ section.Height.Bottom < bottom - JunctionTolerance || section.Height.Top > top + JunctionTolerance ||
+ !HasOnlyBeamTargetContact(memo, BeamColumnRelation, junction, axis.Owner,
+ (role, contact) => PreservesCut(id, axis, role, contact)))
+ return null;
+ }
+
+ return [new ColumnBeamMask(Math.Max(range.Bottom, bottom), Math.Min(range.Top, top),
+ [PointAt(0, half), PointAt(main.Length, half), PointAt(main.Length, -half), PointAt(0, -half)])];
+
+ PlaPlanPoint PointAt(double station, double across) =>
+ new(main.X - origin.X + main.Dx * station + main.Dy * across,
+ main.Y - origin.Y + main.Dy * station - main.Dx * across);
+
+ bool PreservesCut(Guid id, BeamPrism beam, Guid role, Guid contact)
+ {
+ if (role == BeamColumnRelation)
+ return ReadBeamStructuralNeighbor(geometry, id, role, contact) is not null;
+ if (role == BeamWallRelation || role == BeamSlabRelation)
+ return id == strongest.Memo && BeamWinsContact(geometry, id, role, contact, strongest.Priority);
+ var interior = ReadBeamAxisJunction(geometry, id, role, contact, withoutPoint: true);
+ if ((interior ?? ReadBeamAxisJunction(geometry, id, role, contact)) is not { } join ||
+ geometry.Read(join.Peer, BeamMemoClass) is not { } memo || !HasGeometryRelation(memo, join.Reciprocal, contact) ||
+ ReadBeamPrism(geometry, join.Peer, memo, home) is not { } peer ||
+ !SameIntersectionGroup(geometry, beam.Layer, peer.Layer) ||
+ interior is null && (!OnAxis(beam, join.X, join.Y) || !OnAxis(peer, join.X, join.Y)))
+ return false;
+ if (group.Contains(join.Peer)) return true;
+
+ // Cleanup at a reciprocal beam join cannot change the cut outside the connected beam's strip.
+ if (ReadColumnCutterEnvelope(geometry, join.Peer, memo, peer) is not { } other) return false;
+ if (DisjointHeights(other.Height.Bottom, other.Height.Top, range)) return true;
+ double offset = (origin.X - peer.X) * peer.Dy - (origin.Y - peer.Y) * peer.Dx;
+ return ring.All(p => offset + p.X * peer.Dy - p.Y * peer.Dx < other.Left - JunctionTolerance) ||
+ ring.All(p => offset + p.X * peer.Dy - p.Y * peer.Dx > other.Right + JunctionTolerance);
+ }
+
+ static bool OnAxis(BeamPrism beam, double x, double y) =>
+ IsOnBeamJoint(beam, x, y, end: true) || IsOnBeamJoint(beam, x, y, end: false);
+ }
+
+ private static (Elevations Height, double Left, double Right, uint Priority)? ReadColumnCutterEnvelope(
+ ModelGeometry geometry, Guid id, byte[] memo, BeamPrism axis)
+ {
+ Guid section = ReadSingleRelation(memo, SectionProfileRelation, 0x11, requireSection: true);
+ var materials = geometry.Attributes.Material;
+ if (geometry.Read(section, RectangularSectionClass) is not null)
+ {
+ var hatch = ReadBeamHatch(geometry, id, memo);
+ return BeamSectionExtents(axis, hatch) is { } outline &&
+ materials.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is > 0 and { } priority
+ ? (outline.Height, outline.Left, outline.Right, priority) : null;
+ }
+ if (geometry.Read(axis.Owner, BeamClass) is not { } body ||
+ ReadMemberProfile(body.AsSpan(FindClassFrame(body, BeamClass)), axis.Owner, beam: true, geometry) is not { } profile ||
+ ProjectBeamProfile(axis, profile) is not { } extents)
+ return null;
+ uint maximum = 0;
+ foreach (var part in profile.Components)
+ {
+ if (materials.GetValueOrDefault(part.BuildingMaterialIndex) is not (> 0 and { } priority)) return null;
+ maximum = Math.Max(maximum, priority);
+ }
+ return (extents.Height, extents.Left, extents.Right, maximum);
+ }
+
+ private static bool BeamKeepsColumnBand(ModelGeometry geometry, Guid beam, BeamPrism axis, Guid role, Guid junction,
+ double home, (double X0, double Y0, double X1, double Y1) section, uint priority, uint columnPriority,
+ (double HalfWidth, double Depth) rectangle, HashSet active,
+ List<(Guid Memo, double Start, double End)> throughSpans,
+ List miters, List requiredMiters,
+ ref ((double Right, double Left) Start, (double Right, double Left) End) limits)
+ {
+ if (role == BeamColumnRelation)
+ // Each column contact uses the beam sweep before cuts from the other column contacts.
+ return ReadBeamStructuralNeighbor(geometry, beam, role, junction) is not null;
+ if (role == BeamWallRelation || role == BeamSlabRelation)
+ return BeamWinsContact(geometry, beam, role, junction, priority);
+
+ var overlap = ReadBeamAxisJunction(geometry, beam, role, junction, withoutPoint: true);
+ if ((overlap ?? ReadBeamAxisJunction(geometry, beam, role, junction)) is not { } join ||
+ geometry.Read(join.Peer, BeamMemoClass) is not { } memo || !HasGeometryRelation(memo, join.Reciprocal, junction) ||
+ ReadStraightBeamAxis(geometry, join.Peer, memo, home, out var planes, readAnnotations: true) is not { } other ||
+ !planes.HasSquareHorizontalEnds(other) ||
+ !SameIntersectionGroup(geometry, axis.Layer, other.Layer) ||
+ ReadBeamContactExtents(geometry, join.Peer, memo, other) is not { } outline)
+ return false;
+
+ var otherHatch = ReadBeamHatch(geometry, join.Peer, memo);
+ uint? peerPriority = otherHatch.IsEmpty ? null
+ : geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(otherHatch[18..]));
+ var (min, max) = ProjectRectangle(section, other.X, other.Y, other.Dy, -other.Dx);
+ bool outsideStrip = max < outline.Left - JunctionTolerance || min > outline.Right + JunctionTolerance;
+ if (overlap is not null)
+ // An interior collision has no joined cap. A weaker peer leaves the cutter intact.
+ return outsideStrip || peerPriority is > 0 && peerPriority < priority ||
+ DisjointHeights(outline.Height.Bottom, outline.Height.Top, new Elevations(axis.Z - rectangle.Depth, axis.Z));
+
+ bool ownEnd = IsBeamEndRelation(role), peerEnd = IsBeamEndRelation(join.Reciprocal);
+ if (!IsOnBeamJoint(axis, join.X, join.Y, ownEnd) || !IsOnBeamJoint(other, join.X, join.Y, peerEnd))
+ return false;
+ if (!ownEnd && !peerEnd && peerPriority is > 0 && peerPriority < priority &&
+ ReadColumnCutterEnvelope(geometry, join.Peer, memo, other) is { Priority: > 0 } interior && interior.Priority < priority)
+ return true;
+ if (ownEnd && peerEnd &&
+ Math.Abs(axis.Dx * other.Dy - axis.Dy * other.Dx) <= JunctionTolerance)
+ {
+ double along = (join.X - axis.X) * axis.Dx + (join.Y - axis.Y) * axis.Dy;
+ double peerAlong = (join.X - other.X) * other.Dx + (join.Y - other.Y) * other.Dy;
+ double direction = axis.Dx * other.Dx + axis.Dy * other.Dy;
+ // Square caps on opposite sides of a common collinear end meet without changing either sweep.
+ if ((axis.Length / 2 - along) * (other.Length / 2 - peerAlong) * direction < 0) return true;
+ // At coincident ends of coextensive beams the weaker material cannot change the cutter.
+ return Math.Abs(axis.Length - other.Length) <= JunctionTolerance && peerPriority is > 0 && peerPriority < priority;
+ }
+ // The connected beam can only change this band's cross-section inside its transverse strip.
+ if (outsideStrip) return true;
+
+ if (other.SinRoll != 0 || Math.Abs(outline.Left + outline.Right) > JunctionTolerance ||
+ Math.Abs(axis.Z - outline.Height.Top) > JunctionTolerance ||
+ Math.Abs(axis.Z - rectangle.Depth - outline.Height.Bottom) > JunctionTolerance)
+ return false;
+
+ var otherRectangle = ReadBeamRectangle(otherHatch);
+ double dot = axis.Dx * other.Dx + axis.Dy * other.Dy;
+ if (ownEnd && peerEnd)
+ {
+ if (Math.Abs(outline.Right - rectangle.HalfWidth) > JunctionTolerance ||
+ ReadColumnBeamMiter(axis, other, join.X, join.Y, rectangle.HalfWidth) is not { } miter) return false;
+ if (peerPriority == priority && otherRectangle is { } match &&
+ Math.Abs(rectangle.HalfWidth - match.HalfWidth) <= JunctionTolerance)
+ {
+ if (!active.Contains(join.Peer)) return MiterClearsColumn(axis, miter, rectangle.HalfWidth, section);
+ ref var activeCap = ref (miter.AtStart ? ref limits.Start : ref limits.End);
+ double savedEnd = miter.AtStart ? 0 : axis.Length;
+ if ((activeCap.Right != savedEnd || activeCap.Left != savedEnd) &&
+ !miter.Matches(new(miter.AtStart, activeCap.Right, activeCap.Left))) return false;
+ activeCap = (miter.Right, miter.Left);
+ miters.Add(miter);
+ return true;
+ }
+ // A weaker overlapping peer can repeat the same join in another evaluation context.
+ if (peerPriority is not (> 0) || peerPriority >= priority || active.Contains(join.Peer) ||
+ ReadColumnCutterEnvelope(geometry, join.Peer, memo, other) is not { } weaker || weaker.Priority > columnPriority ||
+ weaker.Left < -rectangle.HalfWidth - JunctionTolerance || weaker.Right > rectangle.HalfWidth + JunctionTolerance ||
+ weaker.Height.Bottom < axis.Z - rectangle.Depth - JunctionTolerance || weaker.Height.Top > axis.Z + JunctionTolerance)
+ return false;
+ requiredMiters.Add(miter);
+ return true;
+ }
+ if (ownEnd == peerEnd || peerPriority is not (> 0)) return false;
+
+ var through = ownEnd ? other : axis;
+ var branch = ownEnd ? axis : other;
+ double width = ownEnd ? rectangle.HalfWidth : outline.Right;
+ double throughWidth = ownEnd ? outline.Right : rectangle.HalfWidth;
+ if (Math.Abs(dot) * width > throughWidth + JunctionTolerance ||
+ ProjectBeamJunctionInterval(through, branch, join.X, join.Y, -throughWidth, throughWidth, -width, width)
+ is not { } reach ||
+ reach.Min <= JunctionTolerance || reach.Max >= through.Length - JunctionTolerance)
+ return false;
+
+ // For equal cutters, the through beam contains the joined end's change in plan.
+ if (active.Contains(join.Peer))
+ {
+ if (peerPriority != priority || otherRectangle is null) return false;
+ throughSpans.Add((ownEnd ? join.Peer : beam, reach.Min, reach.Max));
+ return true;
+ }
+ if (peerPriority > columnPriority || otherRectangle is not null ||
+ !IsConcaveBeamSection(StraightSectionVertices(otherHatch))) return false;
+ if (!ownEnd) return true;
+
+ // Intersect both sides of the rectangular branch with the weaker through beam's near face.
+ double at = (join.X - axis.X) * axis.Dx + (join.Y - axis.Y) * axis.Dy;
+ bool atStart = at < axis.Length / 2;
+ double slope = axis.Dx * other.Dy - axis.Dy * other.Dx;
+ double face = (atStart ? slope : -slope) > 0 ? outline.Right : outline.Left;
+ double side = rectangle.HalfWidth * dot;
+ ref var cap = ref (atStart ? ref limits.Start : ref limits.End);
+ double saved = atStart ? 0 : axis.Length;
+ double rightAtFace = saved + (face - side) / slope;
+ double leftAtFace = saved + (face + side) / slope;
+ if (cap.Right != saved || cap.Left != saved)
+ return Math.Abs(cap.Right - rightAtFace) <= JunctionTolerance &&
+ Math.Abs(cap.Left - leftAtFace) <= JunctionTolerance;
+ cap = (rightAtFace, leftAtFace);
+ return true;
+ }
+
+ private readonly record struct ColumnBeamMiter(bool AtStart, double Right, double Left)
+ {
+ public bool Matches(ColumnBeamMiter other) => AtStart == other.AtStart &&
+ Math.Abs(Right - other.Right) <= JunctionTolerance && Math.Abs(Left - other.Left) <= JunctionTolerance;
+ }
+
+ private static ColumnBeamMiter? ReadColumnBeamMiter(BeamPrism axis, BeamPrism peer, double x, double y, double halfWidth)
+ {
+ double at = (x - axis.X) * axis.Dx + (y - axis.Y) * axis.Dy;
+ double peerAt = (x - peer.X) * peer.Dx + (y - peer.Y) * peer.Dy;
+ bool atStart = at < axis.Length / 2;
+ double sign = atStart ? 1 : -1, otherSign = peerAt < peer.Length / 2 ? 1 : -1;
+ // The equal-width miter plane bisects the two axes directed away from the joint.
+ double nx = peer.Dx * otherSign - axis.Dx * sign, ny = peer.Dy * otherSign - axis.Dy * sign;
+ double normalAlong = nx * axis.Dx + ny * axis.Dy;
+ if (Math.Abs(normalAlong) <= JunctionTolerance) return null;
+ double offset = -halfWidth * (nx * axis.Dy - ny * axis.Dx) / normalAlong;
+ double cap = atStart ? 0 : axis.Length;
+ return Math.Abs(offset) < Math.Min(axis.Length, peer.Length) - JunctionTolerance
+ ? new ColumnBeamMiter(atStart, cap + offset, cap - offset) : null;
+ }
+
+ private static bool MiterClearsColumn(BeamPrism axis, ColumnBeamMiter miter, double halfWidth,
+ (double X0, double Y0, double X1, double Y1) section)
+ {
+ double end = miter.AtStart ? 0 : axis.Length;
+ double slope = (miter.Right - end) / halfWidth;
+ var (min, max) = ProjectRectangle(section, axis.X, axis.Y, axis.Dx, axis.Dy);
+ var (skewMin, skewMax) = ProjectRectangle(section, axis.X, axis.Y,
+ axis.Dx - slope * axis.Dy, axis.Dy + slope * axis.Dx);
+ return Math.Min(min, skewMin) > end + JunctionTolerance || Math.Max(max, skewMax) < end - JunctionTolerance;
+ }
+
+ private static bool IsConcaveBeamSection(ReadOnlySpan vertices)
+ {
+ if (vertices.Length is <= 4 * 16 or > 4096 * 16) return false;
+ var ring = new PlaPlanPoint[vertices.Length / 16];
+ for (int i = 0; i < ring.Length; i++)
+ ring[i] = new PlaPlanPoint(ReadDouble(vertices, i * 16), ReadDouble(vertices, i * 16 + 8));
+ bool clockwise = false, counterclockwise = false;
+ for (int i = 0; i < ring.Length; i++)
+ {
+ double turn = Cross(ring[i], ring[(i + 1) % ring.Length], ring[(i + 2) % ring.Length]);
+ clockwise |= turn < 0;
+ counterclockwise |= turn > 0;
+ }
+ return clockwise && counterclockwise && IsSimpleRing(ring);
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.ColumnGeometry.cs b/src/PlaIO/Internal/ElementReader.ColumnGeometry.cs
new file mode 100644
index 0000000..cc8adbc
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.ColumnGeometry.cs
@@ -0,0 +1,435 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid ColumnMemoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9");
+ private static readonly Guid RectangularSectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6");
+ private static readonly Guid ColumnMemoRelation = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce");
+ private static readonly Guid SectionProfileRelation = new("63b86c30-a221-421c-84fb-926c694bf611");
+ private static readonly Guid FirstColumnPartRelation = new("4e52e27f-cbac-485f-a3a3-89124756a025");
+ private static readonly Guid SecondColumnPartRelation = new("d004bcd5-41ed-4ee8-99cb-99da69422f60");
+ private static readonly Guid ColumnPartsRelation = new("d5e668e5-acee-4e89-ba9a-47b031d7cf69");
+ private static readonly Guid AttributeOwnerRelation = new("f367a8af-cd22-4941-9dc2-71def6f2d0a9");
+ private static readonly Guid ColumnPropertySetRelation = new("2107926d-a8fd-4021-a0eb-cce5950eed37");
+ private static readonly Guid LinkedElementSettingsRelation = new("f732f229-4ef9-4007-b0e4-6ca945917a3e");
+ private static ReadOnlySpan ColumnEndPlaneFrame => [1, 0, 2, 0, 0, 0, 1, 0];
+ private static ReadOnlySpan SectionVectorFrame => [2, 0, 9, 1];
+
+ private static Elevations? ReadColumnElevations(ReadOnlySpan column, Guid columnId, ElementLocation location,
+ ModelGeometry geometry, PlaMemberProfile? profile, out PlaBoundingBox? boundingBox, out PlaColumnExtrusion? extrusion,
+ out PlaColumnCutMesh? cutMesh)
+ {
+ boundingBox = null;
+ extrusion = null;
+ cutMesh = null;
+ if (column.Length < 426 || !column.Slice(304, ColumnEndPlaneFrame.Length).SequenceEqual(ColumnEndPlaneFrame) ||
+ BinaryPrimitives.ReadUInt16LittleEndian(column[368..]) != 1)
+ return null;
+
+ var lower = column[312..];
+ var upper = column[370..];
+ double x = BinaryPrimitives.ReadDoubleLittleEndian(lower);
+ double y = BinaryPrimitives.ReadDoubleLittleEndian(lower[8..]);
+ if (!double.IsFinite(x) || !double.IsFinite(y) ||
+ x != BinaryPrimitives.ReadDoubleLittleEndian(upper) || y != BinaryPrimitives.ReadDoubleLittleEndian(upper[8..]))
+ return null;
+
+ Guid memoId = ReadColumnPrismMemo(column, columnId, geometry);
+ if (memoId == Guid.Empty) return null;
+ var memo = geometry.Read(memoId, ColumnMemoClass);
+ if (memo is null || ReadColumnSection(memo, columnId, out var junctions) is not { } sectionId) return null;
+ var section = geometry.Read(sectionId, RectangularSectionClass);
+ var settings = AfterCountedString(column, 735);
+ int settingsEnd = FindRelationshipSection(column, column.Length) - 6;
+ bool hasPlacementSettings = settings.Length >= 95 && settingsEnd - (column.Length - settings.Length) >= 95;
+ double angle = hasPlacementSettings &&
+ column[721..].StartsWith(ElementIdFrame) ? ReadDouble(settings, 87) : double.NaN;
+ if (section is null && geometry.Read(sectionId, CircularColumnSectionClass) is { } circular)
+ return ReadCircularColumn(memoId, circular, lower, upper, new PlaPlanPoint(x, y), location, geometry, junctions,
+ out boundingBox, out extrusion);
+ int material;
+ (double X, double Y)? halfSize = null;
+ PlaBoundingBox? profileBox = null;
+ if (section is not null)
+ {
+ if (ReadSingleRelation(section, SectionProfileRelation, requireSection: true) != memoId ||
+ (halfSize = ReadCenteredRectangle(section, out material)) is null) return null;
+ }
+ else
+ {
+ var hatch = ReadComplexSectionHatch(geometry, memoId, sectionId);
+ if (hatch.IsEmpty || !HasSectionArea(hatch)) return null;
+ if (profile is not null && double.IsFinite(angle) && ReadDouble(lower, 40) < 0 && ReadDouble(upper, 40) > 0)
+ profileBox = ReadProfileColumnBoundingBox(settings, profile, x, y, angle, ReadDouble(lower, 16),
+ ReadDouble(upper, 16), geometry.StoryElevation(location.HomeStoryIndex));
+ if (!IsHorizontal(lower) || !IsHorizontal(upper))
+ {
+ cutMesh = ReadObliqueColumn(column, hatch, profile, memoId, junctions, location, geometry, angle);
+ if (cutMesh is not null) boundingBox = profileBox;
+ return cutMesh is null ? null : new Elevations(cutMesh.BoundingBox.ZMin - cutMesh.Origin.Z,
+ cutMesh.BoundingBox.ZMax - cutMesh.Origin.Z);
+ }
+ material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]);
+ }
+
+ double bottomRadius = halfSize is { } rectangle ? ReadPlaneRadius(lower, rectangle) : 0;
+ double topRadius = halfSize is { } dimensions ? ReadPlaneRadius(upper, dimensions) : 0;
+ bool unrotated = column.Length >= 735 && column[721..].StartsWith(ElementIdFrame) &&
+ settings.Length >= 36 && BinaryPrimitives.ReadDoubleLittleEndian(settings[28..]) == 0;
+ if ((bottomRadius != 0 || topRadius != 0) && !unrotated) return null;
+
+ double bottom = BinaryPrimitives.ReadDoubleLittleEndian(lower[16..]);
+ double top = BinaryPrimitives.ReadDoubleLittleEndian(upper[16..]);
+ if (BinaryPrimitives.ReadDoubleLittleEndian(lower[40..]) >= 0 ||
+ BinaryPrimitives.ReadDoubleLittleEndian(upper[40..]) <= 0 ||
+ !(top - bottom > bottomRadius + topRadius))
+ return null;
+ var bounds = CheckedElevations(bottom - bottomRadius, top + topRadius);
+ if (bounds is not { } extents) return null;
+ bool horizontal = bottomRadius == 0 && topRadius == 0;
+ bool solid = double.IsFinite(angle) && (angle == 0 || horizontal) && (halfSize.HasValue || profile is not null);
+ bool keepsNominalBox = junctions is null;
+ if (junctions is not null)
+ {
+ var plan = solid && horizontal && halfSize is { } half
+ ? new RectangularColumnPlan(new PlaPlanPoint(x, y), half.X, half.Y, angle) : (RectangularColumnPlan?)null;
+ bounds = ResolveColumnJunctions(geometry, memoId, junctions, location, material, extents,
+ unrotated && halfSize is { } size ? (x - size.X, y - size.Y, x + size.X, y + size.Y) : null,
+ bottom + bottomRadius, top - topRadius, section is null, solid, out keepsNominalBox, out solid, plan);
+ }
+ Elevations[]? bands = null;
+ List? partialMasks = null;
+ if (!solid && horizontal && double.IsFinite(angle) && section is null && profile is not null && junctions is not null &&
+ geometry.StoryElevation(location.HomeStoryIndex) is { } level &&
+ geometry.Attributes.Material.GetValueOrDefault(material) is > 0 and { } priority &&
+ ReadColumnFootprint(column, ReadComplexSectionHatch(geometry, memoId, sectionId), angle) is { } painted &&
+ ReadColumnBeamBands(geometry, memoId, junctions, location, priority, level, extents, painted,
+ new PlaPlanPoint(x, y), out partialMasks) is { } surviving)
+ {
+ bands = surviving;
+ bounds = new Elevations(bands[0].Bottom, bands[^1].Top);
+ solid = true;
+ }
+ PlaPlanPoint[]? cutSection = null;
+ if (partialMasks is { Count: <= 48 } && profile is not null && ReadStraightProfileSection(profile.Components) is { Count: 1 } rings)
+ cutSection = OrientColumnSection(rings[0], angle);
+ if (!solid && horizontal && double.IsFinite(angle) && halfSize is { } rectangleSize && junctions is not null &&
+ geometry.StoryElevation(location.HomeStoryIndex) is { } story &&
+ geometry.Attributes.Material.GetValueOrDefault(material) is > 0 and { } columnPriority)
+ {
+ var (w, d) = rectangleSize;
+ var ring = OrientColumnSection([new(-w, -d), new(w, -d), new(w, d), new(-w, d)], angle);
+ partialMasks = ReadCoextensiveColumnBeamCut(geometry, memoId, junctions, location, columnPriority, story,
+ extents, new PlaPlanPoint(x, y), ring);
+ if (partialMasks is not null) cutSection = ring;
+ }
+ if (cutSection is { } ringOutline && partialMasks is not null &&
+ geometry.StoryElevation(location.HomeStoryIndex) is { } cutHome)
+ {
+ double x0 = ringOutline.Min(p => p.X), x1 = ringOutline.Max(p => p.X);
+ double y0 = ringOutline.Min(p => p.Y), y1 = ringOutline.Max(p => p.Y);
+ PlaPlanPoint[] envelope = [new(x0, y0), new(x1, y0), new(x1, y1), new(x0, y1)];
+ var origin = new PlaColumnMeshPoint(x, y, cutHome);
+ cutMesh = BuildColumnCutMesh(envelope, extents.Bottom, extents.Top, partialMasks, origin,
+ static (p, z) => new PlaColumnMeshPoint(p.X, p.Y, z), ringOutline);
+ if (cutMesh is { } cut)
+ {
+ var box = cut.BoundingBox;
+ if (section is null)
+ boundingBox = profileBox;
+ else if (halfSize.HasValue && Math.Abs(box.XMin - (x + x0)) <= JunctionTolerance && Math.Abs(box.XMax - (x + x1)) <= JunctionTolerance &&
+ Math.Abs(box.YMin - (y + y0)) <= JunctionTolerance && Math.Abs(box.YMax - (y + y1)) <= JunctionTolerance &&
+ Math.Abs(box.ZMin - (cutHome + extents.Bottom)) <= JunctionTolerance &&
+ Math.Abs(box.ZMax - (cutHome + extents.Top)) <= JunctionTolerance)
+ boundingBox = box;
+ return new Elevations(cut.BoundingBox.ZMin - cutHome, cut.BoundingBox.ZMax - cutHome);
+ }
+ }
+ if (section is null && (junctions is null || solid))
+ boundingBox = profileBox;
+ else if (section is not null && keepsNominalBox && settings.Length >= 95)
+ {
+ var outline = ReadSectionHatch(section, 141, 482);
+ double savedAngle = ReadDouble(settings, 87);
+ if ((savedAngle == 0 || horizontal) && ReadColumnFootprint(column, outline, savedAngle) is { } plan)
+ boundingBox = ProjectBoundingBox(plan, extents, geometry.StoryElevation(location.HomeStoryIndex));
+ }
+ if (solid && bounds is { } evaluated && (bands is not null || evaluated == extents || angle == 0 &&
+ (evaluated.Bottom == extents.Bottom || evaluated.Bottom >= bottom + bottomRadius) &&
+ (evaluated.Top == extents.Top || evaluated.Top <= top - topRadius)) &&
+ geometry.StoryElevation(location.HomeStoryIndex) is { } home)
+ {
+ var low = ReadColumnEndPlane(lower, evaluated.Bottom, extents.Bottom, home);
+ var high = ReadColumnEndPlane(upper, evaluated.Top, extents.Top, home);
+ extrusion = ReadColumnExtrusion(new PlaPlanPoint(x, y), halfSize, profile, angle, low, high, evaluated, home, bands);
+ if (section is not null) boundingBox ??= extrusion?.BoundingBox;
+ }
+ return bounds;
+ }
+
+ private static PlaBoundingBox? ReadProfileColumnBoundingBox(ReadOnlySpan settings, PlaMemberProfile profile,
+ double x, double y, double angle, double bottom, double top, double? home)
+ {
+ if (!(top > bottom) || settings[0] is not (1 or 4)) return null;
+ var (sin, cos) = Math.SinCos(angle);
+ if (ProjectBeamSection(default, profile.Components, cos, -sin) is not { } acrossX ||
+ ProjectBeamSection(default, profile.Components, sin, cos) is not { } acrossY) return null;
+
+ if (settings[0] == 4)
+ {
+ double extension = ReadDouble(settings, 69);
+ if (!double.IsFinite(extension) || extension < 0 ||
+ ProjectBeamSection(default, profile.Components, 1, 0) is not { } u ||
+ ProjectBeamSection(default, profile.Components, 0, 1) is not { } v ||
+ Math.Abs(u.Max + u.Min) > JunctionTolerance || Math.Abs(v.Max + v.Min) > JunctionTolerance)
+ return null;
+
+ // The element box includes the four ends of the floor-plan crosshair.
+ double halfU = u.Max + extension, halfV = v.Max + extension;
+ double reachX = Math.Max(halfU * Math.Abs(cos), halfV * Math.Abs(sin));
+ double reachY = Math.Max(halfU * Math.Abs(sin), halfV * Math.Abs(cos));
+ acrossX = (Math.Min(acrossX.Min, -reachX), Math.Max(acrossX.Max, reachX));
+ acrossY = (Math.Min(acrossY.Min, -reachY), Math.Max(acrossY.Max, reachY));
+ }
+
+ return ProjectBoundingBox((x + acrossX.Min, y + acrossY.Min, x + acrossX.Max, y + acrossY.Max), new(bottom, top), home);
+ }
+
+ private static PlaPlanPoint[] OrientColumnSection(IReadOnlyList section, double angle)
+ {
+ var (sin, cos) = Math.SinCos(angle);
+ return section.Select(p => new PlaPlanPoint(cos * p.X - sin * p.Y, sin * p.X + cos * p.Y)).ToArray();
+ }
+
+ private static PlaColumnEndPlane ReadColumnEndPlane(ReadOnlySpan plane, double evaluated, double nominal, double home)
+ {
+ if (evaluated != nominal) return new PlaColumnEndPlane(evaluated + home, 0, 0);
+ double normalZ = ReadDouble(plane, 40);
+ return new PlaColumnEndPlane(ReadDouble(plane, 16) + home, -ReadDouble(plane, 24) / normalZ, -ReadDouble(plane, 32) / normalZ);
+ }
+
+ private static PlaColumnExtrusion? ReadColumnExtrusion(PlaPlanPoint origin, (double X, double Y)? halfSize,
+ PlaMemberProfile? profile, double angle, PlaColumnEndPlane lower, PlaColumnEndPlane upper,
+ Elevations extents, double home, Elevations[]? bands)
+ {
+ IReadOnlyList>? rings = halfSize is { } size
+ ? [[new(-size.X, -size.Y), new(size.X, -size.Y), new(size.X, size.Y), new(-size.X, size.Y)]]
+ : profile is not null ? ReadStraightProfileSection(profile.Components) : null;
+ if (rings is null) return null;
+ // For a centered rectangle the mean of either planar cap height equals its height at the axis.
+ double height = bands is null ? upper.Elevation - lower.Elevation : bands.Sum(b => b.Top - b.Bottom);
+ double volume = rings.Sum(SignedRingArea) * height;
+ if (!double.IsFinite(volume) || volume <= 0) return null;
+
+ var (sin, cos) = Math.SinCos(angle);
+ var oriented = rings.Select(ring => (IReadOnlyList)Array.AsReadOnly(ring.Select(p =>
+ new PlaPlanPoint(cos * p.X - sin * p.Y, sin * p.X + cos * p.Y)).ToArray())).ToArray();
+ if (GroupPlanarContours(oriented) is not { } groups) return null;
+ var points = oriented.SelectMany(ring => ring).ToArray();
+ var plan = (origin.X + points.Min(p => p.X), origin.Y + points.Min(p => p.Y),
+ origin.X + points.Max(p => p.X), origin.Y + points.Max(p => p.Y));
+ return ProjectBoundingBox(plan, extents, home) is { } box
+ ? new PlaColumnExtrusion(origin, Array.AsReadOnly(groups.Select(g => new PlaColumnExtrusionSection(g.AsReadOnly())).ToArray()),
+ lower, upper, box, volume)
+ {
+ Spans = bands is { Length: > 1 }
+ ? Array.AsReadOnly(bands.Select(b => new PlaColumnSpan(b.Bottom + home, b.Top + home)).ToArray()) : null,
+ }
+ : null;
+ }
+
+ private static bool SameColumnExtrusion(PlaColumnExtrusion? a, PlaColumnExtrusion? b) =>
+ a == b || a is not null && b is not null && a.Origin == b.Origin && a.LowerPlane == b.LowerPlane &&
+ a.UpperPlane == b.UpperPlane && a.BoundingBox == b.BoundingBox && a.Volume == b.Volume && a.Sections.Count == b.Sections.Count &&
+ a.CircularRadius == b.CircularRadius && a.ScheduledCapArea == b.ScheduledCapArea &&
+ a.ScheduledLateralArea == b.ScheduledLateralArea &&
+ (a.Spans ?? []).SequenceEqual(b.Spans ?? []) &&
+ a.Sections.Zip(b.Sections).All(pair => pair.First.Rings.Count == pair.Second.Rings.Count &&
+ pair.First.Rings.Zip(pair.Second.Rings).All(rings => rings.First.SequenceEqual(rings.Second)));
+
+ private static bool SameColumnCutMesh(PlaColumnCutMesh? a, PlaColumnCutMesh? b) =>
+ a == b || a is not null && b is not null && a.Origin == b.Origin && a.BoundingBox == b.BoundingBox &&
+ a.Volume == b.Volume && a.Vertices.SequenceEqual(b.Vertices) && a.Indices.SequenceEqual(b.Indices);
+
+ private static bool HasSectionArea(ReadOnlySpan hatch)
+ {
+ int count = (int)BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]);
+ var points = hatch[59..];
+ double x0 = BinaryPrimitives.ReadDoubleLittleEndian(points[16..]);
+ double y0 = BinaryPrimitives.ReadDoubleLittleEndian(points[24..]);
+ double dx = 0, dy = 0;
+ bool hasArea = false;
+ for (int i = 2; i < count; i++)
+ {
+ double x = BinaryPrimitives.ReadDoubleLittleEndian(points[(i * 16)..]) - x0;
+ double y = BinaryPrimitives.ReadDoubleLittleEndian(points[(i * 16 + 8)..]) - y0;
+ if (!double.IsFinite(x) || !double.IsFinite(y)) return false;
+ if (dx == 0 && dy == 0) (dx, dy) = (x, y);
+ double determinant = dx * y - dy * x;
+ if (double.IsFinite(determinant) && determinant != 0) hasArea = true;
+ }
+ return hasArea;
+ }
+
+ private static bool IsHorizontal(ReadOnlySpan plane) =>
+ BinaryPrimitives.ReadDoubleLittleEndian(plane[24..]) == 0 &&
+ BinaryPrimitives.ReadDoubleLittleEndian(plane[32..]) == 0;
+
+ private static ReadOnlySpan StraightSectionVertices(ReadOnlySpan hatch)
+ {
+ if (hatch.IsEmpty) return default;
+ int count = (int)BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]);
+ var points = hatch[59..];
+ int end = count * 16;
+ if (points.Length - end < 6 || BinaryPrimitives.ReadUInt16LittleEndian(points[end..]) != 1 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(points[(end + 2)..]) != 0 ||
+ points[..16].IndexOfAnyExcept((byte)0) >= 0 || !points.Slice(16, 16).SequenceEqual(points.Slice(end - 16, 16)))
+ return default;
+ return points.Slice(16, end - 32);
+ }
+
+ private static double ReadPlaneRadius(ReadOnlySpan plane, (double X, double Y) halfSize)
+ {
+ double nx = BinaryPrimitives.ReadDoubleLittleEndian(plane[24..]);
+ double ny = BinaryPrimitives.ReadDoubleLittleEndian(plane[32..]);
+ double nz = BinaryPrimitives.ReadDoubleLittleEndian(plane[40..]);
+ return (Math.Abs(nx) * halfSize.X + Math.Abs(ny) * halfSize.Y) / Math.Abs(nz);
+ }
+
+ private static Guid ReadColumnPrismMemo(ReadOnlySpan column, Guid owner, ModelGeometry geometry) =>
+ ReadPrismMemo(column, ColumnMemoRelation, acceptsReference: (role, target) => role == ColumnLabelRelation
+ ? geometry.OwnsLabel(owner, target, role) : IsPrismAnnotation(geometry, owner, role, target, allowLinearDimension: true));
+
+ private static Guid ReadPrismMemo(ReadOnlySpan record, Guid ownerRelation,
+ Func? acceptsMember = null, Func? acceptsReference = null)
+ {
+ int start = FindRelationshipSection(record, record.Length);
+ if (start < 0) return Guid.Empty;
+ var data = record[start..];
+ Guid memo = Guid.Empty;
+ bool hasMembership = false;
+ while (data.Length >= 17)
+ {
+ var entry = data;
+ if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid target)) return Guid.Empty;
+ if (tag == 0x11 && key == ownerRelation && memo == Guid.Empty && target != Guid.Empty)
+ memo = target;
+ else if (tag == 2 && key == ElementAssemblyRelation && acceptsMember is not null && !hasMembership &&
+ ReadRelationIds(entry, data, tag) is { Length: 32 } ids &&
+ acceptsMember(new Guid(ids[..16]), new Guid(ids[16..])))
+ hasMembership = true;
+ else if (tag is 1 or 0x11 && acceptsReference is not null &&
+ (key == AttachedAnnotationRelation || key == ColumnLabelRelation || AngularDimensionAnchorRelations.Contains(key)))
+ {
+ var annotations = ReadRelationIds(entry, data, tag);
+ if (annotations.IsEmpty) return Guid.Empty;
+ for (int i = 0; i < annotations.Length; i += 16)
+ if (!acceptsReference(key, new Guid(annotations.Slice(i, 16)))) return Guid.Empty;
+ }
+ else if ((tag is 1 or 0x11) && key == DrawingRelation ||
+ tag == 1 && (key == ColumnPartsRelation || key == ElementPropertyOverrideLink) ||
+ tag == 2 && key == AttributeOwnerRelation ||
+ tag == 0x11 && (key == DefaultElementRelation || key == ElementComponentRelation ||
+ key == ElementSettingsRelation || key == LinkedElementSettingsRelation ||
+ key == ColumnPropertySetRelation) ||
+ tag == 0x12 && (key == ElementPartitionRelation || key == ElementCollectionRelation ||
+ key == DatabaseElementList || key == ColumnTopStoryRelation || key == AttributeOwnerRelation))
+ continue;
+ else
+ return Guid.Empty;
+ }
+ return data is [0] ? memo : Guid.Empty;
+ }
+
+ private static Guid? ReadColumnSection(ReadOnlySpan memo, Guid columnId, out List<(Guid Key, Guid Id)>? junctions)
+ {
+ junctions = null;
+ int start = FindRelationshipSection(memo, memo.Length);
+ if (start < 0) return null;
+ var data = memo[start..];
+ Guid? section = null;
+ bool owner = false;
+ while (data.Length >= 17)
+ {
+ var entry = data;
+ if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid target)) return null;
+ if (tag == 0x12 && key == ColumnMemoRelation && target == columnId && !owner)
+ owner = true;
+ else if (tag == 0x11 && key == SectionProfileRelation && section is null && target != Guid.Empty)
+ section = target;
+ else if (tag == 1 && key == DrawingRelation)
+ continue;
+ else if (tag is 1 or 0x11 && (key == ColumnBeamRelation || key == ColumnSlabRelation || key == ColumnWallRelation))
+ {
+ var ids = tag == 1 ? entry.Slice(21, entry.Length - data.Length - 21) : entry.Slice(17, 16);
+ for (int i = 0; i < ids.Length; i += 16)
+ (junctions ??= []).Add((key, new Guid(ids.Slice(i, 16))));
+ }
+ else if (tag != 0x11 || (key != FirstColumnPartRelation && key != SecondColumnPartRelation && key != DrawingRelation))
+ return null;
+ }
+ return owner && data is [0] ? section : null;
+ }
+
+ private static (double X, double Y)? ReadCenteredRectangle(ReadOnlySpan section, out int material)
+ {
+ material = 0;
+ var hatch = ReadSectionHatch(section, 141, 482);
+ if (hatch.Length < 161 || BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]) != 6) return null;
+ double halfWidth = BinaryPrimitives.ReadDoubleLittleEndian(section[91..]) / 2;
+ double halfDepth = BinaryPrimitives.ReadDoubleLittleEndian(section[99..]) / 2;
+ if (!double.IsFinite(halfWidth) || !double.IsFinite(halfDepth) || halfWidth <= 0 || halfDepth <= 0) return null;
+
+ var points = hatch[59..];
+ if (BinaryPrimitives.ReadUInt16LittleEndian(points[96..]) != 1 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(points[98..]) != 0 ||
+ points[..16].IndexOfAnyExcept((byte)0) >= 0 || !points.Slice(16, 16).SequenceEqual(points.Slice(80, 16)))
+ return null;
+ material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]);
+ return IsCorner(points[16..], -halfWidth, -halfDepth) && IsCorner(points[32..], halfWidth, -halfDepth) &&
+ IsCorner(points[48..], halfWidth, halfDepth) && IsCorner(points[64..], -halfWidth, halfDepth)
+ ? (halfWidth, halfDepth) : null;
+ }
+
+ private static ReadOnlySpan ReadSectionHatch(ReadOnlySpan section, int frame, int hatchOffset,
+ ushort hatchKind = 2)
+ {
+ var vector = ReadSectionVector(section, frame);
+ if (vector.IsEmpty || BinaryPrimitives.ReadUInt32LittleEndian(vector[69..]) != 1) return default;
+
+ for (int i = hatchOffset; i <= vector.Length - 59; i++)
+ {
+ var hatch = vector[i..];
+ if (ReadHatchSize(hatch, hatchKind) == hatch.Length)
+ return hatch;
+ if (frame == 141) break;
+ }
+ return default;
+ }
+
+ private static ReadOnlySpan ReadSectionVector(ReadOnlySpan section, int frame)
+ {
+ if (section.Length < frame + 8 || !section[frame..].StartsWith(SectionVectorFrame)) return default;
+ uint size = BinaryPrimitives.ReadUInt32LittleEndian(section[(frame + 4)..]);
+ if (size < 128 || size > section.Length - frame - 8) return default;
+ var vector = section.Slice(frame + 8, (int)size);
+ return BinaryPrimitives.ReadUInt32LittleEndian(vector) == 128 ? vector : default;
+ }
+
+ private static int ReadHatchSize(ReadOnlySpan hatch, ushort kind)
+ {
+ if (hatch.Length < 59 || hatch[0] != 3 || hatch[1] != 1 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(hatch[6..]) != 0 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(hatch[8..]) != kind) return 0;
+ uint length = BinaryPrimitives.ReadUInt32LittleEndian(hatch[2..]);
+ uint count = BinaryPrimitives.ReadUInt32LittleEndian(hatch[55..]);
+ return length >= 59 && length <= hatch.Length - 6 && count >= 4 && count <= (length - 59) / 16
+ ? 6 + (int)length : 0;
+ }
+
+ private static bool IsCorner(ReadOnlySpan point, double x, double y) =>
+ BinaryPrimitives.ReadDoubleLittleEndian(point) == x && BinaryPrimitives.ReadDoubleLittleEndian(point[8..]) == y;
+}
diff --git a/src/PlaIO/Internal/ElementReader.ColumnMesh.cs b/src/PlaIO/Internal/ElementReader.ColumnMesh.cs
new file mode 100644
index 0000000..b87317b
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.ColumnMesh.cs
@@ -0,0 +1,182 @@
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private readonly record struct ColumnBeamMask(double MinAcross, double MaxAcross, PlaPlanPoint[] Outline);
+
+ private static PlaColumnCutMesh? BuildColumnCutMesh(PlaPlanPoint[] section, double minAcross, double maxAcross,
+ List masks, PlaColumnMeshPoint origin, Func pointAt,
+ IReadOnlyList? profile = null)
+ {
+ var points = section.ToList();
+ List cells = [[0, 1, 2, 3]];
+ if (profile is not null && !SplitAlong(profile)) return null;
+ foreach (var mask in masks)
+ if (!SplitAlong(mask.Outline)) return null;
+
+ bool SplitAlong(IReadOnlyList boundary)
+ {
+ for (int j = 0; j < boundary.Count; j++)
+ {
+ var a = boundary[j];
+ var b = boundary[(j + 1) % boundary.Count];
+ double length = Distance(a, b);
+ if (!(length > JunctionTolerance)) return false;
+ SplitColumnCells(points, cells, a, b, length * JunctionTolerance);
+ if (cells.Count > 1024) return false;
+ }
+ return true;
+ }
+
+ var stops = masks.SelectMany(m => new[] { m.MinAcross, m.MaxAcross }).Append(minAcross).Append(maxAcross)
+ .Distinct().Order().ToArray();
+ double tolerance = profile is null ? 0 : JunctionTolerance;
+ if (tolerance > 0)
+ {
+ var levels = new List(stops.Length);
+ foreach (double stop in stops)
+ {
+ if (levels.Count == 0 || stop - levels[^1] > tolerance)
+ levels.Add(stop);
+ else if (stop == maxAcross)
+ levels[^1] = stop;
+ }
+ // Saved caps and cutter faces at the same elevation can differ by roundoff.
+ stops = levels.ToArray();
+ }
+ var centres = cells.Select(c => new PlaPlanPoint(c.Average(v => points[v].X), c.Average(v => points[v].Y))).ToArray();
+ var areas = cells.Select(c => SignedRingArea(c.Select(v => points[v]).ToArray())).ToArray();
+ if (areas.Any(a => !(a > 0))) return null;
+ var material = centres.Select(p => profile is null || ContainsPoint(profile, p)).ToArray();
+ if (profile is not null)
+ {
+ double area = areas.Where((_, i) => material[i]).Sum();
+ double perimeter = profile.Select((p, i) => Distance(p, profile[(i + 1) % profile.Count])).Sum();
+ if (Math.Abs(area - SignedRingArea(profile)) > JunctionTolerance * perimeter) return null;
+ }
+ var edges = new Dictionary<(int Start, int End), int>();
+ for (int c = 0; c < cells.Count; c++)
+ for (int j = 0; j < cells[c].Length; j++)
+ if (!edges.TryAdd((cells[c][j], cells[c][(j + 1) % cells[c].Length]), c)) return null;
+
+ var inside = new bool[stops.Length - 1, cells.Count];
+ double volume = 0;
+ for (int b = 0; b + 1 < stops.Length; b++)
+ {
+ var cutters = masks.Where(m =>
+ m.MinAcross <= stops[b] + tolerance && m.MaxAcross >= stops[b + 1] - tolerance).ToArray();
+ for (int c = 0; c < cells.Count; c++)
+ {
+ inside[b, c] = material[c] && !cutters.Any(mask => InsideConvex(mask.Outline, centres[c]));
+ if (inside[b, c]) volume += areas[c] * (stops[b + 1] - stops[b]);
+ }
+ }
+ if (!(volume > 0) || !double.IsFinite(volume)) return null;
+
+ var vertices = new List();
+ var keys = new Dictionary<(int Point, int Stop), int>();
+ var triangles = new List();
+ for (int b = 0; b + 1 < stops.Length; b++)
+ {
+ for (int c = 0; c < cells.Count; c++)
+ {
+ if (!inside[b, c]) continue;
+ var cell = cells[c];
+ if (b == 0 || !inside[b - 1, c]) Cap(cell, centres[c], b, upper: false);
+ if (b == stops.Length - 2 || !inside[b + 1, c]) Cap(cell, centres[c], b + 1, upper: true);
+ for (int j = 0; j < cell.Length; j++)
+ {
+ int a = cell[j], d = cell[(j + 1) % cell.Length];
+ if (edges.TryGetValue((d, a), out int neighbor) && inside[b, neighbor]) continue;
+ int a0 = Vertex(a, b), d0 = Vertex(d, b), a1 = Vertex(a, b + 1), d1 = Vertex(d, b + 1);
+ triangles.AddRange([a0, d0, d1, a0, d1, a1]);
+ }
+ }
+ }
+ if (vertices.Count == 0 || !IsClosed(triangles)) return null;
+ var plan = (origin.X + vertices.Min(p => p.X), origin.Y + vertices.Min(p => p.Y),
+ origin.X + vertices.Max(p => p.X), origin.Y + vertices.Max(p => p.Y));
+ var bounds = MakeBoundingBox(plan, origin.Z + vertices.Min(p => p.Z), origin.Z + vertices.Max(p => p.Z));
+ return bounds is not null ? new PlaColumnCutMesh(origin, vertices.AsReadOnly(), triangles.AsReadOnly(), bounds, volume) : null;
+
+ int Vertex(int point, int level)
+ {
+ if (keys.TryGetValue((point, level), out int index)) return index;
+ keys.Add((point, level), vertices.Count);
+ vertices.Add(pointAt(points[point], stops[level]));
+ return vertices.Count - 1;
+ }
+
+ void Cap(int[] cell, PlaPlanPoint centre, int level, bool upper)
+ {
+ // Every edge keeps its shared nodes, including collinear ones needed by adjacent faces.
+ int fan = vertices.Count;
+ vertices.Add(pointAt(centre, stops[level]));
+ for (int j = 0; j < cell.Length; j++)
+ {
+ int a = Vertex(cell[j], level), d = Vertex(cell[(j + 1) % cell.Length], level);
+ triangles.AddRange([fan, upper ? a : d, upper ? d : a]);
+ }
+ }
+ }
+
+ private static bool InsideConvex(PlaPlanPoint[] outline, PlaPlanPoint point)
+ {
+ for (int i = 0; i < outline.Length; i++)
+ if (Cross(outline[i], outline[(i + 1) % outline.Length], point) < 0) return false;
+ return true;
+ }
+
+ private static void SplitColumnCells(List points, List cells, PlaPlanPoint a, PlaPlanPoint b,
+ double tolerance)
+ {
+ var signed = points.Select(p => Cross(a, b, p)).Select(d => Math.Abs(d) <= tolerance ? 0 : d).ToArray();
+ var intersections = new Dictionary<(int, int), int>();
+ int count = cells.Count;
+ for (int c = 0; c < count; c++)
+ {
+ var polygon = cells[c];
+ if (!polygon.Any(i => signed[i] > 0) || !polygon.Any(i => signed[i] < 0)) continue;
+ var positive = new List();
+ var negative = new List();
+ for (int i = 0; i < polygon.Length; i++)
+ {
+ int first = polygon[i], next = polygon[(i + 1) % polygon.Length];
+ double lo = signed[first], hi = signed[next];
+ if (lo >= 0) positive.Add(first);
+ if (lo <= 0) negative.Add(first);
+ if (lo * hi >= 0) continue;
+ var edge = (Math.Min(first, next), Math.Max(first, next));
+ if (!intersections.TryGetValue(edge, out int cut))
+ {
+ double t = lo / (lo - hi);
+ var p = points[first];
+ var q = points[next];
+ cut = points.Count;
+ points.Add(new PlaPlanPoint(p.X + (q.X - p.X) * t, p.Y + (q.Y - p.Y) * t));
+ intersections.Add(edge, cut);
+ }
+ positive.Add(cut);
+ negative.Add(cut);
+ }
+ cells[c] = positive.ToArray();
+ cells.Add(negative.ToArray());
+ }
+ }
+
+ private static bool IsClosed(List triangles)
+ {
+ var sides = new Dictionary<(int, int), (int Count, int Balance)>();
+ for (int i = 0; i < triangles.Count; i += 3)
+ for (int j = 0; j < 3; j++)
+ {
+ int a = triangles[i + j], b = triangles[i + (j + 1) % 3];
+ var edge = (Math.Min(a, b), Math.Max(a, b));
+ var tally = sides.GetValueOrDefault(edge);
+ sides[edge] = (tally.Count + 1, tally.Balance + (a < b ? 1 : -1));
+ }
+ return sides.Values.All(s => s is (2, 0));
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.CurvedBeams.cs b/src/PlaIO/Internal/ElementReader.CurvedBeams.cs
new file mode 100644
index 0000000..700dfc6
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.CurvedBeams.cs
@@ -0,0 +1,280 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid ElementAssemblyRelation = new("68236820-e176-4e8c-be39-d5d56a7a71c0");
+ private static readonly Guid ElementAssemblyClass = new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d");
+ private static readonly Guid ElementAssemblyMemberClass = new("47a28b23-f655-49fa-b219-1511ca52c49a");
+ private static readonly Guid AttachedAnnotationClass = new("5793eecb-32e2-4fdd-b216-739ff6c806c4");
+ private static readonly Guid AttachedAnnotationRelation = new("386bc4fb-ea34-4287-8067-4f16b966b7af");
+ private static readonly Guid AngularDimensionClass = new("2120198c-d317-4cea-ab4e-c7b6ceb5156e");
+ private static readonly HashSet AngularDimensionAnchorRelations =
+ [
+ new("7469b782-0846-4120-b41e-e3a2f7ca9376"), new("1ff9df7b-3f2d-4f16-855a-b863af9ca26d"),
+ new("13fe778c-0592-4d95-a788-f5e0fed3bcbe"), new("b3ffaf20-1c37-4090-b8f3-9e65bd5fa244"),
+ ];
+
+ private static Guid ReadCurvedBeamMemo(ReadOnlySpan record, Guid owner, ModelGeometry geometry) =>
+ ReadPrismMemo(record, BeamMemoRelation, (group, member) => IsUntransformedAssemblyMember(geometry, owner, group, member),
+ (role, target) => IsPrismAnnotation(geometry, owner, role, target, allowLinearDimension: false));
+
+ private static bool IsPrismAnnotation(ModelGeometry geometry, Guid owner, Guid role, Guid target, bool allowLinearDimension) =>
+ role == AttachedAnnotationRelation ? allowLinearDimension && IsAttachedAnnotation(geometry, owner, target) :
+ AngularDimensionAnchorRelations.Contains(role) && geometry.Read(target, AngularDimensionClass) is { } dimension &&
+ ReadSingleRelation(dimension, role, requireSection: true) == owner;
+
+ private static bool IsAttachedAnnotation(ModelGeometry geometry, Guid owner, Guid target) =>
+ geometry.Read(target, AttachedAnnotationClass) is { } annotation &&
+ ReadSingleRelation(annotation, AttachedAnnotationRelation, requireSection: true) == owner;
+
+ private static bool IsUntransformedAssemblyMember(ModelGeometry geometry, Guid owner, Guid group, Guid member)
+ {
+ if (geometry.Read(group, ElementAssemblyClass) is not { } parent ||
+ !HasGeometryRelation(parent, ElementAssemblyRelation, owner) ||
+ geometry.Read(member, ElementAssemblyMemberClass) is not { Length: 144 } child ||
+ FindRelationshipSection(child, child.Length) != 90 ||
+ ReadDouble(child, 60) != 0 || ReadDouble(child, 68) != 0 || ReadDouble(child, 76) != 1)
+ return false;
+ var link = child.AsSpan(90);
+ return link[0] == 4 && new Guid(link.Slice(1, 16)) == ElementAssemblyRelation &&
+ BinaryPrimitives.ReadUInt32LittleEndian(link[17..]) == 2 &&
+ new Guid(link.Slice(21, 16)) == group && new Guid(link.Slice(37, 16)) == owner && link[53] == 0;
+ }
+
+ private static Elevations? ReadCurvedBeamGeometry(ReadOnlySpan record, Guid owner, ModelGeometry geometry,
+ PlaBeamReferenceAxis reference, PlaMemberProfile profile, double home, out PlaBoundingBox? box)
+ {
+ box = null;
+ Guid id = ReadCurvedBeamMemo(record, owner, geometry);
+ if (geometry.Read(id, BeamMemoClass) is not { } memo ||
+ ReadBeamAxisFrame(record, owner, geometry) is not { } frame ||
+ ReadCircularEdge(reference.Start, reference.End, reference.PlanSweepRadians, out _) is not { } arc)
+ return null;
+
+ var axis = frame.Axis with { Z = reference.StartElevationToProjectZero };
+ if (Math.Abs(axis.SinRoll) > JunctionTolerance || ProjectBeamProfile(axis, profile) is not { } section) return null;
+ double radialSign = -Math.Sign(arc.Sweep);
+ double u0 = section.Left, u1 = section.Right;
+ if (Math.Min(arc.Radius + radialSign * u0, arc.Radius + radialSign * u1) <= JunctionTolerance) return null;
+ var neighbors = new (Guid Id, BeamArcCap Cap)?[2];
+ var slabs = new Dictionary();
+ uint priority = ReadBeamSectionPriority(geometry, default, profile);
+ if (!HasOnlyBeamTargetContact(memo, Guid.Empty, Guid.Empty, owner, ReadContact)) return null;
+
+ var start = neighbors[0]?.Cap ?? BeamArcCap.Radial(arc, arc.Start, radialSign);
+ var end = neighbors[1]?.Cap ?? BeamArcCap.Radial(arc, arc.End, radialSign);
+ double angularRoom = Math.Min(Math.Abs(arc.Sweep), Math.Tau - Math.Abs(arc.Sweep)) / 2;
+ if (!start.StaysNear(arc.Start, angularRoom, u0, u1) || !end.StaysNear(arc.End, angularRoom, u0, u1))
+ return null;
+ if (slabs.Values.All(s => s.Band.Bottom > section.Height.Bottom + JunctionTolerance &&
+ s.Band.Top < section.Height.Top - JunctionTolerance))
+ {
+ box = CurvedBeamPlan(arc, start, end, u0, u1, section.Height, PointSurvives);
+ return CheckedElevations(section.Height.Bottom - home, section.Height.Top - home);
+ }
+ return null;
+
+ bool ReadContact(Guid relation, Guid junction)
+ {
+ if (relation == BeamSlabRelation)
+ return ReadSlab(id, junction);
+ if (!IsBeamEndRelation(relation) ||
+ ReadBeamAxisJunction(geometry, id, relation, junction) is not { } joint ||
+ !IsBeamEndRelation(joint.Reciprocal) ||
+ geometry.Read(joint.Peer, BeamMemoClass) is not { } peerMemo ||
+ !HasGeometryRelation(peerMemo, joint.Reciprocal, junction))
+ return false;
+
+ var point = new PlaPlanPoint(joint.X, joint.Y);
+ int side = BeamEndAt(reference, point, arc);
+ if (side < 0) return false;
+ if (neighbors[side] is { } saved) return saved.Id == joint.Peer;
+
+ Guid peerOwner = ReadSingleRelation(peerMemo, BeamMemoRelation, requireSection: true);
+ if (geometry.Read(peerOwner, BeamClass) is not { } peerBody) return false;
+ var peer = peerBody.AsSpan(FindClassFrame(peerBody, BeamClass));
+ if (ReadCurvedBeamMemo(peer, peerOwner, geometry) != joint.Peer ||
+ ReadBeamAxisFrame(peer, peerOwner, geometry) is not { } peerFrame ||
+ !SameIntersectionGroup(geometry, axis.Layer, peerFrame.Axis.Layer) ||
+ ReadBeamReferenceAxis(peer, peerOwner, geometry) is not { } other ||
+ !BeamEndsMeet(reference, side, other, point) ||
+ Math.Abs(other.StartElevationToProjectZero - axis.Z) > JunctionTolerance ||
+ Math.Abs(other.EndElevationToProjectZero - axis.Z) > JunctionTolerance ||
+ Math.Abs(peerFrame.Axis.SinRoll - axis.SinRoll) > JunctionTolerance ||
+ ReadMemberProfile(peer, peerOwner, beam: true, geometry) is not { } otherProfile ||
+ !SameBeamSection(profile, otherProfile) ||
+ !HasOnlyBeamTargetContact(peerMemo, joint.Reciprocal, junction, peerOwner, CheckPeerContact))
+ return false;
+
+ var peerNormal = side == 0 ? peerFrame.Planes.EndNormal : peerFrame.Planes.StartNormal;
+ var ownNormal = side == 0 ? frame.Planes.StartNormal : frame.Planes.EndNormal;
+ if (other.PlanSweepRadians == 0 &&
+ (!AlongAxis(peerNormal with { Z = 0 }, (side == 0 ? 1 : -1) * peerFrame.Axis.Dx,
+ (side == 0 ? 1 : -1) * peerFrame.Axis.Dy) || Math.Abs(peerNormal.Z) > JunctionTolerance) ||
+ ownNormal.Dot(peerNormal) >= 0)
+ return false;
+ var nominal = side == 0 ? arc.Start : arc.End;
+ var cap = Distance(point, nominal) > JunctionTolerance
+ ? BeamArcCap.Radial(arc, nominal, radialSign)
+ : BeamArcCap.AtJoint(arc, other, nominal, side, ownNormal, peerNormal);
+ if (cap is null) return false;
+ neighbors[side] = (joint.Peer, cap.Value);
+ return true;
+
+ bool CheckPeerContact(Guid role, Guid otherJunction)
+ {
+ if (role == BeamSlabRelation) return ReadSlab(joint.Peer, otherJunction);
+ if (!IsBeamEndRelation(role) ||
+ ReadBeamAxisJunction(geometry, joint.Peer, role, otherJunction) is not { } link ||
+ !IsBeamEndRelation(link.Reciprocal)) return false;
+ var contact = new PlaPlanPoint(link.X, link.Y);
+ if (link.Peer == id)
+ return BeamEndsMeet(reference, side, other, contact) && role == joint.Reciprocal &&
+ HasGeometryRelation(memo, relation, otherJunction);
+ if (BeamEndAt(other, contact) == side) return true;
+ if (geometry.Read(link.Peer, BeamMemoClass) is not { } farMemo ||
+ !HasGeometryRelation(farMemo, link.Reciprocal, otherJunction))
+ return false;
+ Guid farOwner = ReadSingleRelation(farMemo, BeamMemoRelation, requireSection: true);
+ if (geometry.Read(farOwner, BeamClass) is not { } farBody ||
+ ReadBeamReferenceAxis(farBody.AsSpan(FindClassFrame(farBody, BeamClass)), farOwner, geometry) is not { } far ||
+ far.PlanSweepRadians == 0 ||
+ ReadCircularEdge(far.Start, far.End, far.PlanSweepRadians, out _) is not { } farArc ||
+ BeamEndAt(far, contact, farArc) != 1 - side)
+ return false;
+ return BeamEndsMeet(far, 1 - side, other, contact);
+ }
+ }
+
+ bool ReadSlab(Guid beam, Guid junction)
+ {
+ if (geometry.Read(junction, BeamSlabJunctionClass) is not { } contact ||
+ ReadSingleRelation(contact, BeamSlabRelation, requireSection: true) != beam)
+ return false;
+ Guid slab = ReadSingleRelation(contact, SlabBeamRelation, requireSection: true);
+ if (geometry.Read(slab, SlabClass) is not { } body || !HasGeometryRelation(body, SlabBeamRelation, junction))
+ return false;
+ if (slabs.ContainsKey(slab)) return true;
+ var framed = body.AsSpan(FindClassFrame(body, SlabClass));
+ var location = ReadElementLocation(framed, "Slab", 0);
+ if (!SameIntersectionGroup(geometry, axis.Layer, location.LayerIndex) ||
+ !HasSupportedSlabContacts(framed, Guid.Empty, Guid.Empty, IsKnownContact,
+ (group, member) => IsUntransformedAssemblyMember(geometry, slab, group, member)))
+ return false;
+ var settings = AfterCountedString(framed, ClassElementIdOffset("Slab"));
+ if (priority > 0 && ReadSlabPriority(settings, geometry.Attributes) is { } p && p < priority) return true;
+ if (ReadElevations(framed, "Slab") is not { } planes ||
+ ReadFloorBox(framed, "Slab", planes, geometry.StoryElevation(location.HomeStoryIndex))
+ is not { } bounds)
+ return false;
+ if (DisjointHeights(bounds.ZMin, bounds.ZMax, section.Height)) return true;
+ var outline = ReadSlabOutline(settings);
+ if (ReadAfterVerticalSlabEdges(outline).IsEmpty) return false;
+ var plan = BinaryPrimitives.ReadUInt32LittleEndian(outline[47..]) == 0
+ ? ReadStraightRings(outline, out _) is { } rings ? new PlaSlabGeometry(rings, bounds.ZMin, bounds.ZMax, 0, null) : null
+ : ReadCurvedSlabGeometry(outline, bounds);
+ if (plan is null) return false;
+ slabs.Add(slab, new CurvedBeamSlab(new Elevations(bounds.ZMin, bounds.ZMax), plan));
+ return true;
+
+ bool IsKnownContact(Guid key, Guid target)
+ {
+ if (key == AttachedAnnotationRelation)
+ return IsAttachedAnnotation(geometry, slab, target);
+ if (key != SlabBeamRelation || geometry.Read(target, BeamSlabJunctionClass) is not { } link ||
+ ReadSingleRelation(link, key, requireSection: true) != slab)
+ return false;
+ Guid neighbor = ReadSingleRelation(link, BeamSlabRelation, requireSection: true);
+ return geometry.Read(neighbor, BeamMemoClass) is { } neighborMemo &&
+ HasGeometryRelation(neighborMemo, BeamSlabRelation, target);
+ }
+ }
+
+ bool PointSurvives(PlaPlanPoint point, double u)
+ {
+ var cutters = slabs.Values.Where(s => s.MayContain(point)).ToArray();
+ if (cutters.Length == 0) return true;
+ foreach (var component in profile.Components)
+ {
+ var ring = component.Rings[0];
+ for (int i = 0; i < ring.Count; i++)
+ {
+ var p = ring[i];
+ var q = ring[(i + 1) % ring.Count];
+ double a = axis.CosRoll * p.U - axis.SinRoll * p.Z;
+ double b = axis.CosRoll * q.U - axis.SinRoll * q.Z;
+ double z0 = axis.Z + axis.SinRoll * p.U + axis.CosRoll * p.Z;
+ double z1 = axis.Z + axis.SinRoll * q.U + axis.CosRoll * q.Z;
+ if (u == a && FreeAt(z0)) return true;
+ if ((u > Math.Min(a, b) && u < Math.Max(a, b)) &&
+ !(component.Arcs?.Any(edge => edge.RingIndex == 0 && edge.StartVertexIndex == i) ?? false) &&
+ FreeAt(z0 + (z1 - z0) * ((u - a) / (b - a))))
+ return true;
+ }
+ }
+ return false;
+
+ bool FreeAt(double z) => cutters.All(s => z < s.Band.Bottom - JunctionTolerance || z > s.Band.Top + JunctionTolerance);
+ }
+ }
+
+ private static bool SameBeamSection(PlaMemberProfile a, PlaMemberProfile b) =>
+ a.ProfileIndex == b.ProfileIndex && a.Components.Count == b.Components.Count &&
+ a.Components.Zip(b.Components).All(p => p.First.BuildingMaterialIndex == p.Second.BuildingMaterialIndex &&
+ p.First.Rings.Count == p.Second.Rings.Count &&
+ p.First.Rings.Zip(p.Second.Rings).All(r => r.First.SequenceEqual(r.Second)) &&
+ (p.First.Arcs ?? []).SequenceEqual(p.Second.Arcs ?? []));
+
+ private static int BeamEndAt(PlaBeamReferenceAxis axis, PlaPlanPoint point, SlabEdge? arc = null)
+ {
+ bool start = Matches(axis.Start, outward: -Math.Sign(axis.PlanSweepRadians));
+ bool end = Matches(axis.End, outward: Math.Sign(axis.PlanSweepRadians));
+ return start == end ? -1 : start ? 0 : 1;
+
+ bool Matches(PlaPlanPoint end, int outward)
+ {
+ double gap = Distance(end, point);
+ if (gap <= JunctionTolerance) return true;
+ // Near tangency the saved extra intersection can fall beyond the end of the drawn arc.
+ // Its tangential displacement must fit within the sagitta of the coordinate tolerance.
+ return arc is { } edge && gap * gap <= 2 * edge.Radius * JunctionTolerance &&
+ Math.Abs(Distance(edge.Center, point) - edge.Radius) <= JunctionTolerance &&
+ outward * Cross(edge.Center, end, point) > 0;
+ }
+ }
+
+ private static bool BeamEndsMeet(PlaBeamReferenceAxis curved, int side, PlaBeamReferenceAxis peer, PlaPlanPoint joint)
+ {
+ var a = side == 0 ? curved.Start : curved.End;
+ var b = side == 0 ? peer.End : peer.Start;
+ if (Distance(a, b) > JunctionTolerance) return false;
+ if (Distance(b, joint) <= JunctionTolerance) return true;
+ double length = Distance(peer.Start, peer.End);
+ return peer.PlanSweepRadians == 0 && Math.Abs(Cross(peer.Start, peer.End, joint)) <= JunctionTolerance * length;
+ }
+
+ private readonly record struct CurvedBeamSlab(Elevations Band, PlaSlabGeometry Section)
+ {
+ public bool MayContain(PlaPlanPoint point)
+ {
+ var ring = Section.Rings[0];
+ if (Section.Arcs is not { Count: > 0 })
+ return ContainsPoint(ring, point) || PointOnOpeningBoundary(ring, point);
+ var edges = new SlabEdge[ring.Count];
+ for (int i = 0; i < ring.Count; i++) edges[i] = new(ring[i], ring[(i + 1) % ring.Count], 0);
+ foreach (var item in Section.Arcs)
+ {
+ if (item.RingIndex != 0) continue;
+ var chord = edges[item.StartVertexIndex];
+ if (ReadCircularEdge(chord.Start, chord.End, item.SweepRadians, out _) is not { } edge) return true;
+ if (Math.Abs(Distance(edge.Center, point) - edge.Radius) <= JunctionTolerance &&
+ edge.IncludesDirection(point)) return true;
+ edges[item.StartVertexIndex] = edge;
+ }
+ return CurvedRingContainsPoint(ring, edges, point) || PointOnOpeningBoundary(ring, point);
+ }
+ }
+}
diff --git a/src/PlaIO/Internal/ElementReader.DoorParameters.cs b/src/PlaIO/Internal/ElementReader.DoorParameters.cs
new file mode 100644
index 0000000..1209a89
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.DoorParameters.cs
@@ -0,0 +1,214 @@
+using System.Buffers.Binary;
+using System.Text;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid LibraryParameterClass = new("11db227d-dbe4-45af-88b6-6fddea993f71");
+ private static readonly Guid LibraryParameterDirectory = new("34d77468-1d98-45b9-958d-1eea37423cb5");
+ private static readonly Guid LibraryParameterRelation = new("76ebf0a4-c2ef-483f-a1a8-28d3adde99a0");
+ private static ReadOnlySpan PlacedLibraryFrame => [1, 0, 0x83, 0, 3, 0, 0, 0, 1, 0, 2, 0];
+ private static ReadOnlySpan LibraryParameterFrame => [1, 0, 8, 0, 0x83, 0, 3, 0, 0, 0, 1, 0, 1, 0];
+ private const int LibraryParameterBase = 57;
+ private const int LibraryParameterRowSize = 72;
+ private static readonly (string Name, ushort Type, double? Plain, double Pocket)[] PassageSettings =
+ [
+ ("AC_WallType", 0, 1, 1),
+ ("gs_leaf_optype_m", 0, 1, 25),
+ ("gs_wallhole_nominal", 13, 1, 1),
+ ("gs_reveal_type_int", 0, 1, 1),
+ ("gs_closure_type_int", 0, 1, 1),
+ ("gs_trimtype_out_int", 0, 1, 1),
+ ("gs_trimtype_in_int", 0, 1, 1),
+ ("iThresholdType", 0, 2, -1),
+ ("gs_sunShade_iType", 0, 1, 1),
+ ("gs_sidelight_left", 13, 0, 0),
+ ("gs_sidelight_right", 13, 0, 0),
+ ("gs_sill_outside", 13, 0, 0),
+ ("gs_board_inside", 13, 0, 0),
+ ("gs_shutRoll_cutWallBehind", 13, 0, 0),
+ ("gs_shutLam_cutWallBehind", 13, 0, 0),
+ ("bMasonryArch", 13, 0, 0),
+ ("gs_pocket_door_frame", 13, null, 1),
+ ("gs_pocket_frame", 13, null, 0),
+ ("gs_leaf_center", 13, null, 1),
+ ("bThreshold", 13, null, 0),
+ ("gs_leaf_offset", 2, null, 0.01),
+ ("gs_leaf_undercut", 2, null, 0),
+ ("gs_leaf_thk", 2, null, 0.04),
+ ("ac_leaf_height", 2, null, 2.05),
+ ("ac_leaf_width", 2, null, PocketLeafWidth),
+ ("gs_leaf_panel_width", 2, null, PocketLeafWidth),
+ ("gs_frame_thk", 2, null, PocketFrameDepth),
+ ("gs_frame_width", 2, null, 0.05),
+ ("gs_frame_width_left", 2, null, 0.04),
+ ("gs_frame_width_right", 2, null, 0.04),
+ ("gs_frame_width_upper", 2, null, 0.04),
+ ];
+ private static readonly Dictionary PassageSettingValues =
+ PassageSettings.Select((field, index) => (field, index))
+ .ToDictionary(pair => pair.field.Name, pair => (pair.field.Type, pair.field.Plain, pair.field.Pocket, 1u << pair.index));
+ private static readonly uint PlainPassageMask = PassageSettingValues.Values.Where(s => s.Plain.HasValue)
+ .Aggregate(0u, (bits, setting) => bits | setting.Bit);
+ private static readonly uint PocketPassageMask = (1u << PassageSettings.Length) - 1;
+
+ private readonly record struct DoorParameterLink(Guid Descriptor, Guid Table);
+ private sealed record DoorParameterTable(PlaDoorWallHoleDimensions Dimensions, HashSet Descriptors,
+ bool NoOversize, bool PlainPassage, bool CenteredPocketPassage);
+
+ private static Dictionary ReadDoorParameterTables(IReadOnlyList pools,
+ Dictionary> entries)
+ {
+ var tables = new Dictionary();
+ foreach (var pool in pools)
+ {
+ // Door and library parameter records can be saved in separate pools.
+ ulong units = (ulong)(pool.TotalDecompressed / ExtentUnit);
+ if (pool.TotalDecompressed % ExtentUnit != 0 || !entries.TryGetValue(units, out var records)) continue;
+ byte[] data = pool.Decode();
+ foreach (var record in records)
+ {
+ if (ReadIndexedPayload(data, record) is not { } payload) continue;
+ var table = ReadDoorParameterTable(payload);
+ if (!tables.TryAdd(record.ObjectId, table) &&
+ (table is null || tables[record.ObjectId] is not { } previous ||
+ table.Dimensions != previous.Dimensions || table.NoOversize != previous.NoOversize ||
+ table.PlainPassage != previous.PlainPassage || table.CenteredPocketPassage != previous.CenteredPocketPassage ||
+ !table.Descriptors.SetEquals(previous.Descriptors)))
+ tables[record.ObjectId] = null;
+ }
+ }
+ return tables;
+ }
+
+ private static DoorParameterTable? ResolveDoorParameterTable(Dictionary tables, DoorParameterLink link)
+ {
+ var table = tables.GetValueOrDefault(link.Table);
+ return table is not null && table.Descriptors.Contains(link.Descriptor) ? table : null;
+ }
+
+ private static DoorParameterTable? ReadDoorParameterTable(ReadOnlySpan data)
+ {
+ if (!TryReadLibraryParameterFrame(data, out var rows, out _, out var relation)) return null;
+
+ double? width = null, height = null;
+ int oversizes = 0;
+ bool noOversize = true;
+ uint passageSettings = 0, plainSettings = 0, pocketSettings = 0;
+ for (int i = 0; i < rows.Length; i += LibraryParameterRowSize)
+ {
+ var row = rows.Slice(i, LibraryParameterRowSize);
+ var name = ReadLibraryParameterName(row);
+ if (name.IsEmpty) continue;
+ bool isWidth = name.SequenceEqual("ac_wallhole_width"u8);
+ if (!isWidth && !name.SequenceEqual("ac_wallhole_height"u8))
+ {
+ int bit = name.SequenceEqual("ac_left_oversize"u8) ? 1 :
+ name.SequenceEqual("ac_right_oversize"u8) ? 2 :
+ name.SequenceEqual("ac_lower_oversize"u8) ? 4 :
+ name.SequenceEqual("ac_upper_oversize"u8) ? 8 : 0;
+ if (bit != 0)
+ {
+ noOversize &= (oversizes & bit) == 0 && IsScalarLength(row) && ReadDouble(row, 24) == 0;
+ oversizes |= bit;
+ }
+ else if (PassageSettingValues.TryGetValue(Encoding.ASCII.GetString(name), out var setting))
+ {
+ bool valid = (passageSettings & setting.Bit) == 0 &&
+ BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) == setting.Type &&
+ BinaryPrimitives.ReadUInt64LittleEndian(row[12..]) == 0 && (setting.Type != 2 || IsScalarLength(row));
+ double actual = setting.Type == 2 ? ReadDouble(row, 24) : BinaryPrimitives.ReadInt32LittleEndian(row[24..]);
+ if (!valid)
+ {
+ plainSettings &= ~setting.Bit;
+ pocketSettings &= ~setting.Bit;
+ }
+ else
+ {
+ if (actual == setting.Plain) plainSettings |= setting.Bit;
+ if (Math.Abs(actual - setting.Pocket) <= JunctionTolerance) pocketSettings |= setting.Bit;
+ }
+ passageSettings |= setting.Bit;
+ }
+ continue;
+ }
+
+ ref double? value = ref (isWidth ? ref width : ref height);
+ if (value.HasValue || !IsScalarLength(row)) return null;
+ double dimension = ReadDouble(row, 24);
+ if (!(dimension > 0) || !double.IsFinite(dimension)) return null;
+ value = dimension;
+ }
+ if (width is not double w || height is not double h) return null;
+
+ var descriptors = ReadLibraryParameterOwners(relation);
+ return descriptors is null ? null : new DoorParameterTable(new(w, h), descriptors,
+ noOversize && oversizes == 15, plainSettings == PlainPassageMask, pocketSettings == PocketPassageMask);
+ }
+
+ private static bool TryReadLibraryParameterFrame(ReadOnlySpan data, out ReadOnlySpan rows,
+ out ReadOnlySpan table, out ReadOnlySpan relation)
+ {
+ const int rowStart = LibraryParameterBase + 8;
+ const int trailerSize = 24;
+ rows = table = relation = default;
+ if (data.Length < rowStart || new Guid(data[..16]) != LibraryParameterClass ||
+ !data[39..].StartsWith(LibraryParameterFrame) ||
+ !TryReadDeclaredRelations(data, out int end, out relation)) return false;
+ uint tableSize = BinaryPrimitives.ReadUInt32LittleEndian(data[53..]);
+ uint count = BinaryPrimitives.ReadUInt32LittleEndian(data[LibraryParameterBase..]);
+ if (end != (long)LibraryParameterBase + tableSize + trailerSize ||
+ tableSize < rowStart - LibraryParameterBase || count > (tableSize - (rowStart - LibraryParameterBase)) / LibraryParameterRowSize)
+ return false;
+ table = data.Slice(LibraryParameterBase, (int)tableSize);
+ rows = data.Slice(rowStart, (int)count * LibraryParameterRowSize);
+ return true;
+ }
+
+ private static bool TryReadDeclaredRelations(ReadOnlySpan data, out int end, out ReadOnlySpan relation)
+ {
+ const int bodyStart = 39;
+ end = 0;
+ relation = default;
+ if (data.Length < bodyStart + 7) return false;
+ uint bodySize = BinaryPrimitives.ReadUInt32LittleEndian(data[35..]);
+ if (bodySize > data.Length - bodyStart - 7) return false;
+ end = bodyStart + (int)bodySize;
+ if (BinaryPrimitives.ReadUInt32LittleEndian(data[end..]) != data.Length - end - 4 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(data[(end + 4)..]) != 1) return false;
+ relation = data[(end + 6)..];
+ return true;
+ }
+
+ private static ReadOnlySpan ReadLibraryParameterName(ReadOnlySpan row)
+ {
+ var name = row.Slice(32, 32);
+ int terminator = name.IndexOf((byte)0);
+ return terminator < 0 ? default : name[..terminator];
+ }
+
+ private static HashSet? ReadLibraryParameterOwners(ReadOnlySpan relation)
+ {
+ var entry = relation;
+ if (!TryReadGeometryRelation(ref relation, out byte tag, out Guid key, out _) ||
+ key != LibraryParameterRelation || tag is not (2 or 0x12) || relation is not [0])
+ return null;
+ var descriptors = new HashSet();
+ var ids = ReadRelationIds(entry, relation, tag);
+ for (int i = 0; i < ids.Length; i += 16)
+ {
+ Guid id = new(ids.Slice(i, 16));
+ if (id == Guid.Empty || !descriptors.Add(id)) return null;
+ }
+ return descriptors.Count == 0 ? null : descriptors;
+ }
+
+ private static bool IsScalarLength(ReadOnlySpan row) => IsScalarNumber(row, 2);
+
+ private static bool IsScalarNumber(ReadOnlySpan row, ushort type) =>
+ BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) == type &&
+ BinaryPrimitives.ReadUInt64LittleEndian(row[12..]) == 0 &&
+ BinaryPrimitives.ReadUInt32LittleEndian(row[68..]) == sizeof(double);
+}
diff --git a/src/PlaIO/Internal/ElementReader.Doors.cs b/src/PlaIO/Internal/ElementReader.Doors.cs
new file mode 100644
index 0000000..59f1e92
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.Doors.cs
@@ -0,0 +1,168 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private static readonly Guid PlacedLibraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f");
+ private static readonly Guid DoorLibraryRelation = new("672f1c46-64f3-41f5-8a4a-ffdfd86bcbfd");
+ private static readonly Guid SimpleDoorOpeningPart = new("f6fab810-3a56-4c74-8eb8-b58738a9ee9b");
+ private static readonly Guid SimpleDoorOpeningRevision = new("0adb90d2-efb3-4a46-ae2b-35a98d9eef91");
+ private static readonly Guid RectangularDoorOpeningPart = new("ffd54fba-1ad6-4cf7-87cc-918accd4e480");
+ private static readonly Guid RectangularDoorOpeningRevision = new("6ebb67a2-5c74-4640-ab79-86e54703485a");
+ private static readonly PlaLibraryPartReference SwingDoorPart = new(
+ new Guid("13d8efa7-3fee-4993-b7a5-d826a6830657"), new Guid("a4ce2f76-b4d0-4b26-a920-4a84fbe513dc"));
+ private static readonly PlaLibraryPartReference TransomDoorPart = new(
+ new Guid("e155d0a0-7435-41af-8668-b4bae047f2b2"), new Guid("460fe002-f8e8-4d2c-859e-e99587473cef"));
+ private static readonly PlaLibraryPartReference PocketDoorPart = new(
+ new Guid("e4b25630-169a-4820-8bd9-962ed253b6c1"), new Guid("318e68fb-15e0-4e0b-92ed-bbf67a14b2eb"));
+ private const double PocketLeafWidth = 0.6;
+ private const double PocketFrameDepth = 0.06;
+
+ private static PlaDoorDimensions? ReadDoorDimensions(ReadOnlySpan door, ReadOnlySpan settings)
+ {
+ if (door.Length < 286 || BinaryPrimitives.ReadUInt16LittleEndian(door[185..]) != 1 ||
+ BinaryPrimitives.ReadUInt32LittleEndian(door[268..]) != 1 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(door[272..]) != 83 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(door[274..]) is not (1 or 2))
+ return null;
+
+ double width = ReadDouble(door, 202), height = ReadDouble(door, 210);
+ if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0) return null;
+ var dimensions = new PlaDoorDimensions(width, height);
+ if (settings.Length >= 72 &&
+ settings[..24] is [0, 1, 0, 14, 0, 0, 0, 1 or 63, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 or 255, 0, 0] &&
+ ReadDouble(settings, 64) is var sill && double.IsFinite(sill))
+ dimensions = dimensions with { SillHeightFromAnchor = sill };
+ return dimensions;
+ }
+
+ private static Guid ReadDoorHost(ReadOnlySpan door, Guid id, ModelGeometry geometry)
+ {
+ var owners = ReadOpeningRelation(door, DoorHostRelation, owner: true);
+ if (owners.IsEmpty) return Guid.Empty;
+ Guid wallId = new(owners);
+ if (geometry.Read(wallId, WallClass) is not { } wall) return Guid.Empty;
+ var doors = ReadOpeningRelation(wall, DoorHostRelation);
+ bool found = false;
+ for (int i = 0; i < doors.Length; i += 16)
+ {
+ if (new Guid(doors.Slice(i, 16)) != id) continue;
+ if (found) return Guid.Empty;
+ found = true;
+ }
+ return found ? wallId : Guid.Empty;
+ }
+
+ private static PlaLibraryPartReference? ReadDoorLibraryPart(ModelGeometry geometry, ReadOnlySpan door, Guid id,
+ out DoorParameterLink parameterLink)
+ {
+ parameterLink = default;
+ Guid part = ReadSingleRelation(door, DoorLibraryRelation, 0x11, requireSection: true);
+ if (geometry.Read(part, PlacedLibraryClass) is not { Length: >= 89 } descriptor ||
+ !descriptor.AsSpan(39).StartsWith(PlacedLibraryFrame) ||
+ ReadSingleRelation(descriptor, DoorLibraryRelation, 0x12, requireSection: true) != id)
+ return null;
+ Guid family = new(descriptor.AsSpan(51, 16)), revision = new(descriptor.AsSpan(67, 16));
+ if (family == Guid.Empty || revision == Guid.Empty) return null;
+ Guid parameters = ReadSingleRelation(descriptor, LibraryParameterRelation, 0x11, requireSection: true);
+ if (parameters != Guid.Empty) parameterLink = new DoorParameterLink(part, parameters);
+ return new PlaLibraryPartReference(family, revision);
+ }
+
+ private static PlaDoorPlacement? ReadDoorPlacement(ModelGeometry geometry, ReadOnlySpan door, Guid host)
+ {
+ if (geometry.Read(host, WallClass) is not { } body || FindClassFrame(body, WallClass) is not (>= 0 and { } frame))
+ return null;
+ var wall = body.AsSpan(frame);
+ var wallSettings = AfterCountedString(wall, 197);
+ if (wallSettings.Length < 229 || wallSettings[184] != 0 ||
+ BinaryPrimitives.ReadUInt16LittleEndian(wallSettings[227..]) != 1) return null;
+
+ var settings = AfterCountedString(door, ClassElementIdOffset("Door"));
+ if (ReadDoorDimensions(door, settings) is not { SillHeightFromAnchor: { } sill } ||
+ ReadDoorStation(settings) is not { } station) return null;
+ double x = ReadDouble(wallSettings, 0), y = ReadDouble(wallSettings, 8);
+ double dx = ReadDouble(wallSettings, 16) - x, dy = ReadDouble(wallSettings, 24) - y;
+ double length = double.Hypot(dx, dy);
+ if (!double.IsFinite(length) || length <= JunctionTolerance || station < 0 || station > length) return null;
+ var point = new PlaPlanPoint(x + dx / length * station, y + dy / length * station);
+ if (!double.IsFinite(point.X) || !double.IsFinite(point.Y)) return null;
+ int? hostStory = ReadElementLocation(wall, "Wall", 0).HomeStoryIndex;
+ double height = ReadDouble(wallSettings, 161) + sill;
+ double? toHostStory = hostStory.HasValue && double.IsFinite(height) ? height : null;
+ return new PlaDoorPlacement(point, station, ToProjectZero(toHostStory, geometry.StoryElevation(hostStory)), toHostStory);
+ }
+
+ private static double? ReadDoorStation(ReadOnlySpan settings)
+ {
+ double station = ReadDouble(settings, 24);
+ return double.IsFinite(station) && ReadDouble(settings, 32) == 0 && ReadDouble(settings, 40) == 0 &&
+ ReadDouble(settings, 48) == 1 && ReadDouble(settings, 56) == 0 ? station : null;
+ }
+
+ private static bool ReadDoorCapObstacles(ModelGeometry geometry, Guid wall, Guid id,
+ ReadOnlySpan wallSettings, WallStrip strip, List obstacles)
+ {
+ if (geometry.Read(id, DoorClass) is not { } body) return false;
+ var door = body.AsSpan(FindClassFrame(body, DoorClass));
+ if (ReadDoorHost(door, id, geometry) != wall ||
+ ReadDoorLibraryPart(geometry, door, id, out var parameterLink) is not { } library)
+ return false;
+ var (family, revision) = library;
+
+ var settings = AfterCountedString(door, ClassElementIdOffset("Door"));
+ if (ReadDoorDimensions(door, settings) is not { SillHeightFromAnchor: { } sill } dimensions ||
+ ReadDoorStation(settings) is not { } station) return false;
+ bool pocket = library == PocketDoorPart;
+ if (library == SwingDoorPart || library == TransomDoorPart || pocket)
+ {
+ if (geometry.DoorParameters(parameterLink) is not { NoOversize: true, Dimensions: var hole } table ||
+ (pocket ? !table.CenteredPocketPassage || !HasSupportedPocketHost(geometry, wallSettings, hole) : !table.PlainPassage) ||
+ Math.Abs(hole.Width - dimensions.Width) > JunctionTolerance ||
+ Math.Abs(hole.Height - dimensions.Height) > JunctionTolerance)
+ return false;
+ dimensions = dimensions with { Width = hole.Width, Height = hole.Height };
+ }
+ else if (!(family == SimpleDoorOpeningPart && revision == SimpleDoorOpeningRevision ||
+ family == RectangularDoorOpeningPart && revision == RectangularDoorOpeningRevision))
+ return false;
+ int axis = strip.AlongX ? 0 : 8;
+ double origin = ReadDouble(wallSettings, axis), destination = ReadDouble(wallSettings, axis + 16);
+ double center = origin + Math.Sign(destination - origin) * station;
+ double start = center - dimensions.Width / 2, end = center + dimensions.Width / 2;
+ // Only the straight, vertical host placement establishes the aperture's height.
+ double bottom = ReadDouble(wallSettings, 161) + sill;
+ var height = BinaryPrimitives.ReadUInt16LittleEndian(wallSettings[227..]) == 1
+ ? CheckedElevations(bottom, bottom + dimensions.Height) : null;
+ if (!(start >= strip.Start - JunctionTolerance && end <= strip.End + JunctionTolerance && end > start))
+ return false;
+ obstacles.Add(new((Math.Max(start, strip.Start), Math.Min(end, strip.End)), height));
+ if (pocket)
+ {
+ // The verified recess fits within the leaf's width and the centered frame's depth.
+ // Include both possible directions so the placement flags cannot leave a cut unaccounted for.
+ AddPocket(Math.Max(start - PocketLeafWidth, strip.Start), start);
+ AddPocket(end, Math.Min(end + PocketLeafWidth, strip.End));
+ }
+ return true;
+
+ void AddPocket(double from, double to)
+ {
+ if (from >= to) return;
+ double middle = strip.AcrossMin + (strip.AcrossMax - strip.AcrossMin) / 2;
+ double low = middle - PocketFrameDepth / 2, high = middle + PocketFrameDepth / 2;
+ obstacles.Add(new((from, to), height, RectangleRing(strip.AlongX ? (from, low, to, high) : (low, from, high, to))));
+ }
+ }
+
+ private static bool HasSupportedPocketHost(ModelGeometry geometry, ReadOnlySpan settings, PlaDoorWallHoleDimensions hole) =>
+ settings.Length >= 231 && BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) == 2 &&
+ BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) == 1 &&
+ geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..]))
+ is [var outside, var core, var inside] &&
+ Math.Abs(outside.Thickness - 0.024) <= JunctionTolerance && Math.Abs(core.Thickness - 0.052) <= JunctionTolerance &&
+ Math.Abs(inside.Thickness - 0.024) <= JunctionTolerance && Math.Abs(ReadDouble(settings, 77) - 0.1) <= JunctionTolerance &&
+ Math.Abs(hole.Width - 0.7) <= JunctionTolerance && Math.Abs(hole.Height - 2.1) <= JunctionTolerance;
+}
diff --git a/src/PlaIO/Internal/ElementReader.Elevations.cs b/src/PlaIO/Internal/ElementReader.Elevations.cs
new file mode 100644
index 0000000..a9d8886
--- /dev/null
+++ b/src/PlaIO/Internal/ElementReader.Elevations.cs
@@ -0,0 +1,412 @@
+using System.Buffers.Binary;
+using PlaIO.Model;
+
+namespace PlaIO.Internal;
+
+internal static partial class ElementReader
+{
+ private readonly record struct Elevations(double Bottom, double Top, double? StoredProjectBottom = null);
+ private readonly record struct WallCut(Guid Junction, bool CoversWallJoins = false, Guid[]? BeamJunctions = null,
+ Guid OtherEndJunction = default);
+
+ private static readonly Guid DrawingRelation = new("9898f378-2c25-462e-86b9-5e6b7a9aa0e4");
+ private static readonly Guid DefaultElementRelation = new("3b42cf2e-0d77-4d3d-bf03-0b922103f576");
+ private static readonly Guid ElementComponentRelation = new("9534032d-da8d-4c44-b42b-6363688cafc6");
+ private static readonly Guid ElementSettingsRelation = new("c10473a6-9941-4108-b463-322b3ed18cfd");
+ private static readonly Guid ElementPartitionRelation = new("79b61203-ae84-4d88-a9c6-20ead705e0bc");
+ private static readonly Guid ElementCollectionRelation = new("a855b980-fd19-4560-8bc1-7a2b82c4f5aa");
+ private static readonly HashSet UnjoinedWallChildRelations =
+ [
+ DefaultElementRelation,
+ new("6cf2b574-87db-442c-ad71-859dfffd9a56"),
+ ElementComponentRelation,
+ ElementSettingsRelation,
+ ];
+
+ private static readonly HashSet UnjoinedWallOwnerRelations =
+ [
+ ElementPartitionRelation,
+ ElementCollectionRelation,
+ ];
+
+ private static Elevations? ReadElevations(ReadOnlySpan record, string type)
+ {
+ switch (type)
+ {
+ case "Slab":
+ {
+ var planes = AfterCountedString(record, ClassElementIdOffset(type));
+ if (!HasSupportedSlabReferencePlane(planes)) return null;
+
+ double reference = BinaryPrimitives.ReadDoubleLittleEndian(planes);
+ double thickness = BinaryPrimitives.ReadDoubleLittleEndian(planes[17..]);
+ if (thickness < 0) return null;
+ double top = reference + BinaryPrimitives.ReadDoubleLittleEndian(planes[9..]);
+ // shortcut: these are the saved slab planes, use evaluated geometry for model operations that alter them.
+ return CheckedElevations(top - thickness, top);
+ }
+ case "Zone":
+ {
+ var levels = ReadZoneSettings(record);
+ if (levels.Length < 24) return null;
+
+ double height = BinaryPrimitives.ReadDoubleLittleEndian(levels[8..]);
+ if (height < 0) return null;
+ double bottom = BinaryPrimitives.ReadDoubleLittleEndian(levels) +
+ BinaryPrimitives.ReadDoubleLittleEndian(levels[16..]);
+ return CheckedElevations(bottom, bottom + height);
+ }
+ default:
+ return null;
+ }
+ }
+
+ private static ReadOnlySpan ReadZoneSettings(ReadOnlySpan record) =>
+ AfterCountedString(AfterCountedString(record, 253), sizeof(ushort));
+
+ private static Elevations? ReadWallElevations(ReadOnlySpan record, Guid wallId, ElementLocation location,
+ ModelGeometry geometry, (double X0, double Y0, double X1, double Y1)? authoredFootprint, PlaWallReferencePlan? referencePlan,
+ PlaWallProfile? profile, out PlaBoundingBox? boundingBox, out PlaWallExtrusion? extrusion, out List? isolatedDoors,
+ out bool needsDoorSolid, out (double? Bottom, double? Top) retainedCap)
+ {
+ boundingBox = null;
+ extrusion = null;
+ isolatedDoors = null;
+ needsDoorSolid = false;
+ retainedCap = default;
+ const int id = 197;
+ if (record.Length < id || !record[(id - ElementIdFrame.Length)..].StartsWith(ElementIdFrame))
+ return null;
+
+ var settings = AfterCountedString(record, id);
+ bool emptyOutline = HasUncachedDoorWallOutline(record, settings);
+ if ((!emptyOutline && settings.Length < 563) ||
+ BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) is not (1 or 2 or 3)) return null;
+ boundingBox = emptyOutline ? null : ReadSavedWallBox(settings);
+ if (ReadWallReferencePlanes(settings, location, geometry) is not { } bounds) return null;
+ if (!emptyOutline && boundingBox is null && geometry.StoryElevation(location.HomeStoryIndex) is { } story)
+ boundingBox = ReadWallBoxWithoutPlanCache(settings, location, authoredFootprint, profile, bounds, story);
+
+ double boxBottom = emptyOutline ? double.NaN : ReadDouble(settings, 547);
+ double boxTop = emptyOutline ? double.NaN : ReadDouble(settings, 555);
+ // The reference planes and the saved world-space envelope must describe the same height.
+ var contour = ReadWallContour(geometry, record, wallId);
+ bool hasWorldEnvelope = Math.Abs((boxTop - boxBottom) - (bounds.Top - bounds.Bottom)) <= JunctionTolerance;
+ var inline = emptyOutline || boundingBox is not null && HasEmptyWallPlanCache(settings) ? authoredFootprint : null;
+ var wall = emptyOutline && inline is null ? null : ReadWallStrip(settings, contour, inline);
+ bool needsAuthoredFootprint = !hasWorldEnvelope && (wall is null || contour is null && inline is null);
+ if (needsAuthoredFootprint && authoredFootprint is null) return null;
+ if (!HasSupportedWallRelations(record, settings, wallId, location, geometry, bounds, wall, default, emptyOutline,
+ out var evaluated, out var cutter, out bool onlyWallJunctions, out bool unjoined, out var doorIds, out var survivingCap))
+ {
+ if (!needsAuthoredFootprint && (!hasWorldEnvelope || geometry.StoryElevation(location.HomeStoryIndex) is not { } homeLevel ||
+ Math.Abs(bounds.Bottom + homeLevel - boxBottom) <= JunctionTolerance))
+ retainedCap = survivingCap;
+ return null;
+ }
+ if (needsAuthoredFootprint && !unjoined) return null;
+ if (cutter.Junction != Guid.Empty &&
+ !HasSupportedWallRelations(record, settings, wallId, location, geometry, evaluated, wall, cutter, false,
+ out _, out _, out _, out _, out _, out _))
+ return null;
+ if (boundingBox is null && onlyWallJunctions && contour is { } plan && wall is not null)
+ boundingBox = ProjectBoundingBox(plan, evaluated, geometry.StoryElevation(location.HomeStoryIndex));
+ if (boundingBox is null && (unjoined || doorIds is not null) && authoredFootprint is { } authored)
+ boundingBox = ProjectBoundingBox(authored, evaluated, geometry.StoryElevation(location.HomeStoryIndex));
+ if (unjoined && boundingBox is { } box && geometry.StoryElevation(location.HomeStoryIndex) is { } home)
+ extrusion = ReadWallExtrusion(settings, referencePlan, profile, evaluated, home, box);
+ isolatedDoors = doorIds;
+ needsDoorSolid = emptyOutline && doorIds is not null;
+ return hasWorldEnvelope ? evaluated with { StoredProjectBottom = boxBottom + (evaluated.Bottom - bounds.Bottom) } : evaluated;
+ }
+
+ private static Elevations? ReadWallReferencePlanes(ReadOnlySpan settings, ElementLocation location, ModelGeometry geometry)
+ {
+ if (settings.Length < 169) return null;
+ double bottom = ReadDouble(settings, 161);
+ double top = bottom + ReadDouble(settings, 153);
+ if (location.TopStoryPartition != Guid.Empty)
+ {
+ if (geometry.LinkedElevation(location.TopStoryPartition) is not { } linkedStory ||
+ geometry.StoryElevation(location.HomeStoryIndex) is not { } home) return null;
+ top = linkedStory - home + ReadDouble(settings, 145);
+ }
+ return top > bottom ? CheckedElevations(bottom, top) : null;
+ }
+
+ private static bool HasSupportedWallRelations(ReadOnlySpan record, ReadOnlySpan settings,
+ Guid wallId, ElementLocation location, ModelGeometry geometry, Elevations bounds, WallStrip? wall, WallCut validatedCut,
+ bool requiresIsolated,
+ out Elevations evaluated, out WallCut cutter, out bool onlyWallJunctions, out bool unjoined, out List? isolatedDoors,
+ out (double? Bottom, double? Top) retainedCap)
+ {
+ evaluated = bounds;
+ cutter = default;
+ onlyWallJunctions = true;
+ unjoined = false;
+ isolatedDoors = null;
+ retainedCap = default;
+ List? doorOwners = null;
+ int start = FindRelationshipSection(record, record.Length);
+ if (start < 0) return false;
+ var data = record[start..];
+ var blocked = new List();
+ List? doorCuts = null;
+ var contacts = new List<(Guid Id, Guid Key, uint Priority)>();
+ HashSet? slabLinks = null;
+ HashSet? slabs = null;
+ List? operations = null;
+ List? openings = null;
+ var profile = ReadWallProfileVector(geometry, wallId, record);
+ bool basic = IsBasicWall(settings);
+ if (BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) == 3 && profile.IsEmpty) return false;
+ uint? slabCutPriority = basic ? null : ReadCompositeWallCutPriority(settings, geometry.Attributes);
+ while (data.Length >= 17)
+ {
+ var entry = data;
+ if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid target)) return false;
+ if (key == WallTopStoryRelation)
+ {
+ if (tag != 0x12 || target == Guid.Empty || target != location.TopStoryPartition) return false;
+ continue;
+ }
+ if ((tag is 1 or 0x11) && key == DrawingRelation ||
+ tag == 0x11 && (UnjoinedWallChildRelations.Contains(key) || key == LinkedElementSettingsRelation) ||
+ tag == 2 && key == AttributeOwnerRelation ||
+ tag == 0x12 && (key == DatabaseElementList || key == AttributeOwnerRelation || UnjoinedWallOwnerRelations.Contains(key)))
+ continue;
+ if (tag == 0x11 && key == PlanContourRelation &&
+ geometry.Read(target, WallPlanContourClass) is { } contour &&
+ ReadSingleRelation(contour, PlanContourRelation, requireSection: true) == wallId)
+ continue;
+ if (tag == 0x11 && key == WallProfileRelation && !profile.IsEmpty) continue;
+ if (key == DoorHostRelation)
+ {
+ if (tag is not (1 or 0x11) || wall is not { } wallStrip || doorCuts is not null) return false;
+ var doorIds = ReadRelationIds(entry, data, tag);
+ if (doorIds.IsEmpty) return false;
+ doorCuts = [];
+ doorOwners = [];
+ for (int i = 0; i < doorIds.Length; i += 16)
+ {
+ Guid door = new(doorIds.Slice(i, 16));
+ if (!ReadDoorCapObstacles(geometry, wallId, door, settings, wallStrip, doorCuts))
+ return false;
+ doorOwners.Add(door);
+ }
+ onlyWallJunctions = false;
+ continue;
+ }
+ if (key == CutElementRelation || key == OpeningHostRelation)
+ {
+ if (requiresIsolated || tag is not (1 or 0x11)) return false;
+ var openingIds = ReadRelationIds(entry, data, tag);
+ if (openingIds.IsEmpty) return false;
+ for (int i = 0; i < openingIds.Length; i += 16)
+ {
+ if (ReadWallOpeningContact(geometry, record, wallId, key, new Guid(openingIds.Slice(i, 16))) is not { } opening)
+ return false;
+ (openings ??= []).Add(opening);
+ }
+ onlyWallJunctions = false;
+ continue;
+ }
+ if (key == ElementAssemblyRelation)
+ {
+ var pairs = ReadRelationIds(entry, data, tag);
+ if (tag == 2 && WallIsSubtractionOperator(geometry, wallId, pairs)) continue;
+ if (requiresIsolated || tag != 1 || wall is not { } operandTarget || operations is not null ||
+ BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1 ||
+ ReadWallSlabOperations(geometry, wallId, pairs,
+ (ReadJoinedWallStrip(geometry, wallId, operandTarget, location) ?? operandTarget).Footprint) is not { } parsed) return false;
+ operations = parsed;
+ continue;
+ }
+ if (key == ZoneCalculationRelation)
+ {
+ if (tag != 2 || !WallBoundsZones(geometry, wallId, ReadRelationIds(entry, data, tag))) return false;
+ continue;
+ }
+ if (tag is 1 or 0x11 && (key == AttachedAnnotationRelation || key == WallLabelRelation || key == ElementPropertyOverrideLink))
+ {
+ var references = ReadRelationIds(entry, data, tag);
+ if (references.IsEmpty) return false;
+ for (int offset = 0; offset < references.Length; offset += 16)
+ {
+ var reference = new Guid(references.Slice(offset, 16));
+ if (reference == Guid.Empty ||
+ key == WallLabelRelation && !geometry.OwnsLabel(wallId, reference, key) ||
+ key == AttachedAnnotationRelation && !IsAttachedAnnotation(geometry, wallId, reference))
+ return false;
+ }
+ continue;
+ }
+ if (requiresIsolated || tag is not (1 or 0x11) || (key != FirstWallEndRelation && key != SecondWallEndRelation &&
+ key != WallSlabRelation && key != WallBeamRelation && key != WallColumnRelation) ||
+ ReadLowestWallPriority(settings, geometry.Attributes, profile) is not { } priority ||
+ priority == 0)
+ return false;
+ if (validatedCut.Junction != Guid.Empty && !validatedCut.CoversWallJoins &&
+ (key == FirstWallEndRelation || key == SecondWallEndRelation)) return false;
+ onlyWallJunctions &= key == FirstWallEndRelation || key == SecondWallEndRelation;
+ var ids = tag == 1 ? entry.Slice(21, entry.Length - data.Length - 21) : entry.Slice(17, 16);
+ for (int i = 0; i < ids.Length; i += 16)
+ {
+ var id = new Guid(ids.Slice(i, 16));
+ if (id == Guid.Empty) return false;
+ if (key == WallSlabRelation)
+ {
+ if (!(slabLinks ??= []).Add(id) || ReadWallSlabContact(geometry, wallId, id, out Guid slab) is null)
+ return false;
+ // Separate reciprocal junctions can refer to the same cutting solid.
+ if (!(slabs ??= []).Add(slab)) continue;
+ }
+ contacts.Add((id, key, priority));
+ }
+ }
+ if (data is not [0]) return false;
+ if (operations is not null)
+ contacts.RemoveAll(c => c.Key == WallSlabRelation &&
+ SlabJunctionIsInactive(geometry, wallId, location.LayerIndex, c.Id, fromWall: true));
+ bool isolated = contacts.Count == 0 && operations is null && openings is null;
+ unjoined = isolated && doorCuts is null;
+ if (isolated) isolatedDoors = doorOwners;
+ if (validatedCut.Junction == Guid.Empty && wall is { } targetWall)
+ {
+ if (ResolveJoinedWallSlabs(geometry, wallId, location, settings, targetWall, bounds, contacts, operations, basic,
+ slabCutPriority, doorCuts, out bool unresolvedCoverage, out var joinedEnds) is { } jointCut)
+ {
+ evaluated = jointCut;
+ return WallOpeningsMissEnds(openings, evaluated);
+ }
+ retainedCap = (CheckWallEndOpeningClearance(joinedEnds.Bottom, openings),
+ CheckWallEndOpeningClearance(joinedEnds.Top, openings));
+ // Separate tests of the cutters cannot establish the result of an unresolved combined cut.
+ if (unresolvedCoverage || operations?.Exists(op => op.MayLoseMaterial) == true &&
+ contacts.Exists(c => c.Key == WallSlabRelation || c.Key == WallBeamRelation || c.Key == WallColumnRelation))
+ return false;
+ }
+ if (doorCuts is not null) blocked.AddRange(doorCuts);
+ // A slab cut can account for beam contacts that cannot be resolved in isolation.
+ foreach (var (id, key, priority) in contacts.OrderBy(c => c.Key == WallBeamRelation))
+ {
+ if ((key == WallSlabRelation || key == WallBeamRelation) &&
+ (id == validatedCut.Junction || id == validatedCut.OtherEndJunction) ||
+ key == WallBeamRelation && ((validatedCut.BeamJunctions?.Contains(id) ?? false) ||
+ (cutter.BeamJunctions?.Contains(id) ?? false))) continue;
+ if (!WallKeepsItsPlanes(geometry, wallId, id, key, priority, location, bounds, wall, basic, slabCutPriority, blocked,
+ out var clipped, out var wallCut)) return false;
+ if (clipped == bounds) continue;
+ if (validatedCut.Junction != Guid.Empty) return false;
+ if (cutter.Junction != Guid.Empty)
+ {
+ if (!cutter.CoversWallJoins || !wallCut.CoversWallJoins || cutter.OtherEndJunction != Guid.Empty ||
+ cutter.BeamJunctions is not null || wallCut.BeamJunctions is not null ||
+ (clipped.Bottom != bounds.Bottom) == (evaluated.Bottom != bounds.Bottom) ||
+ (clipped.Top != bounds.Top) == (evaluated.Top != bounds.Top) ||
+ CheckedElevations(Math.Max(evaluated.Bottom, clipped.Bottom), Math.Min(evaluated.Top, clipped.Top))
+ is not { } intersection || intersection.Bottom >= intersection.Top)
+ return false;
+ cutter = cutter with { OtherEndJunction = wallCut.Junction };
+ evaluated = intersection;
+ continue;
+ }
+ cutter = wallCut;
+ evaluated = clipped;
+ }
+ if (operations is not null)
+ {
+ if (cutter.Junction != Guid.Empty || validatedCut.Junction != Guid.Empty ||
+ ResolveWallSlabOperations(geometry, location, wall!.Value, bounds, operations, blocked) is not { } operationBounds ||
+ contacts.Count != 0 && operationBounds != bounds)
+ return false;
+ onlyWallJunctions = false;
+ evaluated = operationBounds;
+ return WallOpeningsMissEnds(openings, evaluated);
+ }
+ if (!WallOpeningsMissEnds(openings, evaluated)) return false;
+ // A proven cut is checked again at the surviving heights, with fresh blocked intervals.
+ if (blocked.Count == 0 || cutter.CoversWallJoins) return true;
+ var (bottom, top) = WallCapsWithMaterial(wall!.Value, bounds, blocked);
+ if (bottom && top) return true;
+ if (cutter.Junction == Guid.Empty && validatedCut.Junction == Guid.Empty && blocked.TrueForAll(obstacle => obstacle.HasVerifiedExtent))
+ retainedCap = (retainedCap.Bottom ?? (bottom ? bounds.Bottom : null), retainedCap.Top ?? (top ? bounds.Top : null));
+ return false;
+ }
+
+ private static double? CheckWallEndOpeningClearance(double? elevation, List? openings) =>
+ elevation is { } end && (openings is null ||
+ openings.All(o => end < o.Bottom - JunctionTolerance || end > o.Top + JunctionTolerance)) ? end : null;
+
+ private static bool WallOpeningsMissEnds(List? openings, Elevations bounds) =>
+ openings is null || openings.All(o => MissesEndFaces(o.Bottom, o.Top, bounds, bounds.Bottom, bounds.Top));
+
+ private static bool IsBasicWall(ReadOnlySpan settings) =>
+ BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) == 1;
+
+ private static uint? ReadCompositeWallCutPriority(ReadOnlySpan settings, JunctionAttributes attributes)
+ {
+ if (BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) != 2 ||
+ attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..])) is not { } skins ||
+ skins.Any(skin => !double.IsFinite(skin.Thickness) || skin.Thickness <= 0) ||
+ !(Math.Abs(skins.Sum(skin => skin.Thickness) - ReadDouble(settings, 77)) <= JunctionTolerance))
+ return null;
+ // The last surviving wall skin controls the elevation of the cut end.
+ return skins.Max(skin => skin.Priority);
+ }
+
+ private static uint? ReadLowestWallPriority(ReadOnlySpan