From cfcc403abff7fd1a7f3bbea3a31f1a00e277678d Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:42:51 +0300 Subject: [PATCH 1/3] Read Archicad model data from PLN and PLA --- CHANGELOG.md | 128 +- README.md | 23 +- docs/cli.md | 107 +- docs/getting-started.md | 5 +- docs/index.md | 2 +- docs/public-api.md | 472 +- docs/reader-parity.md | 139 + docs/scene.md | 73 +- docs/toc.yml | 2 + src/PlaIO.Cli/Cli.cs | 53 +- src/PlaIO.Scene/PlaExtrusionMesh.cs | 258 + src/PlaIO.Scene/PlaIO.Scene.csproj | 5 +- src/PlaIO.Scene/PlaSceneOptions.cs | 2 +- src/PlaIO.Scene/PlaSceneProperties.cs | 176 + src/PlaIO.Scene/PlaSceneReader.cs | 87 +- src/PlaIO.Scene/PlaSceneResult.cs | 5 +- src/PlaIO/Internal/BlockScanner.cs | 6 +- .../Internal/ElementReader.BeamArcCaps.cs | 155 + .../Internal/ElementReader.BeamBounds.cs | 243 + .../Internal/ElementReader.BeamCoverage.cs | 200 + src/PlaIO/Internal/ElementReader.BeamCuts.cs | 498 ++ .../Internal/ElementReader.BeamElevations.cs | 233 + .../Internal/ElementReader.BeamEndPlanes.cs | 129 + .../Internal/ElementReader.BeamWallCuts.cs | 134 + src/PlaIO/Internal/ElementReader.Bounds.cs | 152 + .../Internal/ElementReader.CircularColumns.cs | 77 + .../Internal/ElementReader.Classifications.cs | 141 + .../Internal/ElementReader.ColumnCuts.cs | 481 ++ .../Internal/ElementReader.ColumnGeometry.cs | 435 ++ .../Internal/ElementReader.ColumnMesh.cs | 182 + .../Internal/ElementReader.CurvedBeams.cs | 280 + .../Internal/ElementReader.DoorParameters.cs | 181 + src/PlaIO/Internal/ElementReader.Doors.cs | 168 + .../Internal/ElementReader.Elevations.cs | 412 ++ src/PlaIO/Internal/ElementReader.Junctions.cs | 1042 ++++ .../Internal/ElementReader.LayoutRevisions.cs | 205 + src/PlaIO/Internal/ElementReader.Layouts.cs | 362 ++ src/PlaIO/Internal/ElementReader.Locations.cs | 217 + .../ElementReader.MaterialDirectories.cs | 55 + src/PlaIO/Internal/ElementReader.Materials.cs | 157 + .../Internal/ElementReader.ObliqueColumns.cs | 225 + .../Internal/ElementReader.OpeningGeometry.cs | 130 + src/PlaIO/Internal/ElementReader.Openings.cs | 155 + .../Internal/ElementReader.PlanarContours.cs | 161 + .../Internal/ElementReader.ProfileCatalog.cs | 115 + .../ElementReader.ProfileModifierValues.cs | 154 + .../ElementReader.ProfileModifiers.cs | 110 + .../Internal/ElementReader.Properties.cs | 226 + .../ElementReader.PropertyOverrides.cs | 73 + .../Internal/ElementReader.RecordFields.cs | 99 + src/PlaIO/Internal/ElementReader.SlabArcs.cs | 230 + .../Internal/ElementReader.SlabColumnCuts.cs | 208 + src/PlaIO/Internal/ElementReader.SlabCuts.cs | 424 ++ .../Internal/ElementReader.SlabGeometry.cs | 302 ++ .../Internal/ElementReader.SlabOpenings.cs | 274 + .../Internal/ElementReader.SlabWallCuts.cs | 183 + .../Internal/ElementReader.WallCapPlan.cs | 76 + .../Internal/ElementReader.WallExtrusion.cs | 146 + .../Internal/ElementReader.WallProfiles.cs | 167 + .../ElementReader.WallReferencePlan.cs | 109 + .../ElementReader.WallSlabOperations.cs | 472 ++ src/PlaIO/Internal/ElementReader.cs | 727 +++ src/PlaIO/Internal/EmbeddedLibraryReader.cs | 164 + src/PlaIO/Internal/PoolReader.cs | 49 +- src/PlaIO/Internal/QuickLzLevelOne.cs | 50 + src/PlaIO/Model/PlaBeamReferenceAxis.cs | 22 + src/PlaIO/Model/PlaBoundingBox.cs | 10 + src/PlaIO/Model/PlaClassificationSystem.cs | 25 + src/PlaIO/Model/PlaColumnCutMesh.cs | 13 + src/PlaIO/Model/PlaColumnExtrusion.cs | 43 + src/PlaIO/Model/PlaDoorDimensions.cs | 10 + src/PlaIO/Model/PlaDoorPlacement.cs | 9 + src/PlaIO/Model/PlaDoorWallHoleDimensions.cs | 6 + src/PlaIO/Model/PlaElement.cs | 116 + src/PlaIO/Model/PlaEmbeddedLibraryCatalog.cs | 21 + src/PlaIO/Model/PlaLayer.cs | 8 + src/PlaIO/Model/PlaLayoutBook.cs | 66 + src/PlaIO/Model/PlaMaterialCatalog.cs | 31 + src/PlaIO/Model/PlaMemberProfile.cs | 15 + src/PlaIO/Model/PlaObjectClass.cs | 7 + src/PlaIO/Model/PlaOpeningGeometry.cs | 17 + src/PlaIO/Model/PlaOpeningProfile.cs | 7 + src/PlaIO/Model/PlaProfileAttribute.cs | 40 + src/PlaIO/Model/PlaPropertyCatalog.cs | 40 + src/PlaIO/Model/PlaSlabGeometry.cs | 52 + src/PlaIO/Model/PlaStory.cs | 7 + src/PlaIO/Model/PlaWallExtrusion.cs | 15 + src/PlaIO/Model/PlaWallProfile.cs | 27 + src/PlaIO/Model/PlaWallReferencePlan.cs | 11 + src/PlaIO/PlaDocument.cs | 190 +- tests/PlaIO.Tests/CliTests.cs | 133 + .../ElementReaderTests.Classifications.cs | 129 + .../ElementReaderTests.DoorParameters.cs | 138 + .../ElementReaderTests.EmbeddedLibrary.cs | 103 + .../PlaIO.Tests/ElementReaderTests.Layouts.cs | 399 ++ .../ElementReaderTests.Properties.cs | 215 + .../ElementReaderTests.WallDoorCuts.cs | 101 + tests/PlaIO.Tests/ElementReaderTests.cs | 4828 +++++++++++++++++ tests/PlaIO.Tests/PlaSceneReaderTests.cs | 685 ++- 99 files changed, 20139 insertions(+), 111 deletions(-) create mode 100644 docs/reader-parity.md create mode 100644 src/PlaIO.Scene/PlaExtrusionMesh.cs create mode 100644 src/PlaIO.Scene/PlaSceneProperties.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamArcCaps.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamBounds.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamCoverage.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamElevations.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamEndPlanes.cs create mode 100644 src/PlaIO/Internal/ElementReader.BeamWallCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.Bounds.cs create mode 100644 src/PlaIO/Internal/ElementReader.CircularColumns.cs create mode 100644 src/PlaIO/Internal/ElementReader.Classifications.cs create mode 100644 src/PlaIO/Internal/ElementReader.ColumnCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.ColumnGeometry.cs create mode 100644 src/PlaIO/Internal/ElementReader.ColumnMesh.cs create mode 100644 src/PlaIO/Internal/ElementReader.CurvedBeams.cs create mode 100644 src/PlaIO/Internal/ElementReader.DoorParameters.cs create mode 100644 src/PlaIO/Internal/ElementReader.Doors.cs create mode 100644 src/PlaIO/Internal/ElementReader.Elevations.cs create mode 100644 src/PlaIO/Internal/ElementReader.Junctions.cs create mode 100644 src/PlaIO/Internal/ElementReader.LayoutRevisions.cs create mode 100644 src/PlaIO/Internal/ElementReader.Layouts.cs create mode 100644 src/PlaIO/Internal/ElementReader.Locations.cs create mode 100644 src/PlaIO/Internal/ElementReader.MaterialDirectories.cs create mode 100644 src/PlaIO/Internal/ElementReader.Materials.cs create mode 100644 src/PlaIO/Internal/ElementReader.ObliqueColumns.cs create mode 100644 src/PlaIO/Internal/ElementReader.OpeningGeometry.cs create mode 100644 src/PlaIO/Internal/ElementReader.Openings.cs create mode 100644 src/PlaIO/Internal/ElementReader.PlanarContours.cs create mode 100644 src/PlaIO/Internal/ElementReader.ProfileCatalog.cs create mode 100644 src/PlaIO/Internal/ElementReader.ProfileModifierValues.cs create mode 100644 src/PlaIO/Internal/ElementReader.ProfileModifiers.cs create mode 100644 src/PlaIO/Internal/ElementReader.Properties.cs create mode 100644 src/PlaIO/Internal/ElementReader.PropertyOverrides.cs create mode 100644 src/PlaIO/Internal/ElementReader.RecordFields.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabArcs.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabColumnCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabGeometry.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabOpenings.cs create mode 100644 src/PlaIO/Internal/ElementReader.SlabWallCuts.cs create mode 100644 src/PlaIO/Internal/ElementReader.WallCapPlan.cs create mode 100644 src/PlaIO/Internal/ElementReader.WallExtrusion.cs create mode 100644 src/PlaIO/Internal/ElementReader.WallProfiles.cs create mode 100644 src/PlaIO/Internal/ElementReader.WallReferencePlan.cs create mode 100644 src/PlaIO/Internal/ElementReader.WallSlabOperations.cs create mode 100644 src/PlaIO/Internal/ElementReader.cs create mode 100644 src/PlaIO/Internal/EmbeddedLibraryReader.cs create mode 100644 src/PlaIO/Model/PlaBeamReferenceAxis.cs create mode 100644 src/PlaIO/Model/PlaBoundingBox.cs create mode 100644 src/PlaIO/Model/PlaClassificationSystem.cs create mode 100644 src/PlaIO/Model/PlaColumnCutMesh.cs create mode 100644 src/PlaIO/Model/PlaColumnExtrusion.cs create mode 100644 src/PlaIO/Model/PlaDoorDimensions.cs create mode 100644 src/PlaIO/Model/PlaDoorPlacement.cs create mode 100644 src/PlaIO/Model/PlaDoorWallHoleDimensions.cs create mode 100644 src/PlaIO/Model/PlaElement.cs create mode 100644 src/PlaIO/Model/PlaEmbeddedLibraryCatalog.cs create mode 100644 src/PlaIO/Model/PlaLayer.cs create mode 100644 src/PlaIO/Model/PlaLayoutBook.cs create mode 100644 src/PlaIO/Model/PlaMaterialCatalog.cs create mode 100644 src/PlaIO/Model/PlaMemberProfile.cs create mode 100644 src/PlaIO/Model/PlaObjectClass.cs create mode 100644 src/PlaIO/Model/PlaOpeningGeometry.cs create mode 100644 src/PlaIO/Model/PlaOpeningProfile.cs create mode 100644 src/PlaIO/Model/PlaProfileAttribute.cs create mode 100644 src/PlaIO/Model/PlaPropertyCatalog.cs create mode 100644 src/PlaIO/Model/PlaSlabGeometry.cs create mode 100644 src/PlaIO/Model/PlaStory.cs create mode 100644 src/PlaIO/Model/PlaWallExtrusion.cs create mode 100644 src/PlaIO/Model/PlaWallProfile.cs create mode 100644 src/PlaIO/Model/PlaWallReferencePlan.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.Classifications.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.DoorParameters.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.EmbeddedLibrary.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.Layouts.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.Properties.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.WallDoorCuts.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.cs 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/README.md b/README.md index d84695a..28023fb 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, 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,11 @@ 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 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 +51,13 @@ 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 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 +76,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`, `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..85a2112 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -10,6 +10,14 @@ 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 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 +45,106 @@ 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. + +### 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/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..5189227 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -40,19 +40,489 @@ 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.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. 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. +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..48e7de3 --- /dev/null +++ b/docs/reader-parity.md @@ -0,0 +1,139 @@ +# 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` | `ReadStories()` provides the full saved catalog for supported story tables. 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. Grid paths 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 and layers. The scene adapter maps recognized elements, saved levels, 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). + +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..82375fc 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -1,42 +1,63 @@ # 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. - -## What the scene holds today - -- 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. - -A geometry-free scene file is a valid scene document: a consumer that reads it shows the model with no content to draw. +`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. + +## Contents + +- 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. +- 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`. + +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. | +| Info | `geometry-incomplete` | Reports how many decoded elements have no triangle mesh. | + +A malformed or ambiguous indexed object class 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.1, 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..2d09d1e 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,20 @@ 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 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 +36,14 @@ 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. + 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 +64,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 "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 +108,38 @@ 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 "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..602e936 100644 --- a/src/PlaIO.Scene/PlaSceneReader.cs +++ b/src/PlaIO.Scene/PlaSceneReader.cs @@ -4,22 +4,18 @@ 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, 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,14 +37,77 @@ private static PlaSceneResult Map(string path, string key) SourceFormat = SourceFormat(path), Producer = Producer, }); + bool hasClassTable = document.HasObjectClassTable; + var levels = new Dictionary(); + foreach (var story in hasClassTable ? document.ReadStories() : []) + { + 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 }); + } + + var elements = hasClassTable ? document.ReadElements() : []; + if (elements.Count == 0) + return new PlaSceneResult + { + Document = scene, + Diagnostics = [new(SceneSeverity.Info, "container-only", "The model contains no decoded elements.")], + }; + + 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(); return new PlaSceneResult { 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."), - ], + Diagnostics = withoutMesh == 0 ? [] : + [new(SceneSeverity.Info, "geometry-incomplete", FormattableString.Invariant( + $"Triangle meshes are unavailable for {withoutMesh} of {elements.Count} decoded elements."))], }; } diff --git a/src/PlaIO.Scene/PlaSceneResult.cs b/src/PlaIO.Scene/PlaSceneResult.cs index 00177bb..449feb7 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 scenes without decoded elements or with incomplete mesh 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..eabbeb4 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.DoorParameters.cs @@ -0,0 +1,181 @@ +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 LibraryParameterFrame => [1, 0, 8, 0, 0x83, 0, 3, 0, 0, 0, 1, 0, 1, 0]; + 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) + { + const int bodyOffset = 39; + const int tableOffset = 57; + const int trailerSize = 24; + const int rowStart = 65; + const int rowSize = 72; + if (data.Length < rowStart || new Guid(data[..16]) != LibraryParameterClass || + !data[bodyOffset..].StartsWith(LibraryParameterFrame)) return null; + uint bodySize = BinaryPrimitives.ReadUInt32LittleEndian(data[35..]); + uint tableSize = BinaryPrimitives.ReadUInt32LittleEndian(data[53..]); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(data[tableOffset..]); + if (bodySize < rowStart - bodyOffset || bodySize > data.Length - bodyOffset - 7 || + bodySize != (long)tableSize + tableOffset + trailerSize - bodyOffset || + tableSize < rowStart - tableOffset || count > (tableSize - (rowStart - tableOffset)) / rowSize) + return null; + int end = bodyOffset + (int)bodySize; + if (BinaryPrimitives.ReadUInt32LittleEndian(data[end..]) != data.Length - end - 4 || + BinaryPrimitives.ReadUInt16LittleEndian(data[(end + 4)..]) != 1) 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 < count; i++) + { + var row = data.Slice(rowStart + i * rowSize, rowSize); + var name = row.Slice(32, 32); + int terminator = name.IndexOf((byte)0); + if (terminator < 0) continue; + name = name[..terminator]; + 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 relation = data[(end + 6)..]; + 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 : new DoorParameterTable(new(w, h), descriptors, + noOversize && oversizes == 15, plainSettings == PlainPassageMask, pocketSettings == PocketPassageMask); + + static bool IsScalarLength(ReadOnlySpan row) => + BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) == 2 && + 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..6927f77 --- /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 DoorLibraryClass = 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, DoorLibraryClass) is not { Length: >= 89 } descriptor || + !descriptor.AsSpan(39).StartsWith(new byte[] { 1, 0, 131, 0, 3, 0, 0, 0, 1, 0, 2, 0 }) || + 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 settings, JunctionAttributes attributes, ReadOnlySpan profile) + { + if (BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1) return null; + return BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) switch + { + 1 => attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(settings[215..])), + 2 => attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..]))?.Min(skin => skin.Priority), + 3 => ReadWallProfilePriority(profile, attributes.Material, lowest: true), + _ => null, + }; + } + + private static bool TryReadGeometryRelation(ref ReadOnlySpan section, out byte tag, out Guid key, + out Guid target) + { + tag = 0; + key = target = Guid.Empty; + if (section.Length < 17) return false; + tag = section[0]; + key = new Guid(section.Slice(1, 16)); + var entries = section[17..]; + if (tag is 1 or 2) + { + if (entries.Length < 4) return false; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(entries); + if (count > (entries.Length - 4) / 16) return false; + section = entries[(4 + (int)count * 16)..]; + return true; + } + if (tag is not (0x11 or 0x12) || entries.Length < 16) return false; + target = new Guid(entries[..16]); + section = entries[16..]; + return true; + } + + private static ReadOnlySpan ReadRelationIds(ReadOnlySpan entry, ReadOnlySpan remainder, byte tag) => + tag is 1 or 2 ? entry.Slice(21, entry.Length - remainder.Length - 21) : entry.Slice(17, 16); + + private static ReadOnlySpan AfterCountedString(ReadOnlySpan record, int offset) + { + if (offset > record.Length || BinaryPrimitives.ReadUInt16LittleEndian(record[(offset - 2)..]) != 1 || + ReadElementId(record[offset..], out int consumed) is null) + return default; + return record[(offset + consumed)..]; + } + + private static Elevations? CheckedElevations(double bottom, double top) => + double.IsFinite(bottom) && double.IsFinite(top) ? new Elevations(bottom, top) : null; + + private static double? ToProjectZero(double? value, double? storyElevation) + { + double? sum = value + storyElevation; + return sum is { } z && double.IsFinite(z) ? z : null; + } +} diff --git a/src/PlaIO/Internal/ElementReader.Junctions.cs b/src/PlaIO/Internal/ElementReader.Junctions.cs new file mode 100644 index 0000000..766c832 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Junctions.cs @@ -0,0 +1,1042 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid ColumnBeamRelation = new("6346a816-1d7c-4e46-9609-67624e99d0fb"); + private static readonly Guid ColumnSlabRelation = new("87811dc4-1686-45f4-b1a6-dfaa81da44e4"); + private static readonly Guid ColumnWallRelation = new("27c70d06-a928-499c-a005-5307c9f10da0"); + private static readonly Guid BeamColumnJunctionClass = new("f7f60005-35d0-4346-87ab-29e087ac0bbf"); + private static readonly Guid SlabColumnJunctionClass = new("d5381783-6a19-4de8-9e52-2e04a3978db0"); + private static readonly Guid WallColumnJunctionClass = new("a9e0daf5-0932-4054-b976-d8f207bb865a"); + private static readonly Guid BeamColumnRelation = new("cd0b0837-0b34-4e96-8d66-9fe7d926478c"); + private static readonly Guid WallBeamJunctionClass = new("9eb0036e-2b99-4db1-b043-051fb1817f47"); + private static readonly Guid WallBeamRelation = new("b7a142a1-2e5f-4b17-9b52-40604fbc3828"); + private static readonly Guid BeamWallRelation = new("b6d5f795-c750-4a2f-9bb0-e659fb07513a"); + private static readonly Guid SlabColumnRelation = new("f6ee0d9c-27ad-44d0-824f-682969bb171e"); + private static readonly Guid WallColumnRelation = new("199f13d8-5fa0-4894-8adf-761a1442a7f7"); + private static readonly Guid SlabClass = new("945c1275-7948-41d4-8744-9d22d72ca486"); + private static readonly Guid WallClass = new("4f654582-33af-4e52-abfc-c35d46765ec4"); + private static readonly Guid WallProfileRelation = new("e63e7632-0efd-412d-8077-d3f3906b638a"); + private static readonly Guid WallProfileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"); + private static readonly Guid WallPlanContourClass = new("5f7c9d0d-a84b-4240-a67d-f1458abafd0e"); + private static readonly Guid FirstWallEndRelation = new("0e7a0206-f853-4c86-9f9e-43266b0ab58a"); + private static readonly Guid SecondWallEndRelation = new("df61b698-e5ca-45bf-99fd-0e574a5e54d5"); + private static readonly Guid WallJunctionPointRelation = new("90b557ed-5803-411b-af47-ef97d9d3e31e"); + private static readonly Guid WallJunctionPointClass = new("3367fbd4-7f06-4cef-bd01-09c83d399855"); + private static readonly Guid WallWallJunctionClass = new("68122649-d152-4046-8c2d-8880dfd880bf"); + private static readonly Guid WallSlabJunctionClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + private static readonly Guid WallSlabRelation = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + private static readonly Guid SlabWallRelation = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + private static readonly Guid BeamMemoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + private static readonly Guid BeamClass = new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca"); + private static readonly Guid ColumnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"); + private static readonly Guid ComplexSectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"); + private static readonly Guid ProfileShapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"); + private static readonly Guid ProfileShapeRelation = new("ca073b44-0655-407d-9715-1a019e628139"); + private static readonly Guid BuildingMaterialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + private static readonly Guid CompositeClass = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + + private static bool IsJunctionGeometryClass(Guid id) => + id == ColumnMemoClass || id == RectangularSectionClass || id == CircularColumnSectionClass || id == BeamColumnJunctionClass || + id == SlabColumnJunctionClass || id == WallColumnJunctionClass || id == BeamClass || id == BeamMemoClass || id == ColumnClass || + id == ComplexSectionClass || id == ProfileShapeClass || id == SlabClass || id == WallClass || id == WallProfileClass || + id == WallWallJunctionClass || id == WallSlabJunctionClass || id == WallBeamJunctionClass || id == WallPlanContourClass || + id == WallJunctionPointClass || id == BeamBeamJunctionClass || id == BeamSlabJunctionClass || + id == SlabLevelDimensionClass || id == OpeningClass || id == OpeningCutClass || id == DoorClass || id == DoorLibraryClass || + id == ElementAssemblyClass || id == ElementAssemblyMemberClass || id == AttachedAnnotationClass || id == AngularDimensionClass || + id == ZoneClass || id == ZoneBoundaryCalculationClass || id == PropertyOverrideClass; + + private readonly struct ModelGeometry(byte[] pool, ILookup? records, + Dictionary classes, Lazy attributes, Lazy> stories, + Lazy> partitions, Lazy labelOwners, + Dictionary doorParameters) + { + public JunctionAttributes Attributes => attributes.Value; + public double? StoryElevation(int? index) => index is { } story ? stories.Value.GetValueOrDefault(story).Elevation : null; + public double? LinkedElevation(Guid partition) => StoryElevation(partitions.Value.GetValueOrDefault(partition)); + public DoorParameterTable? DoorParameters(DoorParameterLink link) => ResolveDoorParameterTable(doorParameters, link); + public bool OwnsLabel(Guid owner, Guid label, Guid role) => + owner != Guid.Empty && labelOwners.Value.Owners.GetValueOrDefault((label, role)) == owner; + public bool SlabLabelIsMetadata(Guid owner, Guid label, Guid role) => + labelOwners.Value.Owners.TryGetValue((label, role), out Guid saved) + ? owner != Guid.Empty && saved == owner + : labelOwners.Value.Indexed.Contains(label); + + public byte[]? Read(Guid id, Guid expectedClass) + { + if (records is null || id == Guid.Empty) return null; + byte[]? result = null; + foreach (var record in records[id]) + { + if (classes[record.ClassNumber] != expectedClass) continue; + var payload = ReadIndexedPayload(pool, record); + if (payload is not { Length: >= 16 }) continue; + if (expectedClass == SlabClass || expectedClass == WallClass || expectedClass == BeamClass || + expectedClass == ColumnClass || expectedClass == OpeningClass || expectedClass == DoorClass + ? FindClassFrame(payload, expectedClass) < 0 : + new Guid(payload.AsSpan(0, 16)) != expectedClass) continue; + if (result is not null && !result.AsSpan().SequenceEqual(payload)) return null; + result = payload; + } + return result; + } + } + + private readonly record struct SlabSkin(double Thickness, uint Priority, bool? IsCore = null); + + private sealed record JunctionAttributes(Dictionary Material, Dictionary Composite, + Dictionary LayerGroup); + + private static bool SameIntersectionGroup(ModelGeometry geometry, int? first, int? second) => + first is { } a && second is { } b && + geometry.Attributes.LayerGroup.GetValueOrDefault(a) is > 0 and { } group && + geometry.Attributes.LayerGroup.GetValueOrDefault(b) == group; + + private static JunctionAttributes ReadJunctionAttributes(PlaDocument document, IReadOnlyList classes) + { + var classNumbers = classes.Where(c => c.Guid == BuildingMaterialClass || c.Guid == CompositeClass || c.Guid == LayerClass) + .ToDictionary(c => c.Number, c => c.Guid); + var materials = new Dictionary(); + var composites = new Dictionary>(); + var layers = new Dictionary(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || !classNumbers.TryGetValue(block.Kind, out Guid kind) || + !document.PayloadStartsWithClass(block, kind)) continue; + var payload = document.ReadPayload(block); + var data = ReadNamedAttribute(payload, out _, out int index); + if (data.IsEmpty) continue; + + if (kind == BuildingMaterialClass) + { + if (ReadBuildingMaterialPriority(data, out _) is { } priority) AddPriority(materials, index, priority); + } + else if (kind == LayerClass) + { + if (ReadLayerGroup(data) is { } group) AddPriority(layers, index, group); + } + else if (!composites.TryAdd(index, payload.AsMemory(payload.Length - data.Length)) && + !composites[index].Span.SequenceEqual(data)) + composites[index] = default; + } + + return new JunctionAttributes(materials, + composites.ToDictionary(c => c.Key, c => ReadCompositeSkins(c.Value.Span, materials)), layers); + } + + private static void AddPriority(Dictionary values, int index, uint value) + { + if (!values.TryAdd(index, value) && values[index] != value) values[index] = null; + } + + private static SlabSkin[]? ReadCompositeSkins(ReadOnlySpan data, Dictionary materials) + { + var rows = ReadCompositeSkinRows(data); + if (rows.IsEmpty) return null; + var skins = new SlabSkin[rows.Length / CompositeSkinSize]; + for (int i = 0; i < skins.Length; i++) + { + var skin = rows[(CompositeSkinSize * i)..]; + if (materials.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(skin[8..])) is not { } priority) + return null; + var function = ReadCompositeSkinFunction(skin); + skins[i] = new SlabSkin(ReadDouble(skin, 15), priority, function.HasValue ? function == 1 : null); + } + return skins; + } + + private static Elevations? ResolveColumnJunctions(ModelGeometry geometry, Guid memo, List<(Guid Key, Guid Id)> junctions, + ElementLocation location, int material, Elevations bounds, (double X0, double Y0, double X1, double Y1)? footprint, + double lowerMax, double upperMin, bool profiled, bool checkSolid, out bool keepsNominalBox, out bool solid, + RectangularColumnPlan? columnPlan = null) + { + keepsNominalBox = false; + solid = false; + if (geometry.Attributes.Material.GetValueOrDefault(material) is not { } priority || priority == 0) + return null; + bool cut = false; + bool beamContactsMissEnds = true; + List<(Guid Memo, Guid Junction)>? beams = null; + List? otherSlabs = null; + List? cuttingSlabs = null; + foreach (var (key, id) in junctions) + { + var (junctionClass, ownerKey) = key == ColumnBeamRelation ? (BeamColumnJunctionClass, BeamColumnRelation) : + key == ColumnWallRelation ? (WallColumnJunctionClass, WallColumnRelation) : (SlabColumnJunctionClass, SlabColumnRelation); + var contact = geometry.Read(id, junctionClass); + if (contact is null || ReadSingleRelation(contact, key, requireSection: true) != memo) return null; + Guid neighbor = ReadSingleRelation(contact, ownerKey, requireSection: true); + if (key == ColumnBeamRelation) + { + if (ReadBeamPriority(geometry, neighbor, id) is not { } beam) return null; + if (beam > priority) (beams ??= []).Add((neighbor, id)); + continue; + } + if (key == ColumnWallRelation) + { + if (geometry.Read(neighbor, WallClass) is not { } wallRecord || + !HasGeometryRelation(wallRecord, WallColumnRelation, id) || + ReadWallPriority(geometry, neighbor, wallRecord) is not { } wall || wall > priority) return null; + checkSolid &= profiled || !WallMayWrapColumn(geometry.Attributes, ReadWallSettings(wallRecord)); + continue; + } + + var slab = geometry.Read(neighbor, SlabClass); + if (slab is null || !HasGeometryRelation(slab, SlabColumnRelation, id)) return null; + var record = slab.AsSpan(FindClassFrame(slab, SlabClass)); + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (ReadSlabPriority(settings, geometry.Attributes) is not { } slabPriority) return null; + // At equal material priority an automatic column junction takes precedence over a beam or slab. + if (slabPriority <= priority) continue; + if (checkSolid) (cuttingSlabs ??= []).Add(slab); + if (SlabKeepsPlanes(geometry, record, settings, location, priority, lowerMax, upperMin, bounds, checkSkins: true)) + { + (otherSlabs ??= []).Add(slab); + continue; + } + if (cut || footprint is not { } xy || + !HasSupportedSlabContacts(record, SlabColumnRelation, id) || + ClipBySlab(geometry, location, record, settings, xy, bounds, lowerMax, upperMin, out _) is not { } clipped) + return null; + cut = true; + bounds = clipped; + } + if (beams is not null) + { + if (geometry.StoryElevation(location.HomeStoryIndex) is not { } home) + return null; + if (!cut && footprint is { } plan && + geometry.Attributes.LayerGroup.GetValueOrDefault(location.LayerIndex.GetValueOrDefault()) is > 0 && + ClipByBeamUnion(geometry, beams, BeamColumnRelation, location, home, plan, bounds, lowerMax, upperMin) is { } union) + { + cut = union != bounds; + beamContactsMissEnds = beams.All(b => BeamCannotCutColumnEnds(geometry, b.Memo, home, bounds, lowerMax, upperMin)); + bounds = union; + } + else + { + foreach (var (beam, junction) in beams) + { + if (BeamCannotCutColumnEnds(geometry, beam, home, bounds, lowerMax, upperMin)) continue; + if (cut || footprint is not { } xy || + geometry.Attributes.LayerGroup.GetValueOrDefault(location.LayerIndex.GetValueOrDefault()) is not > 0 || + ClipByBeam(geometry, beam, junction, BeamColumnRelation, location, home, xy, bounds, lowerMax, upperMin) is not { } clipped) + return null; + if (clipped == bounds) continue; + double low = clipped.Bottom == bounds.Bottom ? lowerMax : clipped.Bottom; + double high = clipped.Top == bounds.Top ? upperMin : clipped.Top; + if (beams.Any(b => b.Junction != junction && !BeamCannotCutColumnEnds(geometry, b.Memo, home, clipped, low, high))) + return null; + cut = true; + bounds = clipped; + } + } + } + if (cut && otherSlabs is not null) + { + foreach (var slab in otherSlabs) + { + var record = slab.AsSpan(FindClassFrame(slab, SlabClass)); + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (!SlabKeepsPlanes(geometry, record, settings, location, priority, Math.Max(lowerMax, bounds.Bottom), + Math.Min(upperMin, bounds.Top), bounds, checkSkins: true)) return null; + } + } + // shortcut: combined cuts involving skew faces or overlapping slab cuts need their evaluated solids. + keepsNominalBox = !cut && beamContactsMissEnds && junctions.All(c => c.Key != ColumnWallRelation); + solid = checkSolid && (!cut || footprint.HasValue) && + ColumnCuttersClearBody(geometry, location, bounds, priority, beams, cuttingSlabs, columnPlan); + return bounds; + } + + private static bool ColumnCuttersClearBody(ModelGeometry geometry, ElementLocation location, Elevations body, + uint priority, List<(Guid Memo, Guid Junction)>? beams, List? slabs, RectangularColumnPlan? columnPlan) + { + // End cuts prove removal outside the surviving interval. A mesh also needs the whole interval intact. + if (beams is not null && (geometry.StoryElevation(location.HomeStoryIndex) is not { } home || + beams.Any(beam => !BeamCannotCutColumnEnds(geometry, beam.Memo, home, body, body.Top, body.Bottom) && + (columnPlan is not { } plan || !JoinedBeamClearsColumn(geometry, beam.Memo, beam.Junction, location, home, plan))))) + return false; + if (slabs is null) return true; + foreach (var slab in slabs) + { + var record = slab.AsSpan(FindClassFrame(slab, SlabClass)); + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (!SlabKeepsPlanes(geometry, record, settings, location, priority, body.Top, body.Bottom, body, checkSkins: true)) + return false; + } + return true; + } + + private static ReadOnlySpan ReadWallSettings(byte[] wall) => + AfterCountedString(wall.AsSpan(FindClassFrame(wall, WallClass)), 197); + + private static bool WallMayWrapColumn(JunctionAttributes attributes, ReadOnlySpan settings) + { + if (BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) != 2) return false; + var skins = attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..])); + // Wrapping requires both a core and a non-core skin. + return skins is null || (!skins.All(skin => skin.IsCore == true) && !skins.All(skin => skin.IsCore == false)); + } + + private static uint? ReadWallPriority(ModelGeometry geometry, Guid wallId, byte[] wall) + { + var settings = ReadWallSettings(wall); + if (settings.Length < 231 || BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1) return null; + switch (BinaryPrimitives.ReadUInt16LittleEndian(settings[225..])) + { + case 1: + return geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(settings[215..])); + case 2: + return geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..])) + ?.Max(skin => skin.Priority); + case 3: + return ReadWallProfilePriority(ReadWallProfileVector(geometry, wallId, wall), geometry.Attributes.Material, lowest: false); + default: + return null; + } + } + + private static ReadOnlySpan ReadWallProfileVector(ModelGeometry geometry, Guid wallId, ReadOnlySpan wall) + => ReadWallProfileRecord(geometry, wallId, wall) is { } profile ? ReadSectionVector(profile, 394) : default; + + private static byte[]? ReadWallProfileRecord(ModelGeometry geometry, Guid wallId, ReadOnlySpan wall) + { + Guid profileId = ReadSingleRelation(wall, WallProfileRelation, 0x11, requireSection: true); + return geometry.Read(profileId, WallProfileClass) is { } profile && + ReadSingleRelation(profile, WallProfileRelation, requireSection: true) == wallId + ? profile : null; + } + + private static uint? ReadWallProfilePriority(ReadOnlySpan vector, Dictionary materials, bool lowest) + { + var items = ReadFirstWallHatch(vector, out uint count); + if (items.IsEmpty) return null; + uint limit = lowest ? uint.MaxValue : 0; + for (int i = 0; i < count; i++) + { + int size = ReadHatchSize(items, 2); + if (size == 0) return null; + if (materials.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(items[18..])) is not { } priority) + return null; + limit = lowest ? Math.Min(limit, priority) : Math.Max(limit, priority); + items = items[size..]; + if (i + 1 < count) + { + if (items.Length < 16) return null; + items = items[16..]; + } + } + return items.IsEmpty ? limit : null; + } + + private static ReadOnlySpan ReadFirstWallHatch(ReadOnlySpan vector, out uint count) + { + count = 0; + if (vector.IsEmpty) return default; + count = BinaryPrimitives.ReadUInt32LittleEndian(vector[69..]); + if (count == 0 || count > vector.Length / 65) return default; + for (int start = 128; start <= vector.Length - 59; start++) + if (ReadHatchSize(vector[start..], 2) != 0) return vector[start..]; + return default; + } + + private static uint? ReadBeamPriority(ModelGeometry geometry, Guid beamId, Guid junction) + { + var beam = geometry.Read(beamId, BeamMemoClass); + if (beam is null || !HasGeometryRelation(beam, BeamColumnRelation, junction)) return null; + var hatch = ReadBeamHatch(geometry, beamId, beam); + return hatch.IsEmpty ? null : geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])); + } + + private static ReadOnlySpan ReadBeamHatch(ModelGeometry geometry, Guid beamId, ReadOnlySpan beam) + { + Guid sectionId = ReadSingleRelation(beam, SectionProfileRelation, 0x11, requireSection: true); + if (geometry.Read(sectionId, RectangularSectionClass) is { } basic && + ReadSingleRelation(basic, SectionProfileRelation, requireSection: true) == beamId) + { + var hatch = ReadSectionHatch(basic, 141, 482); + return hatch.IsEmpty ? ReadSectionHatch(basic, 141, 482, hatchKind: 14) : hatch; + } + return ReadComplexSectionHatch(geometry, beamId, sectionId); + } + + private static ReadOnlySpan ReadComplexSectionHatch(ModelGeometry geometry, Guid owner, Guid sectionId) + => ReadComplexSectionProfile(geometry, owner, sectionId) is { } profile + ? ReadSectionHatch(profile, 392, 128) : default; + + private static byte[]? ReadComplexSectionProfile(ModelGeometry geometry, Guid owner, Guid sectionId) + { + if (geometry.Read(sectionId, ComplexSectionClass) is { } complex && + ReadSingleRelation(complex, SectionProfileRelation, requireSection: true) == owner) + { + Guid shapeId = ReadSingleRelation(complex, ProfileShapeRelation, 0x11, requireSection: true); + if (geometry.Read(shapeId, ProfileShapeClass) is { } profile && + ReadSingleRelation(profile, ProfileShapeRelation, requireSection: true) == sectionId) + return profile; + } + return null; + } + + private static bool HasGeometryRelation(ReadOnlySpan record, Guid relation, Guid id) + { + int start = FindRelationshipSection(record, record.Length); + if (start < 0) return false; + Span target = stackalloc byte[16]; + id.TryWriteBytes(target); + var data = record[start..]; + bool found = false; + while (data.Length >= 17) + { + var entry = data; + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid single)) return false; + if (key != relation) continue; + if (found) return false; + if (tag == 0x11) + { + found = single == id; + continue; + } + if (tag != 1) return false; + var ids = entry.Slice(21, entry.Length - data.Length - 21); + for (int i = 0; i < ids.Length; i += 16) + if (ids.Slice(i, 16).SequenceEqual(target)) found = true; + } + return found && data is [0]; + } + + private static uint? ReadSlabPriority(ReadOnlySpan settings, JunctionAttributes attributes) + { + if (settings.Length < 89 || BinaryPrimitives.ReadUInt16LittleEndian(settings[85..]) != 1) return null; + return BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) switch + { + 1 => attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(settings[73..])), + 2 => attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..]))?.Max(skin => skin.Priority), + _ => null, + }; + } + + private static bool SlabKeepsPlanes(ModelGeometry geometry, ReadOnlySpan slab, ReadOnlySpan settings, + ElementLocation target, uint priority, double lowerMax, double upperMin, Elevations bounds, bool checkSkins) + { + if (geometry.StoryElevation(target.HomeStoryIndex) is not { } home || + geometry.StoryElevation(ReadElementLocation(slab, "Slab", 0).HomeStoryIndex) is not { } slabStory || + ReadElevations(slab, "Slab") is not { } slabBounds || settings.Length < 89) + return false; + double bottom = slabBounds.Bottom + slabStory - home, top = slabBounds.Top + slabStory - home; + if (MissesEndFaces(bottom, top, bounds, lowerMax, upperMin)) return true; + // A wall may be cut below all the slab skins once an adjoining skin has sufficient priority. + if (!checkSkins || settings[8] != 0 || BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) != 2 || + geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])) is not { } skins) + return false; + foreach (var skin in skins) + { + if (!(skin.Thickness > 0 && double.IsFinite(skin.Thickness))) return false; + double skinBottom = top - skin.Thickness; + if (skin.Priority > priority && !MissesEndFaces(skinBottom, top, bounds, lowerMax, upperMin)) + return false; + top = skinBottom; + } + return Math.Abs(top - bottom) <= JunctionTolerance; + } + + private static bool MissesEndFaces(double low, double high, Elevations bounds, double lowerMax, double upperMin) => + high <= bounds.Bottom + JunctionTolerance || low >= bounds.Top - JunctionTolerance || + low > lowerMax + JunctionTolerance && high < upperMin - JunctionTolerance; + + private static bool HasSupportedSlabContacts(ReadOnlySpan slab, Guid reciprocal, Guid junction, + Func? acceptsOther = null, Func? acceptsMember = null, + Func? acceptsOperatorTarget = null, Func? acceptsTargetOperand = null) + { + int start = FindRelationshipSection(slab, slab.Length); + if (start < 0) return false; + var data = slab[start..]; + bool hasTarget = false, hasMembership = false, hasTargetOperands = false; + while (data.Length >= 17) + { + var entry = data; + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out _)) return false; + if ((tag is 1 or 0x11) && key == DrawingRelation || + tag == 0x11 && (key == DefaultElementRelation || key == ElementComponentRelation || + key == ElementSettingsRelation || key == LinkedElementSettingsRelation) || + tag == 2 && key == AttributeOwnerRelation || + reciprocal == Guid.Empty && tag == 1 && key == ElementPropertyOverrideLink || + tag == 0x12 && (key == ElementPartitionRelation || key == ElementCollectionRelation || + key == DatabaseElementList || key == AttributeOwnerRelation)) + continue; + if (tag == 2 && key == ElementAssemblyRelation && acceptsMember is not null && !hasMembership && + ReadRelationIds(entry, data, tag) is { Length: 32 } membership && + acceptsMember(new Guid(membership[..16]), new Guid(membership[16..]))) + { + hasMembership = true; + continue; + } + if (tag == 2 && key == ElementAssemblyRelation && acceptsOperatorTarget is not null && !hasMembership) + { + var pairs = ReadRelationIds(entry, data, tag); + if (pairs.IsEmpty || pairs.Length % 32 != 0) return false; + for (int i = 0; i < pairs.Length; i += 32) + if (!acceptsOperatorTarget(new Guid(pairs.Slice(i, 16)), new Guid(pairs.Slice(i + 16, 16)))) return false; + hasMembership = true; + continue; + } + if (tag == 1 && key == ElementAssemblyRelation && acceptsTargetOperand is not null && !hasTargetOperands) + { + var pairs = ReadRelationIds(entry, data, tag); + if (pairs.IsEmpty || pairs.Length % 32 != 0) return false; + for (int i = 0; i < pairs.Length; i += 32) + if (!acceptsTargetOperand(new Guid(pairs.Slice(i, 16)), new Guid(pairs.Slice(i + 16, 16)))) return false; + hasTargetOperands = true; + 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 id = new Guid(ids.Slice(i, 16)); + if (id == Guid.Empty) return false; + if (key == reciprocal && id == junction && !hasTarget) + hasTarget = true; + else if (id == junction || acceptsOther is null || !acceptsOther(key, id)) + return false; + } + } + return (hasTarget || reciprocal == Guid.Empty) && data is [0]; + } + + private static Elevations? ClipBySlab(ModelGeometry geometry, ElementLocation element, + ReadOnlySpan slab, ReadOnlySpan settings, (double X0, double Y0, double X1, double Y1) footprint, + Elevations bounds, double lowerMax, double upperMin, out Guid[]? beamJunctions, uint? wallPriority = null, + (Guid Wall, Guid Slab, Guid Junction)? cutter = null, bool requireContiguousEnd = false, + bool allowSharedBeamCoverage = false) + { + beamJunctions = null; + var location = ReadElementLocation(slab, "Slab", 0); + if (!SameIntersectionGroup(geometry, element.LayerIndex, location.LayerIndex) || + geometry.StoryElevation(element.HomeStoryIndex) is not { } home || + geometry.StoryElevation(location.HomeStoryIndex) is not { } slabStory || + settings.Length < 431 || ReadElevations(slab, "Slab") is not { } slabBounds) + return null; + int structure = BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]); + if (structure != 1 && (structure != 2 || wallPriority is null || settings[8] is not (0 or 3))) return null; + + var polygon = settings[270..]; + if (requireContiguousEnd && (ReadOutlineBounds(ReadSlabOutline(settings)) is null || + !HasVerticalSlabEdges(polygon[(int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..])..], + (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]) - + (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..])))) return null; + ReadOnlySpan rectangle = [2, 0, 2, 1, 247, 0, 0, 0, 1, 31, 0]; + var slabPlan = polygon.StartsWith(rectangle) ? ReadRectangularPlan(polygon) : null; + if (slabPlan is null) + { + if (ReadSlabPlanEnvelope(settings) is not { } envelope || + !SlabPolygonContainsFootprint(polygon, footprint, allowBoundary: structure == 2)) + return null; + slabPlan = envelope; + } + var slabFootprint = slabPlan.Value; + var (x0, y0, x1, y1) = slabFootprint; + + double low = slabBounds.Bottom + slabStory - home, high = slabBounds.Top + slabStory - home; + if (!(high > low)) return null; + if (high <= bounds.Bottom || low >= bounds.Top || + footprint.X0 >= x1 || footprint.X1 <= x0 || footprint.Y0 >= y1 || footprint.Y1 <= y0) + return bounds; + bool covers = x0 < footprint.X0 && y0 < footprint.Y0 && x1 > footprint.X1 && y1 > footprint.Y1; + bool leavesCorner = x0 > footprint.X0 || y0 > footprint.Y0 || x1 < footprint.X1 || y1 < footprint.Y1; + if (structure == 2 && wallPriority is { } priority) + { + if (geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])) is not { } skins) + return null; + double skinTop = high, cutBottom = double.PositiveInfinity, cutTop = double.NegativeInfinity; + foreach (var skin in skins) + { + if (!(skin.Thickness > 0 && double.IsFinite(skin.Thickness))) return null; + double skinBottom = skinTop - skin.Thickness; + if (skin.Priority >= priority && skinTop > bounds.Bottom + JunctionTolerance && + skinBottom < bounds.Top - JunctionTolerance) + { + // shortcut: disjoint cutting bands may leave more than one wall piece. + if (double.IsFinite(cutBottom) && cutBottom > skinTop + JunctionTolerance) + return null; + cutBottom = skinBottom; + cutTop = Math.Max(cutTop, skinTop); + } + skinTop = skinBottom; + } + if (Math.Abs(skinTop - low) > JunctionTolerance) return null; + if (cutBottom > cutTop) return bounds; + if (footprint.X0 < x0 - JunctionTolerance || footprint.Y0 < y0 - JunctionTolerance || + footprint.X1 > x1 + JunctionTolerance || footprint.Y1 > y1 + JunctionTolerance) + return leavesCorner ? bounds : null; + bool cutsBottom = low <= bounds.Bottom + JunctionTolerance && high < bounds.Top - JunctionTolerance; + bool cutsTop = high >= bounds.Top - JunctionTolerance && low > bounds.Bottom + JunctionTolerance; + if (!cutsBottom && !cutsTop) + return low > bounds.Bottom + JunctionTolerance && high < bounds.Top - JunctionTolerance ? bounds : null; + if (cutter is not { } joined) return null; + if (requireContiguousEnd && (cutsBottom ? cutBottom > bounds.Bottom + JunctionTolerance : cutTop < bounds.Top - JunctionTolerance)) + return null; + var band = new Elevations(cutBottom, cutTop); + List<(Guid Memo, Guid Junction)>? beams = null; + if (!HasSupportedSlabContacts(slab, SlabWallRelation, joined.Junction, + (key, id) => key == SlabWallRelation && IsSameWallSlabPair(geometry, joined.Wall, joined.Slab, id) || + SlabContactKeepsCuttingBand(geometry, joined.Slab, key, id, priority, home, footprint, band) || + key == SlabBeamRelation && + (allowSharedBeamCoverage && SharedBeamPreservesSlabCoverage(geometry, joined.Wall, joined.Slab, id, + element, home, priority, footprint) || + !requireContiguousEnd && CollectBeamForSlabCut(geometry, joined.Wall, joined.Slab, id, + element, home, band, bounds, cutsBottom, priority, beams ??= [])), + acceptsOperatorTarget: (target, operation) => IsSlabOperatorTarget(geometry, target, joined.Slab, operation))) + return null; + var cut = cutsBottom ? CheckedElevations(cutTop, bounds.Top) : CheckedElevations(bounds.Bottom, cutBottom); + if (beams is null || cut is not { } remainder) return cut; + if (ClipByBeamUnion(geometry, beams, BeamWallRelation, element, home, footprint, remainder, + remainder.Bottom, remainder.Top, joinedSlabWall: true) is not { } combined || + (cutsBottom ? combined.Bottom <= remainder.Bottom || combined.Top != remainder.Top : + combined.Top >= remainder.Top || combined.Bottom != remainder.Bottom)) + return null; + beamJunctions = beams.Select(b => b.Junction).ToArray(); + return combined; + } + if (high < upperMin && low <= bounds.Bottom) + { + if (leavesCorner && lowerMax == bounds.Bottom) return bounds; + if (covers && high >= lowerMax) return CheckedElevations(high, bounds.Top); + } + if (low > lowerMax && high >= bounds.Top) + { + if (leavesCorner && upperMin == bounds.Top) return bounds; + if (covers && low <= upperMin) return CheckedElevations(bounds.Bottom, low); + } + return low > lowerMax && high < upperMin ? bounds : null; + } + + private static bool IsSameWallSlabPair(ModelGeometry geometry, Guid wall, Guid slab, Guid id) => + geometry.Read(id, WallSlabJunctionClass) is { } contact && + ReadSingleRelation(contact, WallSlabRelation, requireSection: true) == wall && + ReadSingleRelation(contact, SlabWallRelation, requireSection: true) == slab && + geometry.Read(wall, WallClass) is { } body && HasGeometryRelation(body, WallSlabRelation, id); + + private static byte[]? ReadWallSlabContact(ModelGeometry geometry, Guid wall, Guid junction, out Guid slab) + { + slab = Guid.Empty; + if (geometry.Read(junction, WallSlabJunctionClass) is not { } contact || + ReadSingleRelation(contact, WallSlabRelation, requireSection: true) != wall) + return null; + slab = ReadSingleRelation(contact, SlabWallRelation, requireSection: true); + return geometry.Read(slab, SlabClass) is { } body && HasGeometryRelation(body, SlabWallRelation, junction) ? body : null; + } + + private static bool WallKeepsItsPlanes(ModelGeometry geometry, Guid wallId, Guid junctionId, Guid key, uint priority, + ElementLocation location, Elevations bounds, WallStrip? wall, bool basic, uint? slabCutPriority, + List blocked, out Elevations newBounds, out WallCut cut, bool trackPartialBeamCuts = false) + { + newBounds = bounds; + cut = new WallCut(junctionId); + if (key == WallColumnRelation) + return ColumnLeavesWallSection(geometry, wallId, junctionId, priority, wall, blocked); + if (key == WallBeamRelation) + { + var contact = geometry.Read(junctionId, WallBeamJunctionClass); + if (contact is null || ReadSingleRelation(contact, WallBeamRelation, requireSection: true) != wallId) return false; + Guid beamId = ReadSingleRelation(contact, BeamWallRelation, requireSection: true); + if (geometry.Read(beamId, BeamMemoClass) is not { } beam || !HasGeometryRelation(beam, BeamWallRelation, junctionId)) return false; + var hatch = ReadBeamHatch(geometry, beamId, beam); + if (hatch.IsEmpty || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } beamPriority) + return false; + if (beamPriority < priority) return true; + if (!trackPartialBeamCuts && wall is { } target && + geometry.StoryElevation(location.HomeStoryIndex) is { } home && + geometry.Attributes.LayerGroup.GetValueOrDefault(location.LayerIndex.GetValueOrDefault()) is > 0 && + basic && (ClipByBeamUnion(geometry, [(beamId, junctionId)], BeamWallRelation, location, home, target.Footprint, + bounds, bounds.Bottom, bounds.Top) ?? + ClipByBeam(geometry, beamId, junctionId, BeamWallRelation, location, home, target.Footprint, + bounds, bounds.Bottom, bounds.Top)) is { } clipped) + { + newBounds = clipped; + return true; + } + return BeamLeavesWallSection(geometry, beamId, beam, hatch, location, bounds, wall, blocked); + } + if (key == WallSlabRelation) + { + if (ReadWallSlabContact(geometry, wallId, junctionId, out Guid slabId) is not { } slab) return false; + var record = slab.AsSpan(FindClassFrame(slab, SlabClass)); + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (ReadSlabPriority(settings, geometry.Attributes) is not { } slabPriority) return false; + if (slabPriority < priority || + SlabKeepsPlanes(geometry, record, settings, location, priority, bounds.Bottom, bounds.Top, bounds, checkSkins: false)) + return true; + if (wall is not { } strip) return false; + bool composite = BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) == 2; + if (composite && (basic ? priority : slabCutPriority) is { } threshold && ReadJoinedWallStrip(geometry, wallId, strip, location) is { } joined && + ClipBySlab(geometry, location, record, settings, joined.Footprint, bounds, bounds.Bottom, bounds.Top, + out Guid[]? beamJunctions, threshold, (wallId, slabId, junctionId), + requireContiguousEnd: !basic || settings[8] == 3) is { } compositeCut && + (joined == strip || compositeCut != bounds)) + { + newBounds = compositeCut; + cut = new WallCut(junctionId, CoversWallJoins: true, beamJunctions); + return true; + } + if (!composite && basic && HasSupportedSlabContacts(record, SlabWallRelation, junctionId) && + ClipBySlab(geometry, location, record, settings, strip.Footprint, bounds, bounds.Bottom, bounds.Top, out _) is { } clipped) + { + newBounds = clipped; + return true; + } + if (ReadSlabPlanEnvelope(settings) is not { } plan) return false; + if (ReadWallSlabPlan(geometry, record, settings, out var world) is { } rings) + { + var height = geometry.StoryElevation(location.HomeStoryIndex) is { } home + ? CheckedElevations(world.Bottom - home, world.Top - home) : null; + AddSlabBlockedInterval(strip, rings, height, blocked); + } + else + AddWallBlockedInterval(strip, plan, blocked, hasVerifiedExtent: false); + return true; + } + + if (geometry.Read(junctionId, WallWallJunctionClass) is not { } joint || + ReadWallJunctionPeers(joint, wallId, key) is not { } peers) return false; + foreach (var (relation, owner) in peers) + { + if (geometry.Read(owner, WallClass) is not { } neighbor || + !HasGeometryRelation(neighbor, relation, junctionId) || + ReadWallPriority(geometry, owner, neighbor) is not { } neighborPriority) + return false; + if (neighborPriority < priority) continue; + var height = ReadNeighborWallHeight(geometry, neighbor, location); + if (height is { } range && MissesEndFaces(range.Bottom, range.Top, bounds, bounds.Bottom, bounds.Top)) continue; + var record = neighbor.AsSpan(FindClassFrame(neighbor, WallClass)); + var settings = AfterCountedString(record, 197); + var contour = ReadWallContour(geometry, record, owner); + (double X0, double Y0, double X1, double Y1)? inline = null; + if (contour is null && HasEmptyWallPlanCache(settings)) ReadWallReferencePlan(settings, out inline); + if (wall is not { } ownStrip) return false; + if (ReadWallStrip(settings, contour, inline) is not { } otherStrip) + { + if (ReadWallReferencePlan(settings, out _) is not { } plan || + ReadWallJunctionStation(geometry, joint, ownStrip) is not { } station || + CrossingWallInterval(ownStrip, plan, station) is not { } interval) + return false; + blocked.Add(new(interval, height)); + continue; + } + if (ownStrip.AlongX != otherStrip.AlongX) + { + blocked.Add(new((otherStrip.AcrossMin, otherStrip.AcrossMax), height)); + } + else if (ownStrip.AcrossMin < otherStrip.AcrossMax && ownStrip.AcrossMax > otherStrip.AcrossMin && + !AreCollinearWallEnds(ownStrip, otherStrip)) + { + if (ReadWallJunctionStation(geometry, joint, ownStrip, WallCapPlanClearance) is { } station && + WallButtAtStation(ownStrip, otherStrip, station)) continue; + if (!ownStrip.HasContour || !otherStrip.HasContour || ownStrip.Line != otherStrip.Line || + !HasOnlyCollinearWallContacts(geometry, record, wallId, owner, ownStrip, otherStrip)) + { + // The verified vertical range can exclude a cut at one end even when the plan is unresolved. + if (height is null || ReadSavedWallBox(settings) is null || settings[184] != 0) return false; + blocked.Add(new((ownStrip.Start, ownStrip.End), height)); + } + else + { + blocked.Add(new((otherStrip.Start, otherStrip.End), height)); + } + } + } + return true; + } + + private static bool ColumnLeavesWallSection(ModelGeometry geometry, Guid wall, Guid junction, uint priority, WallStrip? strip, + List blocked) + { + if (geometry.Read(junction, WallColumnJunctionClass) is not { } contact || + ReadSingleRelation(contact, WallColumnRelation, requireSection: true) != wall) + return false; + Guid memoId = ReadSingleRelation(contact, ColumnWallRelation, requireSection: true); + var hatch = ReadColumnContactSection(geometry, memoId, ColumnWallRelation, junction, out var column); + if (hatch.IsEmpty || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } columnPriority) + return false; + if (columnPriority < priority) return true; + if (strip is not { } s || ReadColumnFootprint(column, hatch) is not { } plan) return false; + AddWallBlockedInterval(s, plan, blocked); + return true; + } + + private static ReadOnlySpan ReadColumnContactSection(ModelGeometry geometry, Guid memoId, Guid relation, + Guid junction, out ReadOnlySpan column, bool includeCircular = false) + { + column = default; + if (geometry.Read(memoId, ColumnMemoClass) is not { } memo || + !HasGeometryRelation(memo, relation, junction)) return default; + Guid owner = ReadSingleRelation(memo, ColumnMemoRelation, requireSection: true); + if (ReadColumnSection(memo, owner, out _) is not { } sectionId || + geometry.Read(owner, ColumnClass) is not { } body) return default; + column = body.AsSpan(FindClassFrame(body, ColumnClass)); + if (column.Length < 735 || ReadColumnPrismMemo(column, owner, geometry) != memoId) return default; + var section = geometry.Read(sectionId, RectangularSectionClass); + if (section is null && includeCircular && geometry.Read(sectionId, CircularColumnSectionClass) is { } circular && + ReadSingleRelation(circular, SectionProfileRelation, requireSection: true) == memoId && + ReadCircularColumnSection(circular, out _) is not null) + return ReadSectionHatch(circular, 141, 482); + return section is null ? ReadComplexSectionHatch(geometry, memoId, sectionId) : + ReadSingleRelation(section, SectionProfileRelation, requireSection: true) == memoId ? ReadSectionHatch(section, 141, 482) : default; + } + + private static (double X0, double Y0, double X1, double Y1)? ReadColumnFootprint( + ReadOnlySpan column, ReadOnlySpan hatch, double? planAngle = null) + { + if (!column.Slice(304, ColumnEndPlaneFrame.Length).SequenceEqual(ColumnEndPlaneFrame) || + BinaryPrimitives.ReadUInt16LittleEndian(column[368..]) != 1 || + !IsCorner(column[370..], ReadDouble(column, 312), ReadDouble(column, 320))) + return null; + var vertices = StraightSectionVertices(hatch); + var settings = AfterCountedString(column, 735); + if (vertices.IsEmpty || settings.Length < 36) return null; + double angle = planAngle ?? ReadDouble(settings, 28), sin = Math.Sin(angle), cos = Math.Cos(angle); + double x0 = double.PositiveInfinity, y0 = double.PositiveInfinity, x1 = double.NegativeInfinity, y1 = double.NegativeInfinity; + for (int i = 0; i < vertices.Length; i += 16) + { + double u = ReadDouble(vertices, i), v = ReadDouble(vertices, i + 8); + double x = ReadDouble(column, 312) + cos * u - sin * v; + double y = ReadDouble(column, 320) + sin * u + cos * v; + x0 = Math.Min(x0, x); + y0 = Math.Min(y0, y); + x1 = Math.Max(x1, x); + y1 = Math.Max(y1, y); + } + return double.IsFinite(x0) && double.IsFinite(y0) && double.IsFinite(x1) && double.IsFinite(y1) ? (x0, y0, x1, y1) : null; + } + + private static void AddWallBlockedInterval(WallStrip strip, (double X0, double Y0, double X1, double Y1) plan, + List blocked, bool hasVerifiedExtent = true) + { + double min = strip.AlongX ? plan.Y0 : plan.X0, max = strip.AlongX ? plan.Y1 : plan.X1; + if (min < strip.AcrossMax && max > strip.AcrossMin) + blocked.Add(new(strip.AlongX ? (plan.X0, plan.X1) : (plan.Y0, plan.Y1), HasVerifiedExtent: hasVerifiedExtent)); + } + + private static void AddSlabBlockedInterval(WallStrip strip, IReadOnlyList> rings, + Elevations? height, List blocked) + { + const double clearance = 1e-7; + var outline = rings[0]; + double start = double.PositiveInfinity, end = double.NegativeInfinity; + // The axial extrema inside the wall's transverse band lie on clipped contour edges. + var previous = outline[^1]; + foreach (var point in outline) + { + double across0 = strip.AlongX ? previous.Y : previous.X, across1 = strip.AlongX ? point.Y : point.X; + double along0 = strip.AlongX ? previous.X : previous.Y, along1 = strip.AlongX ? point.X : point.Y; + double low = 0, high = 1; + if (ClipSegment(across0, across1, strip.AcrossMin - clearance, strip.AcrossMax + clearance, ref low, ref high)) + { + double a = along0 + (along1 - along0) * low, b = along0 + (along1 - along0) * high; + start = Math.Min(start, Math.Min(a, b)); + end = Math.Max(end, Math.Max(a, b)); + } + previous = point; + } + // Prove clearance at the same coordinate precision used to validate the model geometry. + if (start <= end) blocked.Add(new((start - clearance, end + clearance), height, rings)); + } + + private static bool AreCollinearWallEnds(WallStrip a, WallStrip b) => + Math.Abs(a.Line - b.Line) <= JunctionTolerance && + (Math.Abs(a.Start - b.End) <= JunctionTolerance || Math.Abs(a.End - b.Start) <= JunctionTolerance); + + private static bool HasOnlyCollinearWallContacts(ModelGeometry geometry, ReadOnlySpan record, Guid wall, Guid neighbor, + WallStrip own, WallStrip other) + { + int start = FindRelationshipSection(record, record.Length); + if (start < 0) return false; + var data = record[start..]; + 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 && (UnjoinedWallChildRelations.Contains(key) || key == LinkedElementSettingsRelation || key == PlanContourRelation) || + tag == 0x12 && (key == DatabaseElementList || UnjoinedWallOwnerRelations.Contains(key) || + key == WallTopStoryRelation || key == AttributeOwnerRelation)) + continue; + if (tag is not (1 or 0x11) || (key != FirstWallEndRelation && key != SecondWallEndRelation)) return false; + 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 jointId = new Guid(ids.Slice(i, 16)); + if (geometry.Read(jointId, WallWallJunctionClass) is not { } joint || + ReadSingleRelation(joint, key, requireSection: true) != neighbor || + ReadSingleRelation(joint, key == FirstWallEndRelation ? SecondWallEndRelation : FirstWallEndRelation, + requireSection: true) != wall) + return false; + Guid pointId = ReadSingleRelation(joint, WallJunctionPointRelation, requireSection: true); + if (geometry.Read(pointId, WallJunctionPointClass) is not { Length: >= 62 } point) return false; + double along = ReadDouble(point, own.AlongX ? 46 : 54), across = ReadDouble(point, own.AlongX ? 54 : 46); + if (across != own.Line || !(along >= Math.Max(own.Start, other.Start) && along <= Math.Min(own.End, other.End))) + return false; + } + } + return data is [0]; + } + + private readonly record struct WallStrip(bool AlongX, double Start, double End, double AcrossMin, double AcrossMax, + double Line, bool HasContour) + { + public (double X0, double Y0, double X1, double Y1) Footprint => + AlongX ? (Start, AcrossMin, End, AcrossMax) : (AcrossMin, Start, AcrossMax, End); + } + + private static (double X0, double Y0, double X1, double Y1)? ReadSlabPlanEnvelope(ReadOnlySpan settings) + { + if (settings.Length < 341) return null; + var polygon = settings[270..]; + if (!polygon.StartsWith(SlabOutlineFrame) || !polygon[8..].StartsWith(new byte[] { 1, 31, 0 }) || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0) return null; + uint size = BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..]); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]); + uint contours = BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]); + if (size > polygon.Length || size < 71 || count < 4 || count > (size - 71) / 16 || + contours == 0 || contours > (size - 71 - count * 16) / 4) return null; + double x0 = ReadDouble(polygon, 11), y0 = ReadDouble(polygon, 19); + double x1 = ReadDouble(polygon, 27), y1 = ReadDouble(polygon, 35); + if (!(double.IsFinite(x0) && double.IsFinite(y0) && double.IsFinite(x1) && double.IsFinite(y1) && x0 < x1 && y0 < y1)) + return null; + for (int i = 0; i < count; i++) + { + double x = ReadDouble(polygon, 71 + i * 16), y = ReadDouble(polygon, 79 + i * 16); + if (!(x >= x0 && x <= x1 && y >= y0 && y <= y1)) return null; + } + return (x0, y0, x1, y1); + } + + private static bool SlabPolygonContainsFootprint(ReadOnlySpan polygon, + (double X0, double Y0, double X1, double Y1) footprint, bool allowBoundary) + { + if (allowBoundary) + { + footprint = (footprint.X0 + JunctionTolerance, footprint.Y0 + JunctionTolerance, + footprint.X1 - JunctionTolerance, footprint.Y1 - JunctionTolerance); + if (footprint.X0 >= footprint.X1 || footprint.Y0 >= footprint.Y1) return false; + } + int count = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]); + int contours = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]); + int offset = 71 + count * 16; + if (polygon.Length - offset < 4 + contours * 4 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[offset..]) != 0) + return false; + double x = footprint.X0 + (footprint.X1 - footprint.X0) / 2; + double y = footprint.Y0 + (footprint.Y1 - footprint.Y0) / 2; + bool inside = false; + int start = 0; + for (int c = 1; c <= contours; c++) + { + uint end = BinaryPrimitives.ReadUInt32LittleEndian(polygon[(offset + c * 4)..]); + if (end > count || end < start + 4 || + !polygon.Slice(71 + start * 16, 16).SequenceEqual(polygon.Slice(71 + ((int)end - 1) * 16, 16))) + return false; + for (int i = start + 1; i < end; i++) + { + var edge = polygon[(71 + (i - 1) * 16)..]; + double ax = ReadDouble(edge, 0), ay = ReadDouble(edge, 8), bx = ReadDouble(edge, 16), by = ReadDouble(edge, 24); + double lo = 0, hi = 1; + if (ClipSegment(ax, bx, footprint.X0, footprint.X1, ref lo, ref hi) && + ClipSegment(ay, by, footprint.Y0, footprint.Y1, ref lo, ref hi)) + return false; + if ((ay > y) != (by > y) && x < ax + (y - ay) / (by - ay) * (bx - ax)) + inside = !inside; + } + start = (int)end; + } + return start == count && inside; + } + + private static bool ClipSegment(double a, double b, double min, double max, ref double lo, ref double hi) + { + if (a == b) return a >= min && a <= max; + double t0 = (min - a) / (b - a), t1 = (max - a) / (b - a); + lo = Math.Max(lo, Math.Min(t0, t1)); + hi = Math.Min(hi, Math.Max(t0, t1)); + return lo <= hi; + } + + private static WallStrip? ReadWallStrip(ReadOnlySpan settings, (double X0, double Y0, double X1, double Y1)? footprint, + (double X0, double Y0, double X1, double Y1)? inline = null) + { + if (settings.Length < 229 || settings.Length < 563 && footprint is null && inline is null || settings[184] != 0 || + BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) is not (1 or 2)) + return null; + double x = ReadDouble(settings, 0), y = ReadDouble(settings, 8); + double x1 = ReadDouble(settings, 16), y1 = ReadDouble(settings, 24); + bool alongX = Math.Abs(y - y1) <= JunctionTolerance; + if (!double.IsFinite(x) || !double.IsFinite(x1) || !double.IsFinite(y) || !double.IsFinite(y1) || + (Math.Abs(x - x1) <= JunctionTolerance) == alongX) return null; + double thickness = ReadDouble(settings, 77); + if (!double.IsFinite(thickness) || !(thickness > 0) || thickness != ReadDouble(settings, 85)) return null; + + double a = alongX ? x : y, b = alongX ? x1 : y1, line = alongX ? y : x; + double start = Math.Min(a, b), end = Math.Max(a, b); + var (x0, y0, xMax, yMax) = footprint ?? inline ?? + (ReadDouble(settings, 515), ReadDouble(settings, 523), ReadDouble(settings, 531), ReadDouble(settings, 539)); + double min = alongX ? y0 : x0, max = alongX ? yMax : xMax; + if (!(Math.Abs((alongX ? x0 : y0) - start) <= JunctionTolerance && + Math.Abs((alongX ? xMax : yMax) - end) <= JunctionTolerance && + Math.Abs(max - min - thickness) <= JunctionTolerance && + line >= min - JunctionTolerance && line <= max + JunctionTolerance)) + return null; + return new WallStrip(alongX, start, end, min, max, line, footprint.HasValue); + } + + private static (double X0, double Y0, double X1, double Y1)? ReadWallContour(ModelGeometry geometry, + ReadOnlySpan wall, Guid owner) + { + Guid id = ReadSingleRelation(wall, PlanContourRelation, 0x11, requireSection: true); + if (geometry.Read(id, WallPlanContourClass) is not { Length: >= 206 } contour || + ReadSingleRelation(contour, PlanContourRelation, requireSection: true) != owner) return null; + var polygon = contour.AsSpan(44); + ReadOnlySpan rectangle = [0, 0, 2, 1, 247, 0, 0, 0, 0, 31, 0]; + return polygon.StartsWith(rectangle) ? ReadRectangularPlan(polygon) : null; + } + + private static (double X0, double Y0, double X1, double Y1)? ReadRectangularPlan(ReadOnlySpan polygon) + { + if (polygon.Length < 159 || BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]) != 5 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0 || BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]) != 1 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[155..]) != 5 || !polygon.Slice(71, 16).SequenceEqual(polygon.Slice(135, 16))) + return null; + double x0 = ReadDouble(polygon, 11), y0 = ReadDouble(polygon, 19), x1 = ReadDouble(polygon, 27), y1 = ReadDouble(polygon, 35); + if (!(double.IsFinite(x0) && double.IsFinite(y0) && double.IsFinite(x1) && double.IsFinite(y1) && x0 < x1 && y0 < y1)) + return null; + uint corners = 0; + for (int i = 71; i < 135; i += 16) + { + double x = ReadDouble(polygon, i), y = ReadDouble(polygon, i + 8); + if ((x != x0 && x != x1) || (y != y0 && y != y1) || + ReadDouble(polygon, i + 16) != x && ReadDouble(polygon, i + 24) != y) return null; + corners |= 1u << ((x == x0 ? 0 : 1) + (y == y0 ? 0 : 2)); + } + return corners == 15 ? (x0, y0, x1, y1) : null; + } + + private static Elevations? ReadNeighborWallHeight(ModelGeometry geometry, byte[] neighbor, ElementLocation target) + { + var record = neighbor.AsSpan(FindClassFrame(neighbor, WallClass)); + var location = ReadElementLocation(record, "Wall", 0); + var settings = AfterCountedString(record, 197); + if (settings.Length < 563 || BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) != 1 || + geometry.StoryElevation(location.HomeStoryIndex) is not { } story || + geometry.StoryElevation(target.HomeStoryIndex) is not { } home || + ReadWallReferencePlanes(settings, location, geometry) is not { } planes || + !(Math.Abs(ReadDouble(settings, 547) - (planes.Bottom + story)) <= JunctionTolerance && + Math.Abs(ReadDouble(settings, 555) - (planes.Top + story)) <= JunctionTolerance)) + return null; + return CheckedElevations(planes.Bottom + story - home, planes.Top + story - home); + } +} diff --git a/src/PlaIO/Internal/ElementReader.LayoutRevisions.cs b/src/PlaIO/Internal/ElementReader.LayoutRevisions.cs new file mode 100644 index 0000000..9b8727e --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.LayoutRevisions.cs @@ -0,0 +1,205 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid LayoutRevisionStateClass = new("169571f5-0665-4fec-8070-5e14962eaf1a"); + private static readonly Guid LayoutRevisionOverrideClass = new("8535adec-7d22-4334-8dfa-d3318ff35d23"); + private static readonly Guid IssuedLayoutRevisionClass = new("2c2d6560-da21-4610-b3b8-fe05f4b5c431"); + private static readonly Guid LayoutTransmittalClass = new("ad6bafb9-a10c-4258-aad3-97f97ac5d1ae"); + private static readonly Guid LayoutRevisionStateLink = new("6c8ed16c-a969-4a25-9f40-1ab657dc6b50"); + private static readonly Guid LayoutRevisionOverrideLink = new("a0e2f86f-4496-4a59-bbbe-ef3a6f1267a9"); + private static readonly Guid IssuedLayoutRevisionLink = new("9d374292-829a-4553-a3e0-6631d9a0110c"); + private static readonly Guid IssuedTransmittalLink = new("3b14d41d-2596-4cb7-8767-21309d216a9c"); + private static readonly Guid OpenTransmittalLink = new("2421d43e-0a52-4d18-acfb-54e6262d9dbc"); + + private static void ResolveLayoutRevisions(PlaDocument document, IReadOnlyList classes, + Dictionary navigatorRecords, List items) + { + var kinds = classes.Where(c => c.Guid == IssuedLayoutRevisionClass || c.Guid == LayoutTransmittalClass) + .ToDictionary(c => c.Number, c => c.Guid); + var records = kinds.Count == 0 ? new Dictionary() : ReadClassRecords(document, kinds); + var transmittals = new Dictionary Members)>(); + for (int i = 0; i < items.Count; i++) + { + var item = items[i]; + if (item.Type is not ("LayoutItem" or "MasterLayoutItem") || + ReadLayoutSettings(navigatorRecords, item.Guid, navigatorRecords[item.Guid]) is not { } settings) + continue; + var stateLink = ReadNavigatorLink(settings.Body, LayoutRevisionStateLink, 0x11); + if (stateLink.Length == 0) continue; + if (stateLink.Length != 1 || !navigatorRecords.TryGetValue(stateLink[0], out var state) || + RecordClass(state) != LayoutRevisionStateClass || + !ReadNavigatorLink(state, LayoutRevisionStateLink, 0x12).SequenceEqual([settings.Id])) + throw new InvalidDataException("A layout has a conflicting revision state."); + + var openLink = ReadNavigatorLink(state, OpenTransmittalLink, 0x12); + var stateFields = ReadRecordFields(state, 49, out var stateRelations); + if (!HasNavigatorEnvelope(state, 43) || + !state.AsSpan(39, 4).SequenceEqual(new byte[] { 1, 0, 1, 0 })) continue; + string numberingBase = ReadFramedText(ref stateFields); + if (ReadFramedText(ref stateFields).Length != 0 || !stateFields.IsEmpty || + !HasKnownRevisionStateLinks(stateRelations)) continue; + + var issuedLinks = ReadNavigatorLink(settings.Body, IssuedLayoutRevisionLink, 1, 0x11); + if (issuedLinks.Distinct().Count() != issuedLinks.Length) + throw new InvalidDataException("A layout has a repeated revision."); + var issued = new List(issuedLinks.Length); + foreach (Guid id in issuedLinks) + { + if (!records.TryGetValue(id, out var body) || body.Length < 46 || + RecordClass(body) != IssuedLayoutRevisionClass || + !ReadNavigatorLink(body, IssuedLayoutRevisionLink, 0x12).SequenceEqual([settings.Id])) + throw new InvalidDataException("An issued revision has a conflicting layout link."); + var fields = ReadRecordFields(body, 49, out _); + if (!HasNavigatorEnvelope(body, 43) || !body.AsSpan(39, 4).SequenceEqual(new byte[] { 2, 0, 1, 0 })) + throw new InvalidDataException("An issued layout revision has an invalid field frame."); + string revisionId = ReadFramedText(ref fields); + var transmittal = GetTransmittal(ReadNavigatorLink(body, IssuedTransmittalLink, 0x12), id, issued: true); + issued.Add(new PlaIssuedLayoutRevision(id, revisionId, transmittal)); + } + + PlaLayoutTransmittal? open = openLink.Length == 0 ? null : GetTransmittal(openLink, stateLink[0], issued: false); + string? current = open is null ? issued.Count == 0 ? "" : issued[^1].Id + : open.OverridesRevisionIds ? open.Id + : ResolveOpenRevisionId(ReadSavedRevisionOverride(navigatorRecords, stateLink[0], state) ?? numberingBase, issued); + items[i] = item with + { + Revision = new PlaLayoutRevision(current, open is null ? current : null, issued.Count != 0, open is not null) + { + IssuedRevisions = issued.AsReadOnly(), + OpenTransmittal = open, + }, + }; + } + + PlaLayoutTransmittal GetTransmittal(Guid[] link, Guid member, bool issued) + { + if (link.Length != 1) + throw new InvalidDataException("A layout revision has an invalid transmittal link."); + Guid id = link[0]; + if (!transmittals.TryGetValue(id, out var transmittal)) + { + if (!records.TryGetValue(id, out var body) || body.Length < 46 || RecordClass(body) != LayoutTransmittalClass) + throw new InvalidDataException("A layout revision references an invalid transmittal record."); + var value = ReadLayoutTransmittal(id, body); + bool closed = value.IssuedAtUtc.HasValue; + var members = ReadNavigatorLink(body, closed ? IssuedTransmittalLink : OpenTransmittalLink, 1, 0x11); + transmittal = (value, members.ToHashSet()); + transmittals.Add(id, transmittal); + } + if (transmittal.Value.IssuedAtUtc.HasValue != issued || !transmittal.Members.Contains(member)) + throw new InvalidDataException("A layout revision's transmittal does not confirm its status or membership."); + return transmittal.Value; + } + } + + private static bool HasKnownRevisionStateLinks(ReadOnlySpan relationships) + { + while (relationships.Length >= 17) + { + ReadRelationshipEntry(ref relationships, out byte tag, out Guid role); + if ((role, tag) == (LayoutRevisionOverrideLink, (byte)0x11) || + (role, tag) == (LayoutRevisionStateLink, (byte)0x12) || + (role, tag) == (OpenTransmittalLink, (byte)0x12)) continue; + return false; + } + CheckRelationshipEnd(relationships); + return true; + } + + private static string? ReadSavedRevisionOverride(Dictionary records, Guid stateId, byte[] state) + { + if (ReadNavigatorLink(state, LayoutRevisionOverrideLink, 0x11).Length == 0) return null; + var (_, record) = ReadLinkedNavigatorRecord(records, stateId, state, LayoutRevisionOverrideLink, + LayoutRevisionOverrideClass, 0x11, 0x12); + var fields = ReadRecordFields(record, 47, out _); + if (!HasNavigatorEnvelope(record, 41) || !record.AsSpan(39, 2).SequenceEqual(new byte[] { 1, 0 })) + throw new InvalidDataException("A saved layout revision override has an invalid field frame."); + string value = ReadFramedText(ref fields); + if (!fields.IsEmpty) throw new InvalidDataException("A saved layout revision override has unexpected fields."); + return value; + } + + private static string? ResolveOpenRevisionId(string numberingBase, IReadOnlyList issued) + { + if (numberingBase.Length == 0) return null; + if (!issued.Any(revision => revision.Id == numberingBase)) return numberingBase; + + bool numeric = char.IsAsciiDigit(numberingBase[^1]); + int start = RevisionSequenceStart(numberingBase, numeric); + if (start == numberingBase.Length) return null; + + // After the saved ID is issued, numbering resumes after the highest ID in its sequence. + string highest = numberingBase; + foreach (var revision in issued) + { + string id = revision.Id; + if (id.Length <= start || RevisionSequenceStart(id, numeric) != start || + !id.AsSpan(0, start).SequenceEqual(numberingBase.AsSpan(0, start))) continue; + var a = id.AsSpan(start); + var b = highest.AsSpan(start); + if (numeric) + { + a = a.TrimStart('0'); + b = b.TrimStart('0'); + } + if (a.Length > b.Length || a.Length == b.Length && a.SequenceCompareTo(b) > 0) + highest = id; + } + return AdvanceRevisionId(highest); + } + + private static int RevisionSequenceStart(string id, bool numeric) + { + int start = id.Length; + if (numeric) + { + while (start > 0 && char.IsAsciiDigit(id[start - 1])) start--; + } + else if (start > 0 && id[^1] is >= 'A' and <= 'Z') + { + start--; + while (start > 0 && id[start - 1] == 'Z') start--; + } + return start; + } + + private static string AdvanceRevisionId(string id) + { + char last = id[^1]; + if (last is >= 'A' and < 'Z') return string.Concat(id.AsSpan(0, id.Length - 1), ((char)(last + 1)).ToString()); + if (last == 'Z') return id + "A"; + + int carry = id.Length - 1; + while (carry >= 0 && id[carry] == '9') carry--; + string zeroes = new('0', id.Length - 1 - carry); + return carry >= 0 && char.IsAsciiDigit(id[carry]) + ? string.Concat(id.AsSpan(0, carry), ((char)(id[carry] + 1)).ToString(), zeroes) + : string.Concat(id.AsSpan(0, carry + 1), "1", zeroes); + } + + private static PlaLayoutTransmittal ReadLayoutTransmittal(Guid id, byte[] body) + { + var fields = ReadRecordFields(body, 51, out _); + if (!HasNavigatorEnvelope(body, 45) || !body.AsSpan(39, 2).SequenceEqual(new byte[] { 1, 2 }) || + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(41)) != fields.Length + 6) + throw new InvalidDataException("A layout transmittal has an invalid field frame."); + string number = ReadFramedText(ref fields); + string name = ReadFramedText(ref fields); + if (fields.Length < 4) throw new InvalidDataException("A layout transmittal has a truncated timestamp."); + uint seconds = BinaryPrimitives.ReadUInt32LittleEndian(fields); + fields = fields[4..]; + string user = ReadFramedText(ref fields); + if (fields.Length != 13 || fields[8] > 1 || fields[^1] > 1) + throw new InvalidDataException("A layout transmittal has an invalid status frame."); + bool closed = fields[^1] == 1; + return new PlaLayoutTransmittal(id, number, name, closed ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null, + closed ? user : null) + { + OverridesRevisionIds = fields[8] == 1, + }; + } +} diff --git a/src/PlaIO/Internal/ElementReader.Layouts.cs b/src/PlaIO/Internal/ElementReader.Layouts.cs new file mode 100644 index 0000000..fb56bb8 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Layouts.cs @@ -0,0 +1,362 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid NavigatorDirectoryLayout = new("06957baa-872a-40ea-b18b-2d4d1bcef8f0"); + private static readonly Guid NavigatorRootClass = new("2bbbecb3-0ecd-4228-897b-cc6ffb35d37f"); + private static readonly Guid LayoutBookClass = new("983b7466-b012-43db-a637-bc6f93076c34"); + private static readonly Guid LayoutSubsetClass = new("cf1797c1-69ec-4648-b5c5-57f898ab530b"); + private static readonly Guid LayoutItemClass = new("973bdcc9-e2f6-464f-85fb-833be20f5de5"); + private static readonly Guid MasterFolderClass = new("6253793e-0a1f-4691-811b-4900cba006d1"); + private static readonly Guid MasterLayoutClass = new("9d76eef2-a7cf-43b2-b09b-6d83d9607baa"); + private static readonly Guid LayoutDrawingClass = new("10440840-10b2-4cab-99d7-54f8af93da44"); + + private static readonly Guid LayoutSourceClass = new("af0e45a5-fb37-4d8e-9132-d739c85efb91"); + private static readonly Guid MasterSourceClass = new("2092ceaa-500d-4520-b62a-63403a643735"); + private static readonly Guid DrawingSourceClass = new("31f5f16f-4b9e-41a8-9a32-f006ed168560"); + private static readonly Guid LayoutMetadataClass = new("39b16f73-c419-4640-8ceb-682d7a0e8ff9"); + private static readonly Guid MasterMetadataClass = new("93de1151-dc0a-4fe6-b394-54d7430988b5"); + private static readonly Guid DrawingMetadataClass = new("8c3b244d-a5a4-45d6-b917-ce005c1c6161"); + private static readonly Guid LayoutSettingsClass = new("f080c777-1d2e-40df-91b4-c6169b14e516"); + private static readonly Guid LayoutDatabaseClass = new("32acaf3c-26b8-4593-926c-f81a205550ba"); + private static readonly Guid MasterDatabaseClass = new("041e23dd-9fca-4a53-9633-8865f82a3a40"); + private static readonly Guid DrawingElementClass = new("2dbe8c52-93b3-46b5-a0a9-2492c45c2ab3"); + private static readonly Guid DrawingViewMemoClass = new("ba3407e3-8afd-4eb7-9f53-f197ff35c20e"); + private static readonly Guid SavedViewClass = new("89967df1-d45d-4078-9278-9b637f992e7b"); + private static readonly Guid SavedIndependentViewClass = new("b853520a-b01f-40b4-ad9c-8e855cb09a72"); + + private static readonly Guid NavigatorTreeLink = new("33788fbb-8e6c-4a8d-a816-705f8d1ce5c6"); + private static readonly Guid NavigatorSettingLink = new("22a736de-07dc-49d4-9ab1-df90d9118b23"); + private static readonly Guid NavigatorSourceLink = new("fe91e636-9138-4f5d-9d85-b5d11ed2387b"); + private static readonly Guid NavigatorMetadataLink = new("6cbbd184-9a9c-4907-8363-ee7dd8141394"); + private static readonly Guid LayoutSourceLink = new("90515593-8e6f-4ce1-9c2c-5746fc32716a"); + private static readonly Guid MasterSourceLink = new("e03210e5-e70a-45da-8184-64835d8aeb6a"); + private static readonly Guid LayoutDatabaseLink = new("b1ddeca8-d51c-41c2-9a1a-77a1bcb3a5bb"); + private static readonly Guid MasterDatabaseLink = new("4b952067-803c-4aee-bc0d-8d1bbd107c6f"); + private static readonly Guid LayoutMasterLink = new("980d1d7e-00c4-4f38-a77b-92108e7b660b"); + private static readonly Guid DrawingDatabaseLink = new("daade85d-fe69-4343-8254-4655416e28f6"); + private static readonly Guid DatabaseDrawingLink = new("ac4d07f4-7e7c-4337-8bec-c82b034f4216"); + private static readonly Guid DrawingViewMemoLink = new("004ca348-04da-4f8b-bf94-22d0e313040b"); + private static readonly Guid DrawingViewLink = new("77201cab-66f6-4947-831d-c851ba54217d"); + private static readonly Guid NavigatorViewLink = new("bd38ee00-e866-43d5-a407-2437516d65d0"); + + internal static PlaLayoutBook? ReadLayoutBook(PlaDocument document, IReadOnlyList classes) + { + var records = ReadLayoutRecords(document, classes); + var roots = records.Where(r => RecordClass(r.Value) == LayoutBookClass).Take(2).ToArray(); + if (roots.Length == 0) return null; + if (roots.Length != 1) throw new InvalidDataException("The layout book has conflicting roots."); + var (root, rootBody) = roots[0]; + var parents = ReadNavigatorLink(rootBody, NavigatorTreeLink, 0x12); + if (parents.Length != 1 || !records.TryGetValue(parents[0], out var wrapper) || + RecordClass(wrapper) != NavigatorRootClass || + !ReadNavigatorLink(wrapper, NavigatorTreeLink, 1, 0x11).Contains(root)) + throw new InvalidDataException("The layout book has an invalid navigator root link."); + + var views = IndexLayoutViews(records); + var pending = new Stack<(Guid Item, Guid Parent, Guid? Database)>(); + var visited = new HashSet { root }; + var items = new List(); + QueueChildren(root, rootBody, null); + while (pending.TryPop(out var entry)) + { + if (!visited.Add(entry.Item) || !records.TryGetValue(entry.Item, out var body)) + throw new InvalidDataException("The layout book has a missing or repeated item."); + if (!ReadNavigatorLink(body, NavigatorTreeLink, 0x12).SequenceEqual([entry.Parent])) + throw new InvalidDataException("A layout book item has a conflicting parent link."); + var item = ReadLayoutBookItem(records, views, body, entry.Item, entry.Parent, entry.Database); + items.Add(item); + QueueChildren(entry.Item, body, item.DatabaseGuid); + } + ResolveMasterLayouts(records, items); + ResolveLayoutRevisions(document, classes, records, items); + return new PlaLayoutBook(root, items.AsReadOnly()); + + void QueueChildren(Guid parent, byte[] body, Guid? database) + { + var children = ReadNavigatorLink(body, NavigatorTreeLink, 1, 0x11); + for (int i = children.Length - 1; i >= 0; i--) pending.Push((children[i], parent, database)); + } + } + + private static PlaLayoutBookItem ReadLayoutBookItem(Dictionary records, Dictionary views, + byte[] body, Guid id, Guid parent, Guid? database) + { + Guid type = RecordClass(body); + if (type == MasterFolderClass) + return new PlaLayoutBookItem(id, parent, "MasterFolderItem", null, null, null, null, null); + if (type == LayoutSubsetClass) + { + var fields = ReadRecordFields(body, 56, out _); + if (!HasNavigatorEnvelope(body, 49) || !body.AsSpan(39, 6).SequenceEqual(new byte[] { 1, 0, 3, 0, 8, 1 })) + throw new InvalidDataException("A layout subset has an invalid name frame."); + string number = ReadFramedText(ref fields); + if (fields.IsEmpty || fields[0] > 1) throw new InvalidDataException("A layout subset's name is truncated."); + fields = fields[1..]; + return new PlaLayoutBookItem(id, parent, "SubsetItem", ReadFramedText(ref fields), number, null, null, null); + } + + var (label, sourceClass, metadataClass) = type == LayoutItemClass ? ("LayoutItem", LayoutSourceClass, LayoutMetadataClass) : + type == MasterLayoutClass ? ("MasterLayoutItem", MasterSourceClass, MasterMetadataClass) : + type == LayoutDrawingClass ? ("DrawingItem", DrawingSourceClass, DrawingMetadataClass) : + throw new InvalidDataException("The layout book contains an unsupported item class."); + var (sourceId, source) = ReadLinkedNavigatorRecord(records, id, body, NavigatorSourceLink, sourceClass, 0x12, 0x11); + var (metadataId, metadata) = ReadLinkedNavigatorRecord(records, sourceId, source, NavigatorMetadataLink, metadataClass, 0x12, 0x11); + int textOffset = type == LayoutDrawingClass ? 99 : 56; + var textFields = ReadRecordFields(metadata, textOffset, out _); + if (!HasNavigatorEnvelope(metadata, type == LayoutDrawingClass ? 53 : 49)) + throw new InvalidDataException("A layout book item's text frame is invalid."); + string first = ReadFramedText(ref textFields); + string second = ReadFramedText(ref textFields); + if (type == LayoutDrawingClass) + { + if (textFields.Length <= 40) throw new InvalidDataException("The drawing's source path is truncated."); + var pathField = textFields[40..]; + string path = ReadFramedText(ref pathField); + Guid? drawingSource = path.Length == 0 && pathField.Length >= 8 && + BinaryPrimitives.ReadUInt32LittleEndian(pathField[4..]) is 0x802C or 0x8030 or 0x8032 ? sourceId : + ReadDrawingView(records, views, database, metadataId, metadata); + return new PlaLayoutBookItem(id, parent, label, first, second, drawingSource, path, null); + } + if (type == MasterLayoutClass) + { + if (!ReadNavigatorLink(body, MasterSourceLink, 0x12).SequenceEqual([sourceId])) + throw new InvalidDataException("A master layout has a conflicting source link."); + return new PlaLayoutBookItem(id, parent, label, second, second, sourceId, null, + ReadMasterPaperSize(ReadLayoutSettings(records, id, body)?.Body)) + { + DatabaseGuid = ReadLayoutDatabase(records, metadataId, metadata, MasterDatabaseLink, MasterDatabaseClass) + }; + } + if (!ReadNavigatorLink(body, LayoutSourceLink, 0x12).SequenceEqual([sourceId]) || + !HasNavigatorEnvelope(body, 57) || !body.AsSpan(39, 2).SequenceEqual(new byte[] { 1, 1 })) + throw new InvalidDataException("A layout has an invalid number frame or source link."); + var numberField = ReadRecordFields(body, 64, out _); + return new PlaLayoutBookItem(id, parent, label, second, ReadFramedText(ref numberField), sourceId, null, null) + { + DatabaseGuid = ReadLayoutDatabase(records, metadataId, metadata, LayoutDatabaseLink, LayoutDatabaseClass) + }; + } + + private static Dictionary IndexLayoutViews(Dictionary records) + { + var result = new Dictionary(); + foreach (var (id, record) in records) + { + var type = RecordClass(record); + if (type != SavedViewClass && type != SavedIndependentViewClass) continue; + var target = ReadNavigatorLink(record, NavigatorViewLink, 0x12); + if (target.Length != 0 && !result.TryAdd(target[0], id)) result[target[0]] = null; + } + return result; + } + + private static Guid? ReadDrawingView(Dictionary records, Dictionary views, + Guid? databaseId, Guid metadataId, byte[] metadata) + { + if (databaseId is not { } database || !metadata.AsSpan(59, 3).SequenceEqual(new byte[] { 1, 6, 0 }) || + !ReadNavigatorLink(metadata, DrawingDatabaseLink, 0x12).SequenceEqual([database])) + return null; + var owner = records[database]; + var drawing = new Guid(metadata.AsSpan(62, 16)); + if (!records.TryGetValue(drawing, out var element) || RecordClass(element) != DrawingElementClass || + !ReadNavigatorLink(element, DatabaseDrawingLink, 0x12).SequenceEqual([database]) || + !ReadNavigatorLink(owner, DatabaseDrawingLink, 1, 0x11).Contains(drawing) || + !ReadNavigatorLink(owner, DrawingDatabaseLink, 1, 0x11).Contains(metadataId)) + return null; + var link = ReadNavigatorLink(element, DrawingViewMemoLink, 0x11); + if (link.Length == 0 || !records.TryGetValue(link[0], out var memo) || RecordClass(memo) != DrawingViewMemoClass || + !ReadNavigatorLink(memo, DrawingViewMemoLink, 0x12).SequenceEqual([drawing])) return null; + var view = ReadNavigatorLink(memo, DrawingViewLink, 0x12); + return view.Length == 0 ? null : views.GetValueOrDefault(view[0]); + } + + private static Guid? ReadLayoutDatabase(Dictionary records, Guid metadataId, byte[] metadata, + Guid role, Guid databaseClass) + { + var link = ReadNavigatorLink(metadata, role, 0x12); + if (link.Length == 0 || !records.TryGetValue(link[0], out var database)) return null; + if (RecordClass(database) != databaseClass || + !ReadNavigatorLink(database, role, 0x11).SequenceEqual([metadataId])) + throw new InvalidDataException("A layout has a conflicting database link."); + return link[0]; + } + + private static void ResolveMasterLayouts(Dictionary records, List items) + { + var masters = new Dictionary Layouts)>(); + foreach (var item in items) + { + if (item.Type != "MasterLayoutItem" || item.DatabaseGuid is not { } database) continue; + var layouts = ReadNavigatorLink(records[database], LayoutMasterLink, 1, 0x11).ToHashSet(); + if (!masters.TryAdd(database, (item, layouts))) + throw new InvalidDataException("Master layouts share the same database."); + } + for (int i = 0; i < items.Count; i++) + { + var item = items[i]; + if (item.Type != "LayoutItem" || item.DatabaseGuid is not { } database) continue; + var link = ReadNavigatorLink(records[database], LayoutMasterLink, 0x12); + if (link.Length == 0 || !masters.TryGetValue(link[0], out var master)) continue; + if (!master.Layouts.Contains(database)) + throw new InvalidDataException("A layout and its master have conflicting database links."); + items[i] = item with { MasterLayoutGuid = master.Item.Guid, PaperSize = master.Item.PaperSize }; + } + } + + private static (Guid Id, byte[] Body)? ReadLayoutSettings(Dictionary records, Guid item, byte[] body) + { + var matches = ReadNavigatorLink(body, NavigatorSettingLink, 1, 0x11) + .Where(id => records.TryGetValue(id, out var record) && RecordClass(record) == LayoutSettingsClass) + .Take(2).ToArray(); + if (matches.Length == 0) return null; + if (matches.Length != 1) throw new InvalidDataException("A layout has conflicting settings."); + var settings = records[matches[0]]; + if (!ReadNavigatorLink(settings, NavigatorSettingLink, 0x12).SequenceEqual([item])) + throw new InvalidDataException("A layout's settings have a conflicting owner."); + return (matches[0], settings); + } + + private static PlaLayoutPaperSize? ReadMasterPaperSize(byte[]? settings) + { + if (settings is null || !HasNavigatorEnvelope(settings, 51) || settings.Length < 94 || + !settings.AsSpan(92, 2).SequenceEqual(new byte[] { 0, 2 })) return null; + var dimensions = ReadRecordFields(settings, 94, out _); + if (dimensions.Length < 16) throw new InvalidDataException("A master layout's paper size is truncated."); + double width = BinaryPrimitives.ReadDoubleLittleEndian(dimensions); + double height = BinaryPrimitives.ReadDoubleLittleEndian(dimensions[8..]); + if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0) + throw new InvalidDataException("A master layout has an invalid paper size."); + return new PlaLayoutPaperSize(width, height); + } + + private static bool HasNavigatorEnvelope(byte[] body, int offset) => + body.Length >= offset + 6 && body[offset] is 0x82 or 0x83 && + body.AsSpan(offset + 1, 5).SequenceEqual(new byte[] { 0, 3, 0, 0, 0 }); + + private static (Guid Id, byte[] Record) ReadLinkedNavigatorRecord(Dictionary records, Guid item, + byte[] body, Guid role, Guid expectedClass, byte tag, byte reciprocalTag) + { + var targets = ReadNavigatorLink(body, role, tag); + if (targets.Length != 1 || !records.TryGetValue(targets[0], out var record) || RecordClass(record) != expectedClass || + !ReadNavigatorLink(record, role, reciprocalTag).SequenceEqual([item])) + throw new InvalidDataException("A layout book item has an invalid source or metadata link."); + return (targets[0], record); + } + + private static Guid[] ReadNavigatorLink(byte[] body, Guid role, byte tag, byte alternateTag = 0) + { + ReadRecordFields(body, 39, out var relationships); + Guid[]? result = null; + while (relationships.Length >= 17) + { + var targets = ReadRelationshipEntry(ref relationships, out byte actualTag, out var actualRole); + if (actualRole != role || actualTag != tag && actualTag != alternateTag) continue; + if (result is not null) throw new InvalidDataException("A navigator item has repeated links of the same role."); + result = ReadRelationshipTargets(targets); + } + CheckRelationshipEnd(relationships); + return result ?? []; + } + + private static Guid RecordClass(byte[] body) => new(body.AsSpan(0, 16)); + + private static Dictionary ReadLayoutRecords(PlaDocument document, IReadOnlyList classes) + { + var wanted = new HashSet + { + NavigatorRootClass, LayoutBookClass, LayoutSubsetClass, LayoutItemClass, MasterFolderClass, MasterLayoutClass, + LayoutDrawingClass, LayoutSourceClass, MasterSourceClass, DrawingSourceClass, LayoutMetadataClass, + MasterMetadataClass, DrawingMetadataClass, LayoutSettingsClass, LayoutRevisionStateClass, LayoutDatabaseClass, MasterDatabaseClass, + DrawingElementClass, DrawingViewMemoClass, SavedViewClass, SavedIndependentViewClass, LayoutRevisionOverrideClass, + }; + var kinds = classes.Where(c => wanted.Contains(c.Guid)).ToDictionary(c => c.Number, c => c.Guid); + var result = new Dictionary(); + if (!kinds.ContainsValue(LayoutBookClass)) return result; + var directories = new Dictionary>(); + Span tail = stackalloc byte[DirectoryFinder.RecordSize]; + tail.Clear(); + foreach (var block in document.Blocks) + { + if (!IsRawTable(block, DirectoryKind) || block.UnpackedSize < 40) continue; + ReadOnlySpan data = document.ReadPayload(block); + int header = DirectoryHeaderSize(data, NavigatorDirectoryLayout); + bool navigator = header != 0; + if (!navigator) header = DirectoryHeaderSize(data, DirectoryLayout); + if (header == 0) continue; + ulong units = BinaryPrimitives.ReadUInt64LittleEndian(data[(header - 40)..]); + var owner = new Guid(data.Slice(header - 32, 16)); + if (!navigator && !ContainsLayoutDatabase(data[header..], owner, kinds)) continue; + for (int i = header; i <= data.Length - DirectoryFinder.RecordSize; i += DirectoryFinder.RecordSize) + { + var record = DirectoryFinder.ReadRecord(data[i..]); + if (!kinds.TryGetValue(record.ClassNumber, out var type)) continue; + bool database = IsLayoutDatabase(type); + bool model = database || type == DrawingElementClass || type == DrawingViewMemoClass; + if (navigator == model || database && record.ObjectId != owner) continue; + AddDirectoryEntry(units, record, shortGuid: false); + } + // The prefixed directory can end two bytes before the end of its last entry. + if (!navigator && header == 42 && (data.Length - header) % DirectoryFinder.RecordSize == DirectoryFinder.RecordSize - 2) + { + data[^(DirectoryFinder.RecordSize - 2)..].CopyTo(tail); + var record = DirectoryFinder.ReadRecord(tail); + if (kinds.GetValueOrDefault(record.ClassNumber) == DrawingViewMemoClass) + AddDirectoryEntry(units, record, shortGuid: true); + } + } + if (directories.Count == 0) return result; + foreach (var pool in document.FindCompressedPools()) + { + long length = pool.TotalDecompressed; + if (length % ExtentUnit != 0 || !directories.TryGetValue((ulong)(length / ExtentUnit), out var entries)) continue; + var data = pool.Decode(); + foreach (var (record, shortGuid) in entries) + { + var entry = shortGuid ? CompleteDrawingMemoEntry(data, record) : record; + if (entry.ObjectId == Guid.Empty) continue; + var body = ReadIndexedPayload(data, entry); + if (body is null || body.Length < 46 || RecordClass(body) != kinds[entry.ClassNumber]) continue; + if (!result.TryAdd(entry.ObjectId, body) && !result[entry.ObjectId].AsSpan(35).SequenceEqual(body.AsSpan(35))) + throw new InvalidDataException("A layout book record has conflicting copies."); + } + } + return result; + + void AddDirectoryEntry(ulong units, ObjectDirectoryRecord record, bool shortGuid) + { + if (record.ObjectId == Guid.Empty || record.Count == 0 || record.Position > units || + record.Count > units - record.Position) return; + if (!directories.TryGetValue(units, out var entries)) directories.Add(units, entries = []); + entries.Add((record, shortGuid)); + } + } + + private static bool ContainsLayoutDatabase(ReadOnlySpan directory, Guid owner, Dictionary kinds) + { + for (int i = 0; i <= directory.Length - DirectoryFinder.RecordSize; i += DirectoryFinder.RecordSize) + { + var record = DirectoryFinder.ReadRecord(directory[i..]); + if (record.ObjectId == owner && IsLayoutDatabase(kinds.GetValueOrDefault(record.ClassNumber))) return true; + } + return false; + } + + private static bool IsLayoutDatabase(Guid type) => type == LayoutDatabaseClass || type == MasterDatabaseClass; + + private static ObjectDirectoryRecord CompleteDrawingMemoEntry(ReadOnlySpan pool, ObjectDirectoryRecord record) + { + var extent = pool.Slice((int)(record.Position * ExtentUnit), (int)(record.Count * ExtentUnit)); + if (!BlockHeaderParser.TryParse(extent, 0, extent.Length, out var header, poolSubgroup: true) || + header.Tag != "BL" || header.Version != 1 || header.Kind != record.ClassNumber || header.Guid is not { } id) + return default; + Span prefix = stackalloc byte[16]; + Span candidate = stackalloc byte[16]; + record.ObjectId.TryWriteBytes(prefix); + id.TryWriteBytes(candidate); + return prefix[..14].SequenceEqual(candidate[..14]) ? record with { ObjectId = id } : default; + } +} diff --git a/src/PlaIO/Internal/ElementReader.Locations.cs b/src/PlaIO/Internal/ElementReader.Locations.cs new file mode 100644 index 0000000..7ec513a --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Locations.cs @@ -0,0 +1,217 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private const ushort GenericBlockKind = 0xFFDC; + private static readonly Guid LayerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + private static readonly Guid BuiltInLayer = new("4d22523e-c844-4209-a123-3608c8964de4"); + private static readonly Guid StoryTableClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + private static readonly Guid StoryDescriptorClass = new("bc046b25-27d6-461a-a6e5-6fa0e8594a95"); + private static readonly Guid StoryPartitionRelation = new("baf95b80-f256-4932-b891-03ff66848591"); + private static readonly Guid DoorHostRelation = new("1f6bfe02-d60c-40ae-9ac8-c3953ce12814"); + private static readonly Guid OpeningHostRelation = new("49f5b35f-3e0e-4644-a659-d024c2c93228"); + private static readonly Guid WallTopStoryRelation = new("7b48cc47-7267-4cfd-9133-9214ea18fb99"); + private static readonly Guid ColumnTopStoryRelation = new("5ebebc2d-cf0b-4751-8f55-7c2353c3fd14"); + private static ReadOnlySpan LayerNameFrame => [0x83, 0, 3, 0, 0, 0, 1, 0]; + private static ReadOnlySpan StoryTableFrame => [1, 0, 3, 0, 0, 1, 0]; + private static ReadOnlySpan StoryDescriptorFrame => [5, 0, 0x83, 0, 3, 0, 0, 0, 1, 0]; + + private readonly record struct ElementLocation(int? LayerIndex, int? HomeStoryIndex, Guid Host, Guid TopStoryPartition); + + private readonly record struct Story(string? Name, double? Elevation); + + internal static IReadOnlyList ReadStoryCatalog(PlaDocument document, IReadOnlyList classes) => + ReadStories(document, classes).OrderBy(row => row.Key) + .Select(row => new PlaStory(row.Key, row.Value.Name!, row.Value.Elevation)).ToList().AsReadOnly(); + + private static ElementLocation ReadElementLocation(ReadOnlySpan data, string type, int frame, bool olderObject = false) + { + if (type == "Opening") return new ElementLocation(null, null, ReadSingleRelation(data, OpeningHostRelation), Guid.Empty); + + int offset = frame + (type switch + { + "Beam" or "Column" => 703, + "Door" or "Roof" => 177, + "Object" when olderObject => 45, + "Lamp" or "Object" => 171, + _ => 165, + }); + if (offset > data.Length - 6 || BinaryPrimitives.ReadUInt16LittleEndian(data[(offset - 2)..]) != 1) + return default; + + int layer = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); + int story = BinaryPrimitives.ReadInt16LittleEndian(data[(offset + 4)..]); + Guid host = type == "Door" ? ReadSingleRelation(data, DoorHostRelation) : Guid.Empty; + Guid topStory = type switch + { + "Wall" => ReadSingleRelation(data[frame..], WallTopStoryRelation, requireSection: true), + "Column" => ReadSingleRelation(data[frame..], ColumnTopStoryRelation, requireSection: true), + _ => Guid.Empty, + }; + return new ElementLocation(layer > 0 ? layer : null, story, host, topStory); + } + + private static Guid ReadSingleRelation(ReadOnlySpan data, Guid relation, byte tag = 0x12, bool requireSection = false) + { + Span marker = stackalloc byte[17]; + marker[0] = tag; + relation.TryWriteBytes(marker[1..]); + int start = data.IndexOf(marker); + if (start < 0 || data.Length - start < marker.Length + 16 || data[(start + 1)..].IndexOf(marker) >= 0) + return Guid.Empty; + if (requireSection && FindRelationshipSection(data, start) < 0) return Guid.Empty; + return new Guid(data.Slice(start + marker.Length, 16)); + } + + private static int FindRelationshipSection(ReadOnlySpan data, int relationOffset) + { + int section = -1; + for (int offset = 0; offset <= relationOffset - 6; offset++) + { + if (BinaryPrimitives.ReadUInt32LittleEndian(data[offset..]) != data.Length - offset - sizeof(uint) || + BinaryPrimitives.ReadUInt16LittleEndian(data[(offset + sizeof(uint))..]) != 1) continue; + if (section >= 0) return -1; + section = offset + 6; + } + return section; + } + + private static Dictionary ReadStoryPartitions(PlaDocument document, IReadOnlyList classes, + Dictionary stories) + { + var classNumbers = classes.Where(c => c.Guid == StoryDescriptorClass).Select(c => c.Number).ToHashSet(); + var partitions = new Dictionary(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || !classNumbers.Contains(block.Kind)) continue; + byte[]? body = block.Mode == PlaBlockMode.Lz + ? document.ReadStandalonePayload(block) + : document.PayloadStartsWithClass(block, StoryDescriptorClass) ? document.ReadPayload(block) : null; + if (body is null) continue; + + ReadOnlySpan data = body; + if (data.Length < 64 || new Guid(data[..16]) != StoryDescriptorClass || + !data.Slice(39, StoryDescriptorFrame.Length).SequenceEqual(StoryDescriptorFrame)) continue; + if (ReadElementId(data[49..], out int consumed) is null) continue; + var tail = data[(49 + consumed)..]; + if (tail.Length < 11 || tail[2] != 1 || + BinaryPrimitives.ReadUInt32LittleEndian(tail[5..]) != tail.Length - 9 || + BinaryPrimitives.ReadUInt16LittleEndian(tail[9..]) != 1) continue; + + int story = BinaryPrimitives.ReadInt16LittleEndian(tail); + if (!stories.ContainsKey(story)) continue; + Guid partition = ReadSingleRelation(tail[11..], StoryPartitionRelation, 0x11); + if (partition != Guid.Empty && !partitions.TryAdd(partition, story) && partitions[partition] != story) + partitions[partition] = null; + } + return partitions; + } + + private static Dictionary ReadLayerNames(PlaDocument document, IReadOnlyList classes) + { + var names = new Dictionary(); + foreach (var layer in ReadLayerRecords(document, classes)) + { + if (layer.Name is { } name && !names.TryAdd(layer.Index, name) && names[layer.Index] != name) + throw new InvalidDataException($"Layer {layer.Index} has conflicting names."); + } + return names; + } + + internal static IReadOnlyList ReadLayerCatalog(PlaDocument document, IReadOnlyList classes) + { + var layers = new Dictionary(); + var indices = new Dictionary(); + foreach (var layer in ReadLayerRecords(document, classes)) + { + if (layer.Guid == Guid.Empty) continue; + if (!layers.TryAdd(layer.Index, layer) && layers[layer.Index] != layer || + !indices.TryAdd(layer.Guid, layer.Index) && indices[layer.Guid] != layer.Index) + throw new InvalidDataException($"Layer {layer.Index} has conflicting records."); + } + return layers.Values.OrderBy(layer => layer.Index).ToList().AsReadOnly(); + } + + private static IEnumerable ReadLayerRecords(PlaDocument document, IReadOnlyList classes) + { + var classNumbers = classes.Where(c => c.Guid == LayerClass).Select(c => c.Number).ToHashSet(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || + (block.Kind != GenericBlockKind && !classNumbers.Contains(block.Kind)) || + !document.PayloadStartsWithClass(block, LayerClass)) continue; + + ReadOnlySpan data = document.ReadPayload(block); + if (data.Length < 55 || !data.Slice(47, LayerNameFrame.Length).SequenceEqual(LayerNameFrame)) continue; + var name = ReadElementId(data[55..], out int consumed); + // The built-in layer can store a resource token in place of a name. + if (name is null) + { + if (block.Guid != BuiltInLayer || !data[55..].StartsWith(new byte[] { 1, 0, 0, 0, 0x14, 0 })) + continue; + consumed = 6; + } + var tail = data[(55 + consumed)..]; + if (tail.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(tail) != 1) continue; + int index = BinaryPrimitives.ReadInt32LittleEndian(tail[2..]); + if (index > 0) + yield return new PlaLayer(block.Guid.GetValueOrDefault(), index, name, ReadLayerGroup(tail)); + } + } + + private static uint? ReadLayerGroup(ReadOnlySpan data) => + data.Length >= 39 ? BinaryPrimitives.ReadUInt32LittleEndian(data[35..]) : null; + + private static Dictionary ReadStories(PlaDocument document, IReadOnlyList classes) + { + var classNumbers = classes.Where(c => c.Guid == StoryTableClass).Select(c => c.Number).ToHashSet(); + var stories = new Dictionary(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || !classNumbers.Contains(block.Kind) || + !document.PayloadStartsWithClass(block, StoryTableClass)) continue; + + ReadOnlySpan data = document.ReadPayload(block); + if (data.Length < 50 || !data.Slice(39, StoryTableFrame.Length).SequenceEqual(StoryTableFrame)) continue; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(data[46..]); + var rows = data[50..]; + if (count < 2 || count > rows.Length / 19) + throw new InvalidDataException("The story count is outside the story table."); + + var storedStories = new Story[count]; + for (int i = 0; i < storedStories.Length; i++) + { + if (rows.Length < 19 || BinaryPrimitives.ReadUInt16LittleEndian(rows) != 2 || + BinaryPrimitives.ReadUInt16LittleEndian(rows[10..]) != 1) + throw new InvalidDataException("A story table record has an invalid header."); + var name = ReadElementId(rows[12..], out int consumed); + if (name is null || consumed > rows.Length - 15) + throw new InvalidDataException("A story name exceeds its record."); + double elevation = BinaryPrimitives.ReadDoubleLittleEndian(rows[2..]); + storedStories[i] = new Story(name, double.IsFinite(elevation) ? elevation : null); + rows = rows[(15 + consumed)..]; + } + + if (rows.Length < 6) throw new InvalidDataException("The story table is missing its index range."); + int firstStory = BinaryPrimitives.ReadInt16LittleEndian(rows); + int lastStory = BinaryPrimitives.ReadInt32LittleEndian(rows[2..]); + // The last row is the upper boundary of the highest story. + if (lastStory != firstStory + storedStories.Length - 2) + throw new InvalidDataException("The story table index range does not match its story count."); + for (int i = 0; i < storedStories.Length - 1; i++) + { + int index = firstStory + i; + var story = storedStories[i]; + if (stories.TryAdd(index, story)) continue; + if (stories[index].Name != story.Name) + throw new InvalidDataException($"Story {index} has conflicting names."); + if (stories[index].Elevation != story.Elevation) + stories[index] = story with { Elevation = null }; + } + } + return stories; + } +} diff --git a/src/PlaIO/Internal/ElementReader.MaterialDirectories.cs b/src/PlaIO/Internal/ElementReader.MaterialDirectories.cs new file mode 100644 index 0000000..f26d05e --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.MaterialDirectories.cs @@ -0,0 +1,55 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private const ushort FileDirectoryKind = 0xFDEB; + private static readonly Guid FileDirectoryLayout = new("90b1e208-3b15-45e1-854c-23f5368b97cc"); + + private static IEnumerable<(ObjectDirectoryRecord Record, PlaBlock Block)> FindUnindexedAttributeBlocks( + PlaDocument document, Dictionary kinds, HashSet seen) + { + var indexed = new Lazy>(() => + document.Blocks.Where(b => b.Tag == "BL" && b.Version == 1 && b.Guid.HasValue).ToLookup(b => b.Guid!.Value)); + foreach (var directory in document.Blocks.Where(b => IsRawTable(b, FileDirectoryKind))) + { + var records = ReadFileDirectory(document.ReadPayload(directory), document.Length); + if (records.Count < 2) continue; + var missing = records.Where(r => kinds.ContainsKey(r.ClassNumber) && !seen.Contains(r.ObjectId)).ToArray(); + if (missing.Length == 0) continue; + + // The indexed blocks locate the extent table. Its separate root verifies the chosen origin. + var origins = records.Skip(1).SelectMany(record => indexed.Value[record.ObjectId] + .Where(b => b.Kind == record.ClassNumber) + .Select(b => b.Offset - (long)record.Position * ExtentUnit)) + .Where(offset => offset >= directory.End).Distinct() + .Where(offset => document.ReadDirectoryBlock(offset, records[0]) is not null).Take(2).ToArray(); + if (origins.Length != 1) continue; + foreach (var record in missing) + if (document.ReadDirectoryBlock(origins[0], record) is { } block) + yield return (record, block); + } + } + + private static List ReadFileDirectory(ReadOnlySpan data, long fileLength) + { + if (data.Length < 70 || data[8..24].IndexOfAnyExcept((byte)0) >= 0 || + new Guid(data[24..40]) != FileDirectoryLayout) return []; + ulong used = BinaryPrimitives.ReadUInt64LittleEndian(data); + if (used == 0 || used > (ulong)fileLength / ExtentUnit) return []; + + var records = new List(); + ulong position = 0; + for (int offset = 40; position < used && offset <= data.Length - DirectoryFinder.RecordSize; offset += DirectoryFinder.RecordSize) + { + var record = DirectoryFinder.ReadRecord(data[offset..]); + if (record.ObjectId == Guid.Empty || record.Position != position || + record.Count == 0 || record.Count > used - position) return []; + records.Add(record); + position += record.Count; + } + return position == used ? records : []; + } +} diff --git a/src/PlaIO/Internal/ElementReader.Materials.cs b/src/PlaIO/Internal/ElementReader.Materials.cs new file mode 100644 index 0000000..c84dae8 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Materials.cs @@ -0,0 +1,157 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + internal static PlaMaterialCatalog ReadMaterialCatalog(PlaDocument document, IReadOnlyList classes) + { + var kinds = classes.Where(c => c.Guid == BuildingMaterialClass || c.Guid == CompositeClass) + .ToDictionary(c => c.Number, c => c.Guid); + var materials = new Dictionary(); + var composites = new Dictionary(); + var seen = new HashSet(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || block.Guid is not { } id || id == Guid.Empty || + !kinds.TryGetValue(block.Kind, out Guid type)) continue; + var payload = block.Mode == PlaBlockMode.Lz ? document.ReadStandalonePayload(block) : + document.PayloadStartsWithClass(block, type) ? document.ReadPayload(block) : null; + if (payload is not null) Add(id, type, payload); + } + + if (kinds.Count != 0) + foreach (var (record, block) in FindUnindexedAttributeBlocks(document, kinds, seen)) + if (document.ReadDirectoryPayload(block) is { } payload) + Add(record.ObjectId, kinds[record.ClassNumber], payload); + + return new PlaMaterialCatalog(materials.Values.OrderBy(m => m.Index).ToList().AsReadOnly(), + composites.Values.OrderBy(c => c.Index).ToList().AsReadOnly()); + + void Add(Guid id, Guid type, byte[] payload) + { + if (payload.Length < 16 || new Guid(payload.AsSpan(0, 16)) != type) return; + var data = ReadNamedAttribute(payload, out string? name, out int index); + if (data.IsEmpty) return; + if (type == BuildingMaterialClass) + { + uint? raw = ReadBuildingMaterialPriority(data, out string? materialId); + int? priority = raw switch + { + 4200 => 0, + >= 4300 and <= 5909 => (int)(((raw.Value - 4298) * 31 + 25) / 50), + _ => null, + }; + var material = new PlaBuildingMaterial(id, index, name!, materialId, priority); + if (!materials.TryAdd(index, material)) + { + if (materials[index] != material) throw new InvalidDataException($"Building material {index} has conflicting records."); + return; + } + } + else + { + if (ReadComposite(id, index, name!, data) is not { } composite) return; + if (!composites.TryAdd(index, composite)) + { + var prior = composites[index]; + if ((prior.Guid, prior.Name, prior.TotalThickness) != (composite.Guid, composite.Name, composite.TotalThickness) || + !prior.Skins.SequenceEqual(composite.Skins) || + (prior.UseWith is null) != (composite.UseWith is null) || + !(prior.UseWith ?? []).SequenceEqual(composite.UseWith ?? [])) + throw new InvalidDataException($"Composite {index} has conflicting records."); + return; + } + } + if (!seen.Add(id)) throw new InvalidDataException($"Material attribute {id:D} has conflicting indices or classes."); + } + } + + private static ReadOnlySpan ReadNamedAttribute(ReadOnlySpan payload, out string? name, out int index, + int frame = 47) + { + name = null; + index = 0; + int start = frame + LayerNameFrame.Length; + if (payload.Length < start + sizeof(int) || !payload[frame..].StartsWith(LayerNameFrame) || + ReadElementId(payload[start..], out int consumed) is not { } value) return default; + var data = payload[(start + consumed)..]; + if (data.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 1) return default; + index = BinaryPrimitives.ReadInt32LittleEndian(data[2..]); + if (index <= 0) return default; + name = value; + return data; + } + + private static uint? ReadBuildingMaterialPriority(ReadOnlySpan data, out string? id) + { + id = null; + if (data.Length < 41) return null; + id = ReadElementId(data[37..], out int consumed); + return id is not null && data.Length - 37 - consumed >= 4 + ? BinaryPrimitives.ReadUInt32LittleEndian(data[(37 + consumed)..]) : null; + } + + private const int CompositeSkinSize = 23; + + private static ReadOnlySpan ReadCompositeSkinRows(ReadOnlySpan data) + { + if (data.Length < 45) return default; + int count = BinaryPrimitives.ReadUInt16LittleEndian(data[43..]); + return count > 0 && count <= (data.Length - 45) / CompositeSkinSize + ? data.Slice(45, count * CompositeSkinSize) : default; + } + + private static PlaComposite? ReadComposite(Guid id, int index, string name, ReadOnlySpan data) + { + var rows = ReadCompositeSkinRows(data); + if (rows.IsEmpty) return null; + double total = ReadDouble(data, 35); + var skins = new PlaCompositeSkin[rows.Length / CompositeSkinSize]; + for (int i = 0; i < skins.Length; i++) + { + var row = rows[(i * CompositeSkinSize)..]; + int material = BinaryPrimitives.ReadUInt16LittleEndian(row[8..]); + double thickness = ReadDouble(row, 15); + if (ReadCompositeSkinFunction(row) is not { } function) + return null; + skins[i] = new PlaCompositeSkin(material, thickness, function == 1, function == 5); + } + if (!(Math.Abs(skins.Sum(skin => skin.Thickness) - total) <= JunctionTolerance)) return null; + + ushort usage = BinaryPrimitives.ReadUInt16LittleEndian(data[6..]); + List? useWith = null; + if ((usage & ~60) == 0 && (usage & 48) is 0 or 48) + { + useWith = new List(4); + if ((usage & 4) != 0) useWith.Add("Wall"); + if ((usage & 8) != 0) useWith.Add("Slab"); + if ((usage & 48) != 0) useWith.AddRange(["Roof", "Shell"]); + } + return new PlaComposite(id, index, name, total, Array.AsReadOnly(skins), useWith?.AsReadOnly()); + } + + private static byte? ReadCompositeSkinFunction(ReadOnlySpan row) => + row.StartsWith(new byte[] { 5, 1, 17, 0, 0, 0, 1, 0 }) && + BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) > 0 && + row[14] is 1 or 5 or 6 && ReadDouble(row, 15) is >= 0 and < double.PositiveInfinity + ? row[14] : null; + + private static (int? Material, int? Composite) ReadMaterialReference(ReadOnlySpan record, bool wall) + { + var settings = AfterCountedString(record, wall ? 197 : 185); + int structure = wall ? 225 : 83; + if (settings.Length < structure + 6 || BinaryPrimitives.ReadUInt16LittleEndian(settings[(structure + 2)..]) != 1) + return default; + + return BinaryPrimitives.ReadUInt16LittleEndian(settings[structure..]) switch + { + 1 when BinaryPrimitives.ReadInt32LittleEndian(settings[(structure - 10)..]) is > 0 and { } material => + (material, null), + 2 when BinaryPrimitives.ReadUInt16LittleEndian(settings[(structure + 4)..]) is > 0 and { } composite => + (null, composite), + _ => default, + }; + } +} diff --git a/src/PlaIO/Internal/ElementReader.ObliqueColumns.cs b/src/PlaIO/Internal/ElementReader.ObliqueColumns.cs new file mode 100644 index 0000000..81bfb4c --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.ObliqueColumns.cs @@ -0,0 +1,225 @@ +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static PlaColumnCutMesh? ReadObliqueColumn(ReadOnlySpan column, ReadOnlySpan hatch, + PlaMemberProfile? profile, Guid memo, List<(Guid Key, Guid Id)>? contacts, ElementLocation location, + ModelGeometry geometry, double angle) + { + if (profile is null || contacts is null || !double.IsFinite(angle) || + geometry.StoryElevation(location.HomeStoryIndex) is not { } home || + ReadStraightProfileSection(profile.Components) is not { Count: 1 } regions || regions[0].Count != 4 || + ReadColumnFootprint(column, hatch, angle) is not { } plan || + geometry.Attributes.Material.GetValueOrDefault(profile.Components[0].BuildingMaterialIndex) is not (> 0 and { } priority)) + return null; + var (sin, cos) = Math.SinCos(angle); + if (Math.Abs(sin) > JunctionTolerance && Math.Abs(cos) > JunctionTolerance) return null; + var ring = regions[0]; + if (ring.Where((p, i) => p.X != ring[(i + 1) % ring.Count].X && p.Y != ring[(i + 1) % ring.Count].Y).Any()) return null; + + var lowNormal = ReadBeamVector(column, 336); + var highNormal = ReadBeamVector(column, 394); + bool alongX = Math.Abs(lowNormal.Y) <= JunctionTolerance && Math.Abs(highNormal.Y) <= JunctionTolerance; + if (!lowNormal.IsUnit || !highNormal.IsUnit || !(lowNormal.Z < -JunctionTolerance && highNormal.Z > JunctionTolerance) || + !alongX && (Math.Abs(lowNormal.X) > JunctionTolerance || Math.Abs(highNormal.X) > JunctionTolerance)) return null; + + var origin = new PlaColumnMeshPoint(ReadDouble(column, 312), ReadDouble(column, 320), home); + double start = alongX ? plan.X0 - origin.X : plan.Y0 - origin.Y; + double end = alongX ? plan.X1 - origin.X : plan.Y1 - origin.Y; + double minAcross = alongX ? origin.Y - plan.Y1 : plan.X0 - origin.X; + double maxAcross = alongX ? origin.Y - plan.Y0 : plan.X1 - origin.X; + double lowZ = ReadDouble(column, 328), highZ = ReadDouble(column, 386); + double lowSlope = -(alongX ? lowNormal.X : lowNormal.Y) / lowNormal.Z; + double highSlope = -(alongX ? highNormal.X : highNormal.Y) / highNormal.Z; + PlaPlanPoint[] section = [new(start, lowZ + lowSlope * start), new(end, lowZ + lowSlope * end), + new(end, highZ + highSlope * end), new(start, highZ + highSlope * start)]; + if (!(section[3].Y > section[0].Y && section[2].Y > section[1].Y)) return null; + var height = new Elevations(section.Min(p => p.Y), section.Max(p => p.Y)); + var box = MakeBoundingBox(plan, height.Bottom + home, height.Top + home); + if (box is null) return null; + + var masks = new List(); + var seen = new HashSet(); + foreach (var (role, contact) in contacts) + { + if (role == ColumnWallRelation) + { + if (geometry.Read(contact, WallColumnJunctionClass) is not { } wallJunction || + ReadSingleRelation(wallJunction, role, requireSection: true) != memo) return null; + Guid wallId = ReadSingleRelation(wallJunction, WallColumnRelation, requireSection: true); + if (geometry.Read(wallId, WallClass) is not { } wall || !HasGeometryRelation(wall, WallColumnRelation, contact) || + !WallClearsObliqueColumn(geometry, wallId, wall, location.LayerIndex, priority, box)) return null; + continue; + } + if (role != ColumnBeamRelation || geometry.Read(contact, BeamColumnJunctionClass) is not { } joint || + ReadSingleRelation(joint, role, requireSection: true) != memo) return null; + Guid beamId = ReadSingleRelation(joint, BeamColumnRelation, requireSection: true); + if (ReadBeamPriority(geometry, beamId, contact) is not (> 0 and { } beamPriority)) return null; + if (beamPriority <= priority || !seen.Add(beamId)) continue; + if (geometry.Read(beamId, BeamMemoClass) is not { } beamMemo || + ReadStraightBeamAxis(geometry, beamId, beamMemo, home, out var ends, readAnnotations: true) is not { } beam || + !SameIntersectionGroup(geometry, beam.Layer, location.LayerIndex) || + !HasOnlyBeamTargetContact(beamMemo, BeamColumnRelation, contact, beam.Owner, (r, j) => + BeamKeepsObliqueColumnCut(geometry, beamId, beam, ends, beamPriority, r, j, home, box)) || + !AddObliqueBeamMasks(geometry, beamId, beamMemo, beam, ends, origin, alongX, minAcross, maxAcross, masks)) + return null; + } + + return masks.Count > 0 ? BuildColumnCutMesh(section, minAcross, maxAcross, masks, origin, + (p, across) => alongX ? new(p.X, -across, p.Y) : new(across, p.X, p.Y)) : null; + } + + private static bool AddObliqueBeamMasks(ModelGeometry geometry, Guid beamId, byte[] memo, BeamPrism axis, BeamEndPlanes ends, + PlaColumnMeshPoint origin, bool alongX, double minAcross, double maxAcross, List masks) + { + double direction = alongX ? axis.Dx : axis.Dy; + double acrossDirection = alongX ? -axis.Dy : axis.Dx; + if (Math.Abs(acrossDirection * axis.Length) > JunctionTolerance || Math.Abs(axis.SinRoll) > JunctionTolerance || + !ends.StartNormal.IsUnit || !ends.EndNormal.IsUnit || + Math.Abs(alongX ? ends.StartNormal.Y : ends.StartNormal.X) > JunctionTolerance || + Math.Abs(alongX ? ends.EndNormal.Y : ends.EndNormal.X) > JunctionTolerance || + geometry.Read(axis.Owner, BeamClass) is not { } body) return false; + + var record = body.AsSpan(FindClassFrame(body, BeamClass)); + IReadOnlyList>? profile; + if (ReadMemberProfile(record, axis.Owner, beam: true, geometry) is { } section) + profile = ReadStraightProfileSection(section.Components); + else if (ReadBeamRectangle(ReadBeamHatch(geometry, beamId, memo)) is { } rect) + profile = [[new(-rect.HalfWidth, -rect.Depth), new(rect.HalfWidth, -rect.Depth), new(rect.HalfWidth, 0), new(-rect.HalfWidth, 0)]]; + else + return false; + if (profile is null || profile.Any(r => r.Where((p, i) => p.X != r[(i + 1) % r.Count].X && p.Y != r[(i + 1) % r.Count].Y).Any())) + return false; + + double length = double.Hypot(axis.Length, ends.Rise); + double heading = Math.CopySign(axis.Length / length, direction), pitch = ends.Rise / length; + double lateral = alongX ? origin.Y - axis.Y : axis.X - origin.X; + double start = alongX ? axis.X - origin.X : axis.Y - origin.Y; + double end = start + Math.CopySign(axis.Length, direction); + double startDot = (alongX ? ends.StartNormal.X : ends.StartNormal.Y) * heading + ends.StartNormal.Z * pitch; + double endDot = (alongX ? ends.EndNormal.X : ends.EndNormal.Y) * heading + ends.EndNormal.Z * pitch; + if (!(startDot < -JunctionTolerance && endDot > JunctionTolerance)) return false; + + var knots = profile.SelectMany(r => r).Select(p => p.X).Distinct().Order().ToArray(); + for (int k = 1; k < knots.Length; k++) + { + double a = lateral + Math.CopySign(1, direction) * knots[k - 1], b = lateral + Math.CopySign(1, direction) * knots[k]; + double first = Math.Max(minAcross, Math.Min(a, b)), last = Math.Min(maxAcross, Math.Max(a, b)); + if (!(last > first)) continue; + double sample = (knots[k - 1] + knots[k]) / 2; + var edges = new List(); + foreach (var ring in profile) + for (int i = 0; i < ring.Count; i++) + { + var p = ring[i]; + var q = ring[(i + 1) % ring.Count]; + if (sample > Math.Min(p.X, q.X) && sample < Math.Max(p.X, q.X)) edges.Add(p.Y); + } + if (edges.Count % 2 != 0) return false; + edges.Sort(); + for (int i = 0; i < edges.Count; i += 2) + { + double z0 = edges[i], z1 = edges[i + 1]; + PlaPlanPoint[] polygon = [AtEnd(start, axis.Z, z0, ends.StartNormal, startDot), + AtEnd(end, axis.Z + ends.Rise, z0, ends.EndNormal, endDot), + AtEnd(end, axis.Z + ends.Rise, z1, ends.EndNormal, endDot), + AtEnd(start, axis.Z, z1, ends.StartNormal, startDot)]; + if (!polygon.All(p => double.IsFinite(p.X) && double.IsFinite(p.Y)) || + Math.CopySign(1, direction) * (polygon[1].X - polygon[0].X) <= JunctionTolerance || + Math.CopySign(1, direction) * (polygon[2].X - polygon[3].X) <= JunctionTolerance || masks.Count >= 48) + return false; + if (direction < 0) Array.Reverse(polygon); + masks.Add(new ColumnBeamMask(first, last, polygon)); + } + } + return true; + + PlaPlanPoint AtEnd(double x, double z, double offset, BeamVector normal, double dot) + { + double upX = -Math.CopySign(1, direction) * pitch; + double upZ = axis.Length / length; + double slide = -offset * ((alongX ? normal.X : normal.Y) * upX + normal.Z * upZ) / dot; + return new(x + offset * upX + slide * heading, z + offset * upZ + slide * pitch); + } + } + + private static bool BeamKeepsObliqueColumnCut(ModelGeometry geometry, Guid beamId, BeamPrism beam, BeamEndPlanes ends, + uint priority, Guid role, Guid id, double home, PlaBoundingBox target) + { + var plan = (target.XMin, target.YMin, target.XMax, target.YMax); + if (role == BeamColumnRelation) return ReadBeamStructuralNeighbor(geometry, beamId, role, id) is not null; + if (role == BeamWallRelation) + return BeamWinsContact(geometry, beamId, role, id, priority) || + ReadBeamStructuralNeighbor(geometry, beamId, role, id) is { } wall && + WallClearsObliqueColumn(geometry, wall.Id, wall.Body, beam.Layer, priority, target); + if (role == BeamSlabRelation) + return BeamWinsContact(geometry, beamId, role, id, priority) || + ReadBeamSlabCutBox(geometry, beamId, id, new(target.ZMin, target.ZMax), out var slab) && + (slab is null || ClearPlan(slab, plan)); + + if (ReadBeamAxisJunction(geometry, beamId, role, id) is not { } contact || + geometry.Read(contact.Peer, BeamMemoClass) is not { } memo || !HasGeometryRelation(memo, contact.Reciprocal, id) || + ReadStraightBeamAxis(geometry, contact.Peer, memo, home, out var otherEnds, readAnnotations: true) is not { } other || + !SameIntersectionGroup(geometry, beam.Layer, other.Layer) || + ReadBeamContactExtents(geometry, contact.Peer, memo, other) is not { } outline) return false; + if (IsOnBeamJoint(beam, contact.X, contact.Y, IsBeamEndRelation(role)) && + IsOnBeamJoint(other, contact.X, contact.Y, IsBeamEndRelation(contact.Reciprocal))) + { + var (lo, hi) = ProjectRectangle(plan, other.X, other.Y, other.Dy, -other.Dx); + if (hi < outline.Left - JunctionTolerance || lo > outline.Right + JunctionTolerance) return true; + } + + if (!IsBeamEndRelation(role) || !IsBeamEndRelation(contact.Reciprocal) || + Math.Abs(beam.Dx * other.Dy - beam.Dy * other.Dx) > JunctionTolerance || + geometry.Read(beamId, BeamMemoClass) is not { } ownMemo || + ReadBeamCutEnd(geometry, beamId, ownMemo, beam, ends, contact.X, contact.Y) is not { } own || + ReadBeamCutEnd(geometry, contact.Peer, memo, other, otherEnds, contact.X, contact.Y) is not { } peer || + Math.Abs(own.Normal.Dot(peer.Normal) + 1) > JunctionTolerance) return false; + + // Opposing cap planes bound the join. The entire target must lie on the cutter's side of both planes. + return PlaneMinimum(peer.Normal, peer.Centre) > JunctionTolerance && + PlaneMinimum(own.Normal * -1, own.Centre) > JunctionTolerance; + + double PlaneMinimum(BeamVector normal, BeamVector centre) => + ProjectRectangle(plan, centre.X, centre.Y, normal.X, normal.Y).Min + + normal.Z * ((normal.Z >= 0 ? target.ZMin : target.ZMax) - home - centre.Z); + } + + private static (BeamVector Normal, BeamVector Centre)? ReadBeamCutEnd(ModelGeometry geometry, Guid beamId, byte[] memo, + BeamPrism axis, BeamEndPlanes ends, double x, double y) + { + if (Math.Abs((x - axis.X) * axis.Dy - (y - axis.Y) * axis.Dx) > JunctionTolerance || + geometry.Read(axis.Owner, BeamClass) is not { } record) return null; + var profile = ReadMemberProfile(record.AsSpan(FindClassFrame(record, BeamClass)), axis.Owner, beam: true, geometry); + if (ProjectBeamCaps(axis, ends, ReadBeamHatch(geometry, beamId, memo), profile) is not { } caps) return null; + bool start = Covers(caps.First), end = Covers(caps.Last); + if (start == end) return null; + return start ? (ends.StartNormal, new BeamVector(axis.X, axis.Y, axis.Z)) : + (ends.EndNormal, new BeamVector(axis.X + axis.Dx * axis.Length, axis.Y + axis.Dy * axis.Length, axis.Z + ends.Rise)); + + bool Covers(PlaBoundingBox cap) => cap.XMin - JunctionTolerance <= x && x <= cap.XMax + JunctionTolerance && + cap.YMin - JunctionTolerance <= y && y <= cap.YMax + JunctionTolerance; + } + + private static bool WallClearsObliqueColumn(ModelGeometry geometry, Guid wallId, byte[] wall, int? groupLayer, + uint priority, PlaBoundingBox target) + { + var plan = (target.XMin, target.YMin, target.XMax, target.YMax); + if (ReadWallPriority(geometry, wallId, wall) is > 0 and { } wallPriority && wallPriority <= priority) return true; + var settings = ReadWallSettings(wall); + if (ReadSavedWallBox(settings) is { } box && ClearPlan(box, plan)) return true; + if (ReadWallReferencePlan(settings, out _) is not { } wallPlan) + return ProfileWallMissesBoxes(geometry, wallId, wall, groupLayer, priority, [target], allowPartialPlan: true); + double x = wallPlan.End.X - wallPlan.Start.X, y = wallPlan.End.Y - wallPlan.Start.Y; + double length = double.Hypot(x, y); + var (lo, hi) = ProjectRectangle(plan, wallPlan.Start.X, wallPlan.Start.Y, y / length, -x / length); + return hi < Math.Min(wallPlan.OutsideOffset, wallPlan.InsideOffset) - JunctionTolerance || + lo > Math.Max(wallPlan.OutsideOffset, wallPlan.InsideOffset) + JunctionTolerance; + } + + private static bool ClearPlan(PlaBoundingBox box, (double X0, double Y0, double X1, double Y1) plan) => + box.XMin > plan.X1 + JunctionTolerance || box.XMax < plan.X0 - JunctionTolerance || + box.YMin > plan.Y1 + JunctionTolerance || box.YMax < plan.Y0 - JunctionTolerance; +} diff --git a/src/PlaIO/Internal/ElementReader.OpeningGeometry.cs b/src/PlaIO/Internal/ElementReader.OpeningGeometry.cs new file mode 100644 index 0000000..4cd05a2 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.OpeningGeometry.cs @@ -0,0 +1,130 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static PlaOpeningGeometry? ReadPlacedOpening(ReadOnlySpan settings, PlaOpeningProfile profile, PlaPlanPoint slabOrigin, + (double X0, double Y0, double X1, double Y1) footprint, out double area) + { + area = 0; + var localOrigin = SlabOpeningProfileOrigin(settings, profile); + var origin = new PlaPlanPoint(slabOrigin.X + localOrigin.X, slabOrigin.Y + localOrigin.Y); + var plan = TranslateOpeningPlan(footprint, slabOrigin); + if (!double.IsFinite(plan.X0) || !double.IsFinite(plan.Y0) || !double.IsFinite(plan.X1) || !double.IsFinite(plan.Y1) || + plan.X0 >= plan.X1 || plan.Y0 >= plan.Y1) + return null; + if (profile.Shape == "Custom") + { + var polygon = settings[304..]; + if (ReadStraightRings(polygon, out area) is not { } local) return null; + var rings = local.Select(ring => (IReadOnlyList)Array.AsReadOnly(ring + .Select(p => new PlaPlanPoint(p.X + origin.X, p.Y + origin.Y)).ToArray())).ToArray(); + return new PlaOpeningGeometry(origin, Array.AsReadOnly(rings)); + } + if (profile.Shape is "Circle" or "Ellipse") + { + // The top-center frame uses different circular subdivision counts. Its analytic placement is still available. + if (profile.Shape == "Circle" && settings[256..].StartsWith(CenteredOpeningFrame)) + area = 36 * Math.Tan(Math.PI / 36) * (profile.Width / 2) * (profile.Height / 2); + return new PlaOpeningGeometry(origin, null); + } + area = profile.Width * profile.Height; + PlaPlanPoint[] corners = [new(plan.X0, plan.Y0), new(plan.X1, plan.Y0), new(plan.X1, plan.Y1), new(plan.X0, plan.Y1)]; + return new PlaOpeningGeometry(origin, Array.AsReadOnly>([Array.AsReadOnly(corners)])); + } + + private static bool OpeningFitsSlab(ReadOnlySpan polygon, PlaOpeningGeometry placement, PlaOpeningProfile profile, + (double X0, double Y0, double X1, double Y1) bounds) + { + if (BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0) return false; + bounds = OpeningCutPlan(bounds, profile); + if (SlabPolygonContainsFootprint(polygon, bounds, allowBoundary: true)) return true; + if (profile.Shape != "Custom" || placement.Rings is not { Count: 1 } || + ReadStraightRings(polygon, out _) is not { } slab) + return false; + // A hole can subtract area even when it lies entirely within the footprint's boundary. + var ring = placement.Rings[0]; + if (slab.Skip(1).Any(hole => !IsSeparateHole([slab[0], ring], hole) && + !OpeningPlansDisjoint(bounds, (hole.Min(p => p.X), hole.Min(p => p.Y), hole.Max(p => p.X), hole.Max(p => p.Y))))) + return false; + return Enumerable.Range(0, ring.Count).All(i => SegmentInSlab(ring[i], ring[(i + 1) % ring.Count], slab[0])); + } + + private static bool SegmentInSlab(PlaPlanPoint a, PlaPlanPoint b, IReadOnlyList boundary) + { + var positions = new List { 0, 1 }; + double dx = b.X - a.X, dy = b.Y - a.Y; + double lengthSquared = dx * dx + dy * dy; + if (!double.IsFinite(lengthSquared) || lengthSquared == 0) return false; + for (int i = 0; i < boundary.Count; i++) + { + var c = boundary[i]; + var d = boundary[(i + 1) % boundary.Count]; + double ex = d.X - c.X, ey = d.Y - c.Y; + double det = dx * ey - dy * ex; + double ox = c.X - a.X, oy = c.Y - a.Y; + if (det != 0) + { + double t = (ox * ey - oy * ex) / det, u = (ox * dy - oy * dx) / det; + if (t is > 0 and < 1 && u is >= 0 and <= 1) positions.Add(t); + } + else + { + double t = (ox * dx + oy * dy) / lengthSquared; + if (t is > 0 and < 1) positions.Add(t); + } + } + positions.Sort(); + for (int i = 1; i < positions.Count; i++) + { + double t = (positions[i - 1] + positions[i]) * 0.5; + var point = new PlaPlanPoint(a.X + t * dx, a.Y + t * dy); + if (!ContainsPoint(boundary, point) && !PointOnOpeningBoundary(boundary, point)) return false; + } + return true; + } + + private static bool PointOnOpeningBoundary(IReadOnlyList ring, PlaPlanPoint point) + { + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double lengthSquared = dx * dx + dy * dy; + if (lengthSquared <= 0 || !double.IsFinite(lengthSquared)) continue; + double t = Math.Clamp(((point.X - a.X) * dx + (point.Y - a.Y) * dy) / lengthSquared, 0, 1); + double x = point.X - (a.X + t * dx), y = point.Y - (a.Y + t * dy); + if (x * x + y * y <= JunctionTolerance * JunctionTolerance) return true; + } + return false; + } + + private static (double X0, double Y0, double X1, double Y1) TranslateOpeningPlan( + (double X0, double Y0, double X1, double Y1) plan, PlaPlanPoint origin) => + (plan.X0 + origin.X, plan.Y0 + origin.Y, plan.X1 + origin.X, plan.Y1 + origin.Y); + + private static (double X0, double Y0, double X1, double Y1) OpeningCutPlan( + (double X0, double Y0, double X1, double Y1) plan, PlaOpeningProfile profile) + { + if (profile.Shape != "Circle") return plan; + double extra = profile.Width / 2 * (1 / Math.Cos(Math.PI / 36) - 1); + return (plan.X0 - extra, plan.Y0 - extra, plan.X1 + extra, plan.Y1 + extra); + } + + private static bool OpeningPlansDisjoint((double X0, double Y0, double X1, double Y1) a, + (double X0, double Y0, double X1, double Y1) b) => + a.X1 <= b.X0 || a.X0 >= b.X1 || a.Y1 <= b.Y0 || a.Y0 >= b.Y1; + + private static bool SameOpeningGeometry(PlaOpeningGeometry? first, PlaOpeningGeometry? second) + { + if (first == second) return true; + if (first is null || second is null || first.Origin != second.Origin || first.CutVolume != second.CutVolume) + return false; + return (first.Rings is null ? second.Rings is null : second.Rings is { } rings && + first.Rings.Count == rings.Count && first.Rings.Zip(rings).All(pair => pair.First.SequenceEqual(pair.Second))) && + (first.Cuts is null ? second.Cuts is null : second.Cuts is { } cuts && first.Cuts.SequenceEqual(cuts)); + } +} diff --git a/src/PlaIO/Internal/ElementReader.Openings.cs b/src/PlaIO/Internal/ElementReader.Openings.cs new file mode 100644 index 0000000..f3786bd --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Openings.cs @@ -0,0 +1,155 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid OpeningCutClass = new("9a756127-8689-486d-8873-5c1d7b0f8785"); + private static readonly Guid OpeningCutRelation = new("219fcd20-e2ef-4e61-bb1b-a771897ff878"); + private static readonly Guid CutElementRelation = new("fc9598c9-7004-45ef-93e0-8fdcbc306acf"); + private static ReadOnlySpan CenteredOpeningFrame => [2, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0]; + + private readonly record struct OpeningLinks(Guid Host, IReadOnlyList? Targets = null); + + private static PlaOpeningProfile? ReadOpeningProfile(ReadOnlySpan settings) + { + if (settings.Length < 363 || !settings[230..].StartsWith(new byte[] { 1, 3, 70, 0, 0, 0 })) + return null; + var polygon = settings[304..]; + uint size = BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..]); + if (!polygon.StartsWith(new byte[] { 0, 0, 2, 1 }) || + !polygon[8..].StartsWith(new byte[] { 1, 31, 0 }) || size < 59 || size > polygon.Length) + return null; + + uint kind = BinaryPrimitives.ReadUInt32LittleEndian(settings[236..]); + uint dimensions = BinaryPrimitives.ReadUInt32LittleEndian(settings[298..]); + if (kind is < 1 or > 3 || dimensions > 1) return null; + double width = ReadDouble(settings, 240); + double height = kind != 3 && dimensions == 0 ? width : ReadDouble(settings, 248); + if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0) return null; + if (kind == 3 && (ReadOutlineBounds(polygon) is not { } bounds || + Math.Abs(bounds.X1 - bounds.X0 - width) > JunctionTolerance || + Math.Abs(bounds.Y1 - bounds.Y0 - height) > JunctionTolerance)) + return null; + + string shape = kind switch + { + 1 => width == height ? "Square" : "Rectangle", + 2 => width == height ? "Circle" : "Ellipse", + _ => "Custom", + }; + return new PlaOpeningProfile(shape, width, height); + } + + private static OpeningLinks ReadOpeningLinks(ReadOnlySpan opening, Guid id, + ModelGeometry geometry, Dictionary elements) + { + var owner = ReadOpeningRelation(opening, OpeningHostRelation, owner: true); + if (owner.IsEmpty) return default; + + var host = new Guid(owner); + if (ReadOpeningTarget(host, geometry, elements) is not { } hostRecord || + !HasGeometryRelation(hostRecord, OpeningHostRelation, id)) + return default; + + var cuts = ReadOpeningRelation(opening, OpeningCutRelation); + if (cuts.IsEmpty) return new OpeningLinks(host); + var targets = new SortedSet(); + for (int i = 0; i < cuts.Length; i += 16) + { + var cutId = new Guid(cuts.Slice(i, 16)); + var (source, target) = ReadOpeningCut(geometry, cutId); + if (source != id || target == Guid.Empty) return new OpeningLinks(host); + var targetRecord = target == host ? hostRecord : ReadOpeningTarget(target, geometry, elements); + if (targetRecord is null || !HasGeometryRelation(targetRecord, CutElementRelation, cutId) || !targets.Add(target)) + return new OpeningLinks(host); + } + return targets.Contains(host) ? new OpeningLinks(host, Array.AsReadOnly(targets.ToArray())) : new OpeningLinks(host); + } + + private static (Guid Opening, Guid Target) ReadOpeningCut(ModelGeometry geometry, Guid id) + { + if (geometry.Read(id, OpeningCutClass) is not { } cut) return default; + var opening = ReadOpeningRelation(cut, OpeningCutRelation, owner: true); + var target = ReadOpeningRelation(cut, CutElementRelation, owner: true); + return opening.IsEmpty || target.IsEmpty ? default : (new Guid(opening), new Guid(target)); + } + + private static byte[]? ReadOpeningTarget(Guid id, ModelGeometry geometry, Dictionary elements) => + elements.TryGetValue(id, out var element) && (element.Guid == SlabClass || element.Guid == WallClass) + ? geometry.Read(id, element.Guid) : null; + + private static ReadOnlySpan ReadOpeningRelation(ReadOnlySpan record, Guid relation, bool owner = false) => + TryReadRelationTargets(record, relation, out var ids, owner) ? ids : default; + + private static bool TryReadRelationTargets(ReadOnlySpan record, Guid relation, out ReadOnlySpan ids, bool owner = false) + { + ids = default; + int start = FindRelationshipSection(record, record.Length); + if (start < 0) return false; + var data = record[start..]; + ReadOnlySpan result = default; + bool found = false; + while (data.Length >= 17) + { + var entry = data; + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out _)) return false; + if (key != relation) continue; + if (found || (owner ? tag != 0x12 : tag is not (1 or 0x11))) return false; + found = true; + result = ReadRelationIds(entry, data, tag); + } + if (data is not [0] || found && result.IsEmpty) return false; + ids = result; + return true; + } + + private static Elevations? ReadOpeningElevations(ReadOnlySpan opening, Guid id, PlaOpeningProfile? profile, + OpeningLinks links, ModelGeometry geometry, Dictionary elements, out PlaOpeningGeometry? cutGeometry) + { + cutGeometry = null; + if (profile is null || links.Host == Guid.Empty || links.Targets is null) return null; + var settings = AfterCountedString(opening, ClassElementIdOffset("Opening")); + if (elements[links.Host].Guid == SlabClass) + return ReadSlabOpeningElevations(settings, id, profile, links, geometry, out cutGeometry); + return links.Targets.Count == 1 ? ReadVerticalWallOpeningElevations(settings, profile) : null; + } + + private static Elevations? ReadVerticalWallOpeningElevations(ReadOnlySpan settings, PlaOpeningProfile profile) + { + if (settings.Length < 290 || !settings[256..].StartsWith(CenteredOpeningFrame) || + BinaryPrimitives.ReadUInt32LittleEndian(settings[278..]) is not (0 or 2) || + profile.Shape == "Custom") + return null; + + // The center-anchored profile has its local Y axis along project Z. + if (!(Math.Abs(ReadDouble(settings, 174)) <= JunctionTolerance && + Math.Abs(ReadDouble(settings, 182)) <= JunctionTolerance && + Math.Abs(ReadDouble(settings, 190)) <= JunctionTolerance && + Math.Abs(Math.Abs(ReadDouble(settings, 198)) - 1) <= JunctionTolerance && + Math.Abs(ReadDouble(settings, 222)) <= JunctionTolerance)) + return null; + + double center = ReadDouble(settings, 270); + return CheckedElevations(center - profile.Height / 2, center + profile.Height / 2); + } + + private static Elevations? ReadWallOpeningContact(ModelGeometry geometry, ReadOnlySpan wallRecord, + Guid wall, Guid role, Guid id) + { + var (opening, target) = role == CutElementRelation ? ReadOpeningCut(geometry, id) : (id, wall); + if (target != wall || geometry.Read(opening, OpeningClass) is not { } body || + ReadSingleRelation(body, OpeningHostRelation, 0x12, requireSection: true) != wall || + !HasGeometryRelation(wallRecord, OpeningHostRelation, opening)) + return null; + var cuts = ReadOpeningRelation(body, OpeningCutRelation); + if (cuts.Length != 16) return null; + var operation = new Guid(cuts); + if (role == CutElementRelation ? operation != id : ReadOpeningCut(geometry, operation) != (opening, wall) || + !HasGeometryRelation(wallRecord, CutElementRelation, operation)) + return null; + var settings = AfterCountedString(body.AsSpan(FindClassFrame(body, OpeningClass)), ClassElementIdOffset("Opening")); + return ReadOpeningProfile(settings) is { } profile ? ReadVerticalWallOpeningElevations(settings, profile) : null; + } +} diff --git a/src/PlaIO/Internal/ElementReader.PlanarContours.cs b/src/PlaIO/Internal/ElementReader.PlanarContours.cs new file mode 100644 index 0000000..ab735e1 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.PlanarContours.cs @@ -0,0 +1,161 @@ +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private sealed class PlanarEdge(PlaPlanPoint start, PlaPlanPoint end) + { + internal PlaPlanPoint Start { get; } = start; + internal PlaPlanPoint End { get; } = end; + internal List<(double Parameter, PlaPlanPoint Point)> Nodes { get; } = [(0, start), (1, end)]; + internal List<(double Start, double End, bool SameDirection)> Overlaps { get; } = []; + } + + private static IReadOnlyList>? SubtractSlabFootprint( + IReadOnlyList> rings, IReadOnlyList> footprint, double cutArea) + { + double footprintArea = footprint.Sum(SignedRingArea); + if (!double.IsFinite(footprintArea) || footprintArea >= 0 || footprint.Any(r => !IsSimpleRing(r)) || + CombinePlanarContours(rings, footprint, subtract: true) is not { } result) + return null; + + double area = result.Sum(SignedRingArea); + double perimeter = rings.Concat(footprint).Sum(ring => ring.Select((p, i) => Distance(p, ring[(i + 1) % ring.Count])).Sum()); + return area > 0 && Math.Abs(rings.Sum(SignedRingArea) - area - cutArea) <= JunctionTolerance * Math.Max(1, perimeter) + ? result : null; + } + + private static IReadOnlyList>? CombinePlanarContours( + IReadOnlyList> rings, IReadOnlyList> operand, bool subtract) + { + if (rings.Sum(r => r.Count) + operand.Sum(r => r.Count) > 4096) return null; + var outline = rings.SelectMany(Edges).ToArray(); + var other = operand.SelectMany(Edges).ToArray(); + foreach (var a in outline) + foreach (var b in other) + SplitPlanarEdges(a, b); + + var next = new Dictionary(); + var predecessors = new HashSet(); + // Both kinds of boundary put the remaining material to their left. + if (!KeepBoundaryEdges(outline, p => ContainsMaterial(operand, p), true) || + !KeepBoundaryEdges(other, p => ContainsMaterial(rings, p) != subtract, false) || + next.Count is < 3 or > 4096) + return null; + + var result = new List>(); + while (next.Count != 0) + { + var start = next.First().Key; + var ring = new List(); + var current = start; + do + { + ring.Add(current); + if (!next.Remove(current, out current)) return null; + } while (current != start); + if (ring.Count < 3 || !IsSimpleRing(ring) || SignedRingArea(ring) == 0) return null; + result.Add(ring.AsReadOnly()); + } + + return result.AsReadOnly(); + + static IEnumerable Edges(IReadOnlyList ring) => + ring.Select((point, i) => new PlanarEdge(point, ring[(i + 1) % ring.Count])); + + static bool ContainsMaterial(IReadOnlyList> contours, PlaPlanPoint point) => + contours.Count(r => ContainsPoint(r, point)) % 2 != 0; + + bool KeepBoundaryEdges(PlanarEdge[] edges, Func isRemoved, bool isOutline) + { + foreach (var edge in edges) + { + edge.Nodes.Sort((a, b) => a.Parameter.CompareTo(b.Parameter)); + for (int i = 1; i < edge.Nodes.Count; i++) + { + var (t0, start) = edge.Nodes[i - 1]; + var (t1, end) = edge.Nodes[i]; + if (start == end) continue; + if (!(t0 < t1)) return false; + double t = t0 + (t1 - t0) / 2; + int overlap = edge.Overlaps.FindIndex(r => r.Start < t && t < r.End); + var middle = new PlaPlanPoint(start.X + (end.X - start.X) / 2, start.Y + (end.Y - start.Y) / 2); + bool keep = overlap >= 0 ? isOutline && edge.Overlaps[overlap].SameDirection : !isRemoved(middle); + if (keep && (!next.TryAdd(start, end) || !predecessors.Add(end))) return false; + } + } + return true; + } + } + + private static void SplitPlanarEdges(PlanarEdge a, PlanarEdge b) + { + if (!SegmentsIntersect(a.Start, a.End, b.Start, b.End)) return; + double ax = a.End.X - a.Start.X, ay = a.End.Y - a.Start.Y; + double bx = b.End.X - b.Start.X, by = b.End.Y - b.Start.Y; + double x = b.Start.X - a.Start.X, y = b.Start.Y - a.Start.Y; + double cross = ax * by - ay * bx; + if (cross != 0) + { + // Prefer a saved vertex at a shared endpoint to give all its incident edges the same node. + if (AddEndpoint(a, b, a.Start, 0) | AddEndpoint(a, b, a.End, 1) | + AddEndpoint(b, a, b.Start, 0) | AddEndpoint(b, a, b.End, 1)) return; + double t = (x * by - y * bx) / cross; + double u = (x * ay - y * ax) / cross; + if (t is > 0 and < 1 && u is > 0 and < 1) + { + var p = new PlaPlanPoint(a.Start.X + t * ax, a.Start.Y + t * ay); + a.Nodes.Add((t, p)); + b.Nodes.Add((u, p)); + } + return; + } + if (Cross(a.Start, a.End, b.Start) != 0 || Cross(a.Start, a.End, b.End) != 0) return; + AddOverlap(a, b); + AddOverlap(b, a); + + static double Parameter(PlanarEdge edge, PlaPlanPoint p) + { + double dx = edge.End.X - edge.Start.X, dy = edge.End.Y - edge.Start.Y; + return Math.Abs(dx) >= Math.Abs(dy) ? (p.X - edge.Start.X) / dx : (p.Y - edge.Start.Y) / dy; + } + + static bool AddEndpoint(PlanarEdge owner, PlanarEdge edge, PlaPlanPoint p, double position) + { + if (Cross(edge.Start, edge.End, p) != 0) return false; + double t = Parameter(edge, p); + if (t is < 0 or > 1) return false; + owner.Nodes.Add((position, p)); + edge.Nodes.Add((t, p)); + return true; + } + + static void AddOverlap(PlanarEdge edge, PlanarEdge other) + { + double t = Parameter(edge, other.Start), u = Parameter(edge, other.End); + if (t is > 0 and < 1) edge.Nodes.Add((t, other.Start)); + if (u is > 0 and < 1) edge.Nodes.Add((u, other.End)); + double lo = Math.Max(0, Math.Min(t, u)), hi = Math.Min(1, Math.Max(t, u)); + if (lo < hi) edge.Overlaps.Add((lo, hi, t < u)); + } + } + + private static IReadOnlyList? GroupSlabPrisms(IReadOnlyList> rings) + { + return GroupPlanarContours(rings) is { } groups + ? Array.AsReadOnly(groups.Select(g => new PlaSlabPrism(g.AsReadOnly())).ToArray()) : null; + } + + private static List>[]? GroupPlanarContours(IReadOnlyList> rings) + { + var groups = rings.Where(r => SignedRingArea(r) > 0).Select(r => new List> { r }).ToArray(); + foreach (var hole in rings.Where(r => SignedRingArea(r) < 0)) + { + var group = groups.Where(g => IsSeparateHole([g[0]], hole)).MinBy(g => SignedRingArea(g[0])); + if (group is null || !IsSeparateHole(group, hole)) return null; + group.Add(hole); + } + return groups.Length > 0 ? groups : null; + } +} diff --git a/src/PlaIO/Internal/ElementReader.ProfileCatalog.cs b/src/PlaIO/Internal/ElementReader.ProfileCatalog.cs new file mode 100644 index 0000000..1435847 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.ProfileCatalog.cs @@ -0,0 +1,115 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid ProfileAttributeClass = new("31ab5131-81ae-4181-a714-7e4d3dd1a91d"); + + internal static IReadOnlyList ReadProfileCatalog(PlaDocument document, IReadOnlyList classes) + { + var kinds = classes.Where(c => c.Guid == ProfileAttributeClass).ToDictionary(c => c.Number, c => c.Guid); + if (kinds.Count == 0) return []; + var modifierRecords = new Lazy>(() => ReadProfileModifierRecords(document, classes)); + var profiles = new Dictionary(); + var seen = new HashSet(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || block.Guid is not { } id || id == Guid.Empty || + !kinds.ContainsKey(block.Kind)) continue; + var payload = block.Mode == PlaBlockMode.Lz ? document.ReadStandalonePayload(block) : + document.PayloadStartsWithClass(block, ProfileAttributeClass) ? document.ReadPayload(block) : null; + if (payload is not null) Add(id, payload); + } + + foreach (var (record, block) in FindUnindexedAttributeBlocks(document, kinds, seen)) + if (document.ReadDirectoryPayload(block) is { } payload) + Add(record.ObjectId, payload); + + return profiles.Values.OrderBy(p => p.Index).ToList().AsReadOnly(); + + void Add(Guid id, byte[] payload) + { + if (payload.Length < 16 || new Guid(payload.AsSpan(0, 16)) != ProfileAttributeClass) return; + var data = ReadNamedAttribute(payload, out var name, out int index, frame: 51); + if (data.IsEmpty) return; + var useWith = data.Length >= 37 ? ReadProfileUsage(BinaryPrimitives.ReadUInt16LittleEndian(data[35..])) : null; + var section = ReadSectionVector(data, 37); + var components = ReadProfileComponents(section, allowUnassignedMaterial: true); + var bounds = components is not null ? ReadProfileBounds(components) : default; + var rest = section.IsEmpty ? default : data[(45 + section.Length)..]; + var stretch = ReadProfileStretchSettings(rest); + var profile = new PlaProfileAttribute(id, index, name!, useWith, bounds?.X1 - bounds?.X0, bounds?.Y1 - bounds?.Y0, + components?.Any(c => c.Function == "Core"), components) + { + WidthStretch = stretch.IsEmpty ? null : ReadProfileStretch(stretch[26..], bounds?.X0, bounds?.X1), + HeightStretch = stretch.IsEmpty ? null : ReadProfileStretch(stretch[43..], bounds?.Y0, bounds?.Y1), + Modifiers = ReadProfileModifiers(payload, id, rest, section, components, modifierRecords), + }; + if (!profiles.TryAdd(index, profile)) + { + var prior = profiles[index]; + if (prior.Guid != id || prior.Name != name || (prior.UseWith is null) != (useWith is null) || + !(prior.UseWith ?? []).SequenceEqual(useWith ?? []) || prior.WidthStretch != profile.WidthStretch || + prior.HeightStretch != profile.HeightStretch || (prior.Modifiers is null) != (profile.Modifiers is null) || + !(prior.Modifiers ?? []).SequenceEqual(profile.Modifiers ?? []) || + !SameProfile(index, index, prior.Components, components)) + throw new InvalidDataException($"Profile attribute {index} has conflicting records."); + return; + } + if (!seen.Add(id)) throw new InvalidDataException($"Profile attribute {id:D} has conflicting indices."); + } + } + + private static IReadOnlyList? ReadProfileUsage(ushort flags) + { + if ((flags & ~31) != 0) return null; + var types = new List(5); + if ((flags & 1) != 0) types.Add("Wall"); + if ((flags & 4) != 0) types.Add("Beam"); + if ((flags & 2) != 0) types.Add("Column"); + if ((flags & 8) != 0) types.Add("Railing"); + if ((flags & 16) != 0) types.Add("Object"); + return types.AsReadOnly(); + } + + private static (double X0, double Y0, double X1, double Y1)? ReadProfileBounds(IReadOnlyList components) + { + double xMin = double.PositiveInfinity, xMax = double.NegativeInfinity; + double yMin = double.PositiveInfinity, yMax = double.NegativeInfinity; + foreach (var component in components) + { + foreach (var ring in component.Rings) + foreach (var vertex in ring) + Include(vertex.U, vertex.Z); + foreach (var arc in component.Arcs ?? []) + { + var ring = component.Rings[arc.RingIndex]; + var start = ring[arc.StartVertexIndex]; + var end = ring[(arc.StartVertexIndex + 1) % ring.Count]; + if (ReadCircularEdge(new(start.U, start.Z), new(end.U, end.Z), arc.SweepRadians, out _) is not { } edge) + return null; + for (int axis = 0; axis < 4; axis++) + { + double angle = axis * (Math.PI / 2); + if (edge.IncludesAngle(angle)) + { + var point = edge.AtAngle(angle); + Include(point.X, point.Y); + } + } + } + } + double width = xMax - xMin, height = yMax - yMin; + return width > 0 && height > 0 && double.IsFinite(width) && double.IsFinite(height) ? (xMin, yMin, xMax, yMax) : null; + + void Include(double x, double y) + { + xMin = Math.Min(x, xMin); + xMax = Math.Max(x, xMax); + yMin = Math.Min(y, yMin); + yMax = Math.Max(y, yMax); + } + } +} diff --git a/src/PlaIO/Internal/ElementReader.ProfileModifierValues.cs b/src/PlaIO/Internal/ElementReader.ProfileModifierValues.cs new file mode 100644 index 0000000..de0035b --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.ProfileModifierValues.cs @@ -0,0 +1,154 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static Dictionary? ReadProfileModifierValues(ReadOnlySpan section, + IReadOnlyList components, ReadOnlySpan tables) + { + if (ReadProfileModifierGroups(ref tables) is not { } modifiers || + ReadProfileDimensionGroups(ref tables) is not { } groups || + ReadProfileHatchVertices(section, components) is not { } vertices || + ReadProfileDimensionAnchors(ref tables, vertices) is not { } anchors || + !ReadProfileTableCount(ref tables, 114, out int count)) + return null; + + var dimensions = new Dictionary(); + var seen = new HashSet(); + for (int i = 0; i < count; i++, tables = tables[114..]) + { + var row = tables[..114]; + Guid id = new(row[..16]); + if (!seen.Add(id) || !row[16..].StartsWith(new byte[] { 1, 1, 92, 0, 0, 0 })) return null; + var owner = new Guid(row.Slice(70, 16)); + double angle = ReadDouble(row, 106); + int kind = BinaryPrimitives.ReadInt32LittleEndian(row[102..]); + if (owner == Guid.Empty || owner != new Guid(row.Slice(86, 16)) || kind is not (2 or 3) || + !double.IsFinite(angle) || !anchors.TryGetValue(new Guid(row.Slice(22, 16)), out var a) || + !anchors.TryGetValue(new Guid(row.Slice(38, 16)), out var b)) continue; + double value = (b.U - a.U) * Math.Cos(angle) + (b.Z - a.Z) * Math.Sin(angle); + if (double.IsFinite(value)) dimensions.Add(id, (owner, value)); + } + + var result = new Dictionary(); + foreach (var (owner, groupIds) in modifiers) + { + double? value = null; + foreach (Guid group in groupIds) + { + if (!groups.TryGetValue(group, out Guid id) || !dimensions.TryGetValue(id, out var dimension) || + dimension.Modifier != owner || (value is { } known && Math.Abs(dimension.Value - known) > 1e-7)) + { + value = null; + break; + } + value ??= dimension.Value; + } + if (value is { } confirmed) result.Add(owner, confirmed); + } + return result; + } + + private static Dictionary? ReadProfileModifierGroups(ref ReadOnlySpan data) + { + if (!ReadProfileTableCount(ref data, 22, out int count)) return null; + var groups = new Dictionary(); + for (int i = 0; i < count; i++) + { + if (data.Length < 22) return null; + Guid key = new(data[..16]); + data = data[16..]; + if (!ReadProfileTableCount(ref data, 16, out int length)) return null; + var ids = new Guid[length]; + for (int j = 0; j < length; j++) + ids[j] = new Guid(data.Slice(16 * j, 16)); + if (!groups.TryAdd(key, ids)) return null; + data = data[(16 * length)..]; + } + return groups; + } + + private static Dictionary? ReadProfileDimensionGroups(ref ReadOnlySpan data) + { + if (!ReadProfileTableCount(ref data, 46, out int count)) return null; + var dimensions = new Dictionary(); + for (int i = 0; i < count; i++) + { + if (data.Length < 46 || !data[16..].StartsWith(new byte[] { 1, 0, 2, 0, 0, 0, 1, 0, 1, 0 })) + return null; + Guid key = new(data[..16]); + int edges = BinaryPrimitives.ReadInt32LittleEndian(data[26..]); + if (edges <= 0 || edges > (data.Length - 46) / 28) return null; + int target = 30 + edges * 28; + for (int j = 30; j < target; j += 28) + if (!data[j..].StartsWith(new byte[] { 1, 0, 1, 0 }) || + BinaryPrimitives.ReadUInt32LittleEndian(data[(j + 24)..]) > 1) return null; + if (!dimensions.TryAdd(key, new Guid(data.Slice(target, 16)))) return null; + data = data[(target + 16)..]; + } + return dimensions; + } + + private static Dictionary? ReadProfileHatchVertices(ReadOnlySpan vector, + IReadOnlyList components) + { + var items = ReadFirstWallHatch(vector, out uint count); + int offset = vector.Length - items.Length; + if (count != components.Count || offset < 16) return null; + var points = new Dictionary(); + foreach (var component in components) + { + int length = ReadHatchSize(vector[offset..], 2); + // Constraint vertex indices count across rings without their stored closing vertices. + if (length == 0 || !points.TryAdd(new Guid(vector.Slice(offset - 16, 16)), + component.Rings.SelectMany(ring => ring).ToArray())) return null; + offset += length; + if (offset == vector.Length) break; + if (vector.Length - offset < 16) return null; + offset += 16; + } + return offset == vector.Length && points.Count == components.Count ? points : null; + } + + private static Dictionary? ReadProfileDimensionAnchors(ref ReadOnlySpan data, + Dictionary vertices) + { + if (!ReadProfileTableCount(ref data, 83, out int count)) return null; + var seen = new HashSet(); + var result = new Dictionary(); + for (int i = 0; i < count; i++, data = data[83..]) + { + Guid id = new(data[..16]); + var anchor = data.Slice(16, 67); + if (!seen.Add(id) || BinaryPrimitives.ReadUInt16LittleEndian(anchor) != 1 || + BinaryPrimitives.ReadUInt16LittleEndian(anchor[6..]) != 1 || + BinaryPrimitives.ReadUInt16LittleEndian(anchor[28..]) != 1 || anchor[50] > 1) return null; + int kind = BinaryPrimitives.ReadInt32LittleEndian(anchor[2..]); + if (kind == 3 && anchor[50] == 1) + { + double u = ReadDouble(anchor, 51), z = ReadDouble(anchor, 59); + if (double.IsFinite(u) && double.IsFinite(z)) result.Add(id, new(u, z)); + } + if (kind is 1 or 2) + { + int reference = kind == 1 ? 8 : 30; + Guid hatch = new(anchor.Slice(reference, 16)); + int vertex = BinaryPrimitives.ReadInt32LittleEndian(anchor[(reference + 16)..]); + if (vertices.TryGetValue(hatch, out var points) && vertex > 0 && vertex <= points.Length) + result.Add(id, points[vertex - 1]); + } + } + return result; + } + + private static bool ReadProfileTableCount(ref ReadOnlySpan data, int rowSize, out int count) + { + count = 0; + if (data.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 1) return false; + count = BinaryPrimitives.ReadInt32LittleEndian(data[2..]); + data = data[6..]; + return count >= 0 && count <= data.Length / rowSize; + } +} diff --git a/src/PlaIO/Internal/ElementReader.ProfileModifiers.cs b/src/PlaIO/Internal/ElementReader.ProfileModifiers.cs new file mode 100644 index 0000000..a175203 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.ProfileModifiers.cs @@ -0,0 +1,110 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid ProfileModifierClass = new("09f84a8c-dcf6-45b4-96aa-e23380acf496"); + private static readonly Guid ProfileModifierDefinitionClass = new("7fd67a75-4b36-4be8-bf9a-6ce013ab9247"); + private static readonly Guid ProfileModifierOwnerRelation = new("d98b1d57-b28c-44bf-92a3-a67c8881ed56"); + private static readonly Guid ProfileModifierDefinitionRelation = new("43f52d63-b8d0-4659-b981-4401a14823b1"); + private static ReadOnlySpan ProfileStretchFrame => + [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + private static ReadOnlySpan ReadProfileStretchSettings(ReadOnlySpan data) + { + ReadOnlySpan result = default; + int offset = 0; + while (data[offset..].IndexOf(SectionVectorFrame) is >= 0 and var relative) + { + int start = offset + relative; + offset = start + SectionVectorFrame.Length; + var section = ReadSectionVector(data, start); + if (section.IsEmpty) continue; + var tail = data[(start + 8 + section.Length)..]; + if (tail.Length < 68 || !tail.StartsWith(ProfileStretchFrame) || tail[60] != 2 || + tail[61] != 0 || tail[62] > 1 || BinaryPrimitives.ReadUInt32LittleEndian(tail[63..]) != 4 || + tail[67] != 1) + continue; + if (!result.IsEmpty) return default; + result = tail; + } + return result; + } + + private static PlaProfileStretch? ReadProfileStretch(ReadOnlySpan data, double? sectionStart, double? sectionEnd) + { + double start = ReadDouble(data, 1), end = ReadDouble(data, 9); + if (data[0] == 0 && start == 0 && end == 0) + return new PlaProfileStretch(false, null, null, sectionEnd - sectionStart); + if (data[0] != 1 || !double.IsFinite(start) || !double.IsFinite(end) || end < start) + return null; + double? minimum = null; + if (sectionStart is { } first && sectionEnd is { } last) + minimum = (last - first) - Math.Max(0, Math.Min(end, last) - Math.Max(start, first)); + return new PlaProfileStretch(true, start, end, minimum); + } + + private static IReadOnlyList? ReadProfileModifiers(ReadOnlySpan profile, Guid id, + ReadOnlySpan data, ReadOnlySpan section, IReadOnlyList? components, + Lazy> records) + { + if (data.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 1 || + !TryReadRelationTargets(profile, ProfileModifierOwnerRelation, out var ids) || + BinaryPrimitives.ReadUInt32LittleEndian(data[2..]) != ids.Length / 16) + return null; + if (ids.IsEmpty) return []; + var values = components is null ? null : ReadProfileModifierValues(section, components, data); + var modifiers = new List(); + var seen = new HashSet(); + for (int i = 0; i < ids.Length; i += 16) + { + Guid modifierId = new(ids.Slice(i, 16)); + if (modifierId == Guid.Empty || !seen.Add(modifierId) || + records.Value.GetValueOrDefault(modifierId) is not { } modifier || + new Guid(modifier.AsSpan(0, 16)) != ProfileModifierClass || + ReadSingleRelation(modifier, ProfileModifierOwnerRelation, requireSection: true) != id) + return null; + Guid definitionId = ReadSingleRelation(modifier, ProfileModifierDefinitionRelation, requireSection: true); + if (definitionId == Guid.Empty || records.Value.GetValueOrDefault(definitionId) is not { Length: >= 53 } definition || + new Guid(definition.AsSpan(0, 16)) != ProfileModifierDefinitionClass || + !definition.AsSpan(41).StartsWith(LayerNameFrame) || + !HasGeometryRelation(definition, ProfileModifierDefinitionRelation, modifierId) || + ReadElementId(definition.AsSpan(49), out _) is not { } name) + return null; + double? value = modifier.Length >= 63 && modifier.AsSpan(39).StartsWith(new byte[] { 1, 0, 0x83, 0, 3, 0, 0, 0 }) && + values is not null && values.TryGetValue(new Guid(modifier.AsSpan(47, 16)), out double resolved) + ? resolved : null; + modifiers.Add(new PlaProfileModifier(modifierId, definitionId, name) { DefaultValue = value }); + } + return modifiers.AsReadOnly(); + } + + private static Dictionary ReadProfileModifierRecords(PlaDocument document, IReadOnlyList classes) + { + var kinds = classes.Where(c => c.Guid == ProfileModifierClass || c.Guid == ProfileModifierDefinitionClass) + .ToDictionary(c => c.Number, c => c.Guid); + var result = new Dictionary(); + if (kinds.Count == 0) return result; + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || block.Guid is not { } id || id == Guid.Empty || + !kinds.TryGetValue(block.Kind, out Guid type)) continue; + var payload = block.Mode == PlaBlockMode.Lz ? document.ReadStandalonePayload(block) : + document.PayloadStartsWithClass(block, type) ? document.ReadPayload(block) : null; + Add(id, type, payload); + } + + foreach (var (record, block) in FindUnindexedAttributeBlocks(document, kinds, result.Keys.ToHashSet())) + Add(record.ObjectId, kinds[record.ClassNumber], document.ReadDirectoryPayload(block)); + return result; + + void Add(Guid id, Guid type, byte[]? payload) + { + if (payload is not { Length: >= 16 } || new Guid(payload.AsSpan(0, 16)) != type) return; + if (!result.TryAdd(id, payload) && !payload.AsSpan().SequenceEqual(result[id])) + result[id] = null; + } + } +} diff --git a/src/PlaIO/Internal/ElementReader.Properties.cs b/src/PlaIO/Internal/ElementReader.Properties.cs new file mode 100644 index 0000000..3b2b1f2 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Properties.cs @@ -0,0 +1,226 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid PropertyGroupClass = new("e9cdf1dc-9117-46b6-bd32-5adba41a52c2"); + private static readonly Guid PropertyDefinitionClass = new("1f11a777-d5f5-4336-9b5a-963800153712"); + private static readonly Guid PropertyGroupLink = new("6f061922-6cfd-40c7-bb63-bcb4ed6c577a"); + private static readonly Guid PropertyAvailabilityLink = new("b0b13d7f-53e9-444e-81aa-a11e9b3227fd"); + private static readonly Guid PropertyOverrideLink = new("6d8a4425-a61e-4dd0-8978-9f90fac91e16"); + private static readonly Guid ScalarPropertyType = new("512896ad-f784-49fb-b45e-b741e45ccc7a"); + private static readonly Guid EnumPropertyType = new("87fecb96-0931-4ca1-a911-ac6ba507502a"); + private static readonly Guid IntegerPropertyValue = new("bea7c323-acfb-4de4-83fa-22f8439fb713"); + private static readonly Guid RealPropertyValue = new("e0bf337e-40c2-43c4-86e5-fb8f2186d7f1"); + private static readonly Guid TextPropertyValue = new("b0485a4f-f7a8-4798-a06a-8efa6ec97e59"); + private static readonly Guid BooleanPropertyValue = new("a2ce25b9-2c60-4852-8ac0-62fefe90d34f"); + private static readonly Guid SingleEnumPropertyValue = new("7f8ba35b-ed11-4752-aff1-d4bcf0a0317d"); + private static readonly Guid MultiEnumPropertyValue = new("deb5c8a0-7fd8-4428-a1d4-1ef876cbf0be"); + + internal static PlaPropertyCatalog ReadPropertyCatalog(PlaDocument document, IReadOnlyList classes, + Dictionary? overrideOwners = null) + { + var kinds = classes.Where(c => c.Guid == PropertyGroupClass || c.Guid == PropertyDefinitionClass) + .ToDictionary(c => c.Number, c => c.Guid); + if (kinds.Count == 0) return new PlaPropertyCatalog([], []); + var groups = new List(); + var definitions = new List(); + var groupMembership = new Dictionary(); + foreach (var (id, body) in ReadClassRecords(document, kinds).OrderBy(pair => pair.Key)) + { + bool isGroup = new Guid(body.AsSpan(0, 16)) == PropertyGroupClass; + var fields = ReadPropertyRecord(body, isGroup, out var relationships); + if (fields.IsEmpty) continue; + string name = ReadFramedText(ref fields); + string description = ReadFramedText(ref fields); + if (isGroup) + { + if (fields.Length != 1 || fields[0] > 1) + throw new InvalidDataException("A property group has an invalid field frame."); + groups.Add(new PlaPropertyGroup(id, name)); + ReadPropertyLinks(relationships, true, out var members, out _, out _); + foreach (var member in members) + if (!groupMembership.TryAdd(member, id)) + throw new InvalidDataException("A property definition has conflicting group membership."); + } + else + { + ReadPropertyLinks(relationships, false, out var owners, out var availability, out var overrides); + if (owners.Length != 1) + throw new InvalidDataException("A property definition is missing its group."); + var (type, choices, value) = ReadPropertyType(fields); + definitions.Add(new PlaPropertyDefinition(id, owners[0], name, description, type, + Array.AsReadOnly(availability), choices, value)); + if (overrideOwners is null) continue; + foreach (Guid target in overrides) + if (!overrideOwners.TryAdd(target, id)) + throw new InvalidDataException("A property override has conflicting definitions."); + } + } + foreach (var definition in definitions) + if (groupMembership.GetValueOrDefault(definition.Guid) != definition.GroupGuid) + throw new InvalidDataException("A property group and its definition have conflicting links."); + if (groupMembership.Count != definitions.Count) + throw new InvalidDataException("A property group has an unreadable definition."); + return new PlaPropertyCatalog(groups.AsReadOnly(), definitions.AsReadOnly()); + } + + private static ReadOnlySpan ReadPropertyRecord(ReadOnlySpan body, bool isGroup, + out ReadOnlySpan relationships) + { + relationships = default; + int versionOffset = isGroup ? 45 : 41; + int fieldOffset = isGroup ? 61 : 57; + if (body.Length < fieldOffset || BinaryPrimitives.ReadUInt16LittleEndian(body[39..]) != (isGroup ? 0x0102 : 3) || + body[versionOffset] is not (0x82 or 0x83) || !body[(versionOffset + 1)..].StartsWith(RecordFrameTail)) + return default; + var fields = ReadRecordFields(body, fieldOffset, out relationships); + if (isGroup && BinaryPrimitives.ReadUInt32LittleEndian(body[41..]) != fields.Length + 16) + throw new InvalidDataException("A property group has an invalid nested frame size."); + return fields; + } + + private static void ReadPropertyLinks(ReadOnlySpan data, bool isGroup, out Guid[] members, + out Guid[] availability, out Guid[] overrides) + { + Guid[]? groupTargets = null, classTargets = null, overrideTargets = null; + while (data.Length >= 17) + { + var targets = ReadRelationshipEntry(ref data, out byte tag, out Guid key); + if (key == PropertyGroupLink) + { + if (groupTargets is not null || (isGroup ? tag is not (1 or 0x11) : tag != 0x12)) + throw new InvalidDataException("A property record has conflicting group links."); + groupTargets = ReadRelationshipTargets(targets); + } + if (key == PropertyAvailabilityLink && !isGroup) + { + if (classTargets is not null || tag is not (1 or 0x11)) + throw new InvalidDataException("A property definition has conflicting availability links."); + classTargets = ReadRelationshipTargets(targets); + } + if (key == PropertyOverrideLink && !isGroup) + { + if (overrideTargets is not null || tag is not (1 or 0x11)) + throw new InvalidDataException("A property definition has conflicting override links."); + overrideTargets = ReadRelationshipTargets(targets); + } + } + CheckRelationshipEnd(data); + members = groupTargets ?? []; + availability = classTargets ?? []; + overrides = overrideTargets ?? []; + } + + private static (string? Type, IReadOnlyList? Choices, PlaPropertyValue? Default) + ReadPropertyType(ReadOnlySpan data) + { + if (data.Length < 17 || data[^1] > 1) + throw new InvalidDataException("A property definition has an invalid type frame."); + var encoding = new Guid(data[..16]); + data = data[16..^1]; + if (encoding == EnumPropertyType) return ReadPropertyChoices(data); + if (encoding != ScalarPropertyType || data.Length < 10 || + BinaryPrimitives.ReadUInt16LittleEndian(data) != 1 || + !data[6..10].SequenceEqual(new byte[] { 0, 0, 1, 0 })) return default; + int kind = BinaryPrimitives.ReadUInt16LittleEndian(data[2..]); + int unit = BinaryPrimitives.ReadUInt16LittleEndian(data[4..]); + string? type = (kind, unit) switch + { + (1, 0) => "integer", + (2, 0) => "number", + (2, 1) => "length", + (2, 2) => "area", + (2, 3) => "volume", + (3, 0) => "string", + (4, 0) => "boolean", + _ => null, + }; + return (type, null, type is null ? null : ReadPropertyDefault(data[10..], PropertyValueClass(type))); + } + + private static (string? Type, IReadOnlyList? Choices, PlaPropertyValue? Default) + ReadPropertyChoices(ReadOnlySpan data) + { + ReadOnlySpan header = [2, 0, 2, 0, 1, 0, 3, 0, 1, 0]; + if (!data.StartsWith(header) || data.Length < 14) return default; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(data[10..]); + data = data[14..]; + if (count > data.Length / 47) throw new InvalidDataException("An enumeration's choices are truncated."); + var choices = new List((int)count); + var keys = new HashSet(); + for (int i = 0; i < count; i++) + { + if (data.Length < 47 || data[0] != 2 || new Guid(data[17..33]) != TextPropertyValue || + !data[33..41].SequenceEqual(new byte[] { 2, 0, 2, 0, 0, 0, 0, 0 })) + throw new InvalidDataException("An enumeration choice has an invalid text frame."); + var id = ReadRelationshipTarget(data[1..17]); + if (!keys.Add(id)) throw new InvalidDataException("An enumeration repeats a choice GUID."); + data = data[41..]; + choices.Add(new PlaPropertyChoice(id, ReadFramedText(ref data))); + } + if (data.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 1) + throw new InvalidDataException("An enumeration is missing its choice index."); + uint indexCount = BinaryPrimitives.ReadUInt32LittleEndian(data[2..]); + data = data[6..]; + if (indexCount > data.Length / 16) throw new InvalidDataException("An enumeration's choice index is truncated."); + data = data[((int)indexCount * 16)..]; + if (data.Length < 13 || !data[..6].SequenceEqual(new byte[] { 1, 0, 0, 0, 0, 0 }) || + !data[7..13].SequenceEqual(new byte[] { 0, 0, 0, 0, 1, 0 }) || data[6] > 1) + return (null, choices.AsReadOnly(), null); + bool multiple = data[6] == 1; + var value = ReadPropertyDefault(data[13..], multiple ? MultiEnumPropertyValue : SingleEnumPropertyValue); + if (value?.Value is Guid selected && !keys.Contains(selected)) + throw new InvalidDataException("An enumeration's default points to a missing choice."); + return (multiple ? "multiEnum" : "singleEnum", choices.AsReadOnly(), value); + } + + private static Guid PropertyValueClass(string? type) => type switch + { + "integer" => IntegerPropertyValue, + "number" or "length" or "area" or "volume" => RealPropertyValue, + "string" => TextPropertyValue, + "boolean" => BooleanPropertyValue, + "singleEnum" => SingleEnumPropertyValue, + "multiEnum" => MultiEnumPropertyValue, + _ => Guid.Empty, + }; + + private static PlaPropertyValue? ReadPropertyDefault(ReadOnlySpan data, Guid valueClass) + { + if (data.Length >= 29 && data[..4].SequenceEqual(new byte[] { 2, 0, 2, 0 }) && + BinaryPrimitives.ReadUInt32LittleEndian(data[4..]) is > 0 && + data[8..13].SequenceEqual(new byte[] { 1, 0, 1, 1, 0 })) + return new PlaPropertyValue("expression", null); + if (data.Length < 18 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 1 || + new Guid(data[2..18]) != valueClass) + return null; + return ReadPropertyValue(data[18..], valueClass); + } + + private static PlaPropertyValue? ReadPropertyValue(ReadOnlySpan data, Guid valueClass) + { + if (data.Length < 8 || !data[..4].SequenceEqual(new byte[] { 2, 0, 2, 0 })) + return null; + uint status = BinaryPrimitives.ReadUInt32LittleEndian(data[4..]); + data = data[8..]; + if (status == 3 && data.IsEmpty) return new PlaPropertyValue("userUndefined", null); + if (status != 0) return null; + object? value = null; + if (valueClass == IntegerPropertyValue && data.Length == 4) + value = BinaryPrimitives.ReadInt32LittleEndian(data); + else if (valueClass == RealPropertyValue && data.Length == 8 && + double.IsFinite(BinaryPrimitives.ReadDoubleLittleEndian(data))) + value = BinaryPrimitives.ReadDoubleLittleEndian(data); + else if (valueClass == TextPropertyValue) + { + var text = ReadFramedText(ref data); + if (data.IsEmpty) value = text; + } + else if (valueClass == SingleEnumPropertyValue && data.Length == 16) + value = ReadRelationshipTarget(data); + return value is null ? null : new PlaPropertyValue("normal", value); + } +} diff --git a/src/PlaIO/Internal/ElementReader.PropertyOverrides.cs b/src/PlaIO/Internal/ElementReader.PropertyOverrides.cs new file mode 100644 index 0000000..46e86a2 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.PropertyOverrides.cs @@ -0,0 +1,73 @@ +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid PropertyOverrideClass = new("8dd49051-b081-4f20-a4a7-f6375145640d"); + private static readonly Guid ElementPropertyOverrideLink = new("7306b00e-ff8d-4051-a8b3-f76cfc597704"); + + private static void ReadPropertyOverrideRecords(ReadOnlySpan pool, List records, + Dictionary overrides) + { + foreach (var record in records) + { + var body = ReadIndexedPayload(pool, record); + if (body is null || body.Length < 46 || new Guid(body.AsSpan(0, 16)) != PropertyOverrideClass || + !body.AsSpan(39, 7).SequenceEqual(new byte[] { 2, 0, 1, 0, 3, 0, 0 })) + continue; + var fields = ReadRecordFields(body, 46, out var relationships); + if (fields.Length < 16) throw new InvalidDataException("A property override is missing its value class."); + var valueClass = new Guid(fields[..16]); + Guid element = Guid.Empty, definition = Guid.Empty; + while (relationships.Length >= 17) + { + var targets = ReadRelationshipEntry(ref relationships, out byte tag, out Guid role); + if (role == ElementPropertyOverrideLink) + { + if (tag != 0x12 || element != Guid.Empty) + throw new InvalidDataException("A property override has conflicting element links."); + element = ReadRelationshipTarget(targets); + } + else if (role == PropertyOverrideLink) + { + if (tag != 0x12 || definition != Guid.Empty) + throw new InvalidDataException("A property override has conflicting definition links."); + definition = ReadRelationshipTarget(targets); + } + } + CheckRelationshipEnd(relationships); + if (element == Guid.Empty || definition == Guid.Empty) continue; + var value = new SavedPropertyOverride(element, definition, valueClass, ReadPropertyValue(fields[16..], valueClass)); + if (!overrides.TryAdd(record.ObjectId, value) && overrides[record.ObjectId] != value) + throw new InvalidDataException("A property override has conflicting records."); + } + } + + private static Dictionary> ReadPropertyOverrides(PlaDocument document, + IReadOnlyList classes, Dictionary elements, + Dictionary records) + { + if (records.Count == 0) return []; + var owners = new Dictionary(); + var definitions = ReadPropertyCatalog(document, classes, owners).Definitions.ToDictionary(d => d.Guid); + var byElement = new Dictionary>(); + foreach (var (id, record) in records) + { + if (!elements.ContainsKey(record.Element) || !owners.TryGetValue(id, out var owner) || + owner != record.Definition || !definitions.TryGetValue(owner, out var definition)) + continue; + if (!byElement.TryGetValue(record.Element, out var entries)) byElement.Add(record.Element, entries = []); + var value = record.ValueClass == PropertyValueClass(definition.DataType) ? record.Value : null; + if (value?.Value is Guid choice && definition.Choices?.Any(o => o.Guid == choice) != true) + value = null; + var entry = new PlaPropertyOverride(owner, value); + if (!entries.TryAdd(owner, entry) && entries[owner] != entry) + throw new InvalidDataException("An element has conflicting overrides of the same property."); + } + return byElement.ToDictionary(pair => pair.Key, + pair => (IReadOnlyList)pair.Value.Values.OrderBy(v => v.DefinitionGuid).ToList().AsReadOnly()); + } + + private readonly record struct SavedPropertyOverride(Guid Element, Guid Definition, Guid ValueClass, PlaPropertyValue? Value); +} diff --git a/src/PlaIO/Internal/ElementReader.RecordFields.cs b/src/PlaIO/Internal/ElementReader.RecordFields.cs new file mode 100644 index 0000000..42ae689 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.RecordFields.cs @@ -0,0 +1,99 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static ReadOnlySpan RecordFrameTail => [0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + private static Dictionary ReadClassRecords(PlaDocument document, Dictionary kinds) + { + var records = new Dictionary(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || block.Version != 1 || block.Guid is not { } id || id == Guid.Empty || + !kinds.TryGetValue(block.Kind, out var type)) continue; + var body = block.Mode == PlaBlockMode.Lz ? document.ReadStandalonePayload(block) : + document.PayloadStartsWithClass(block, type) ? document.ReadPayload(block) : null; + Add(id, type, body); + } + foreach (var (record, block) in FindUnindexedAttributeBlocks(document, kinds, records.Keys.ToHashSet())) + Add(record.ObjectId, kinds[record.ClassNumber], document.ReadDirectoryPayload(block)); + return records; + + void Add(Guid id, Guid type, byte[]? body) + { + if (body is null || body.Length < 35 || new Guid(body.AsSpan(0, 16)) != type) return; + if (!records.TryAdd(id, body) && + (!body.AsSpan(0, 16).SequenceEqual(records[id].AsSpan(0, 16)) || + !body.AsSpan(35).SequenceEqual(records[id].AsSpan(35)))) + throw new InvalidDataException($"Record {id} has conflicting copies."); + } + } + + private static ReadOnlySpan ReadRecordFields(ReadOnlySpan body, int fieldStart, + out ReadOnlySpan relationships) + { + uint size = BinaryPrimitives.ReadUInt32LittleEndian(body[35..]); + if (size <= fieldStart - 39 || size > body.Length - 46) + throw new InvalidDataException("The field frame has an invalid length."); + int relationOffset = 39 + (int)size; + var tail = body[relationOffset..]; + if (BinaryPrimitives.ReadUInt32LittleEndian(tail) != tail.Length - 4 || + BinaryPrimitives.ReadUInt16LittleEndian(tail[4..]) != 1) + throw new InvalidDataException("The relationship frame is invalid."); + relationships = tail[6..]; + return body[fieldStart..relationOffset]; + } + + private static string ReadFramedText(ref ReadOnlySpan fields) + { + if (fields.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(fields) != 1 || + ReadCountedUnicode(fields[2..], out int consumed) is not { } value) + throw new InvalidDataException("A framed text field is invalid."); + fields = fields[(2 + consumed)..]; + return value; + } + + private static ReadOnlySpan ReadRelationshipEntry(ref ReadOnlySpan data, out byte tag, out Guid key) + { + tag = data[0]; + key = new Guid(data[1..17]); + data = data[17..]; + uint count = 1; + if (tag is 1 or 2 && data.Length >= 4) + { + count = BinaryPrimitives.ReadUInt32LittleEndian(data); + data = data[4..]; + } + else if (tag is not (0x11 or 0x12)) + throw new InvalidDataException("A relationship has an invalid tag."); + if (count > data.Length / 16) + throw new InvalidDataException("A relationship is truncated."); + var targets = data[..((int)count * 16)]; + data = data[targets.Length..]; + return targets; + } + + private static void CheckRelationshipEnd(ReadOnlySpan data) + { + if (data.Length != 1 || data[0] != 0) + throw new InvalidDataException("The relationship frame has an invalid terminator."); + } + + private static Guid ReadRelationshipTarget(ReadOnlySpan target) + { + var id = new Guid(target); + if (id == Guid.Empty) throw new InvalidDataException("A relationship has an empty target."); + return id; + } + + private static Guid[] ReadRelationshipTargets(ReadOnlySpan targets) + { + var ids = new Guid[targets.Length / 16]; + for (int i = 0; i < ids.Length; i++) + ids[i] = ReadRelationshipTarget(targets.Slice(16 * i, 16)); + return ids; + } +} diff --git a/src/PlaIO/Internal/ElementReader.SlabArcs.cs b/src/PlaIO/Internal/ElementReader.SlabArcs.cs new file mode 100644 index 0000000..0e9aa73 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabArcs.cs @@ -0,0 +1,230 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private readonly record struct SlabEdge(PlaPlanPoint Start, PlaPlanPoint End, double Sweep, + PlaPlanPoint Center = default, double Radius = 0) + { + public PlaPlanPoint AtAngle(double angle) => new(Center.X + Radius * Math.Cos(angle), Center.Y + Radius * Math.Sin(angle)); + + public bool IncludesAngle(double angle) + { + double start = Math.Atan2(Start.Y - Center.Y, Start.X - Center.X); + double travel = Math.IEEERemainder(Math.Sign(Sweep) * (angle - start), Math.Tau); + if (travel < 0) travel += Math.Tau; + double tolerance = JunctionTolerance / Radius; + return travel <= Math.Abs(Sweep) + tolerance || Math.Tau - travel <= tolerance; + } + + public bool IncludesDirection(PlaPlanPoint point) => IncludesAngle(Math.Atan2(point.Y - Center.Y, point.X - Center.X)); + } + + private static PlaSlabGeometry? ReadCurvedSlabGeometry(ReadOnlySpan polygon, PlaBoundingBox box) + { + int points = BinaryPrimitives.ReadInt32LittleEndian(polygon[43..]); + int arcCount = BinaryPrimitives.ReadInt32LittleEndian(polygon[47..]); + int ringCount = BinaryPrimitives.ReadInt32LittleEndian(polygon[51..]); + if (points > 4096) return null; + + var sweeps = new Dictionary(arcCount); + int offsets = 71 + 16 * (points + 1); + for (int i = 0; i < arcCount; i++, offsets += 16) + { + int start = BinaryPrimitives.ReadInt32LittleEndian(polygon[offsets..]) - 1; + double sweep = ReadDouble(polygon, offsets + 8); + if (!(Math.Abs(sweep) is > 0 and < Math.Tau) || !sweeps.TryAdd(start, sweep)) return null; + } + + var rings = new List>(ringCount); + var boundaries = new List(ringCount); + var arcs = new List(arcCount); + double area = 0; + var bounds = (X0: double.PositiveInfinity, Y0: double.PositiveInfinity, + X1: double.NegativeInfinity, Y1: double.NegativeInfinity); + int first = 0; + for (int ringIndex = 0; ringIndex < ringCount; ringIndex++) + { + int last = BinaryPrimitives.ReadInt32LittleEndian(polygon[(offsets + (ringIndex + 1) * 4)..]); + var ring = ReadSlabRing(polygon, first, last); + var edges = new SlabEdge[ring.Length]; + double signedArea = SignedRingArea(ring); + var ringArcs = new List(); + for (int i = 0; i < ring.Length; i++) + { + var p = ring[i]; + var q = ring[(i + 1) % ring.Length]; + if (p == q) return null; + Include(p); + if (!sweeps.Remove(first + i, out double sweep)) + { + edges[i] = new SlabEdge(p, q, 0); + continue; + } + + if (ReadCircularEdge(p, q, sweep, out double segmentArea) is not { } edge) return null; + edges[i] = edge; + for (int axis = 0; axis < 4; axis++) + { + double angle = axis * (Math.PI / 2); + if (edge.IncludesAngle(angle)) Include(edge.AtAngle(angle)); + } + signedArea += segmentArea; + ringArcs.Add(new PlaSlabArc(ringIndex, i, sweep)); + } + first = last; + + if (!double.IsFinite(signedArea) || signedArea == 0 || !SlabRingIsSimple(edges)) return null; + bool outer = ringIndex == 0; + if (!outer && !CurvedHoleFits(ring, edges, rings, boundaries)) return null; + + area += outer ? Math.Abs(signedArea) : -Math.Abs(signedArea); + if ((signedArea > 0) != outer) + { + Array.Reverse(ring); + ringArcs = ringArcs.Select(a => a with + { + StartVertexIndex = ring.Length - 1 - (a.StartVertexIndex + 1) % ring.Length, + SweepRadians = -a.SweepRadians, + }).OrderBy(a => a.StartVertexIndex).ToList(); + } + arcs.AddRange(ringArcs); + rings.Add(Array.AsReadOnly(ring)); + boundaries.Add(edges); + } + if (sweeps.Count != 0 || !double.IsFinite(area) || area <= 0 || + !SamePlan(bounds, box.XMin, box.YMin, box.XMax, box.YMax)) return null; + // shortcut: curved face quantities and volumes require the verified Archicad segmentation and cut geometry. + return new PlaSlabGeometry(rings.AsReadOnly(), box.ZMin, box.ZMax, area, null) { Arcs = arcs.AsReadOnly() }; + + void Include(PlaPlanPoint p) + { + bounds = (Math.Min(p.X, bounds.X0), Math.Min(p.Y, bounds.Y0), + Math.Max(p.X, bounds.X1), Math.Max(p.Y, bounds.Y1)); + } + } + + private static SlabEdge? ReadCircularEdge(PlaPlanPoint p, PlaPlanPoint q, double sweep, out double segmentArea) + { + segmentArea = 0; + double dx = q.X - p.X, dy = q.Y - p.Y; + double chord = double.Hypot(dx, dy), half = sweep * 0.5; + double radius = chord / (2 * Math.Abs(Math.Sin(half))); + double offset = 0.5 / Math.Tan(half); + var center = new PlaPlanPoint(p.X + 0.5 * dx - dy * offset, p.Y + 0.5 * dy + dx * offset); + if (!double.IsFinite(radius) || radius <= 0 || !double.IsFinite(center.X) || !double.IsFinite(center.Y)) + return null; + // Near zero the series avoids subtracting almost equal sine and angle values. + segmentArea = Math.Abs(sweep) < 1e-3 + ? chord * chord * (sweep / 12 + sweep * sweep * sweep / 360) + : radius * radius * (sweep - Math.Sin(sweep)) * 0.5; + return new SlabEdge(p, q, sweep, center, radius); + } + + private static bool CurvedHoleFits(IReadOnlyList ring, SlabEdge[] edges, + List> rings, List boundaries) + { + if (!CurvedRingContainsPoint(rings[0], boundaries[0], ring[0])) return false; + for (int i = 0; i < boundaries.Count; i++) + { + if (i > 0 && (CurvedRingContainsPoint(rings[i], boundaries[i], ring[0]) || + CurvedRingContainsPoint(ring, edges, rings[i][0]))) return false; + foreach (var edge in edges) + foreach (var other in boundaries[i]) + if (SlabEdgesIntersect(edge, other, null)) return false; + } + return true; + } + + private static bool SlabRingIsSimple(SlabEdge[] edges) + { + for (int i = 0; i < edges.Length; i++) + for (int j = i + 1; j < edges.Length; j++) + { + PlaPlanPoint? shared = j == i + 1 ? edges[i].End : i == 0 && j == edges.Length - 1 ? edges[i].Start : null; + if (SlabEdgesIntersect(edges[i], edges[j], shared)) return false; + } + return true; + } + + private static bool CurvedRingContainsPoint(IReadOnlyList ring, SlabEdge[] edges, PlaPlanPoint point) + { + bool inside = ContainsPoint(ring, point); + foreach (var edge in edges) + { + if (edge.Sweep == 0 || double.Hypot(point.X - edge.Center.X, point.Y - edge.Center.Y) >= edge.Radius) continue; + double side = Cross(edge.Start, edge.End, point); + // The chord ray test assigns points on the chord to the right, then above for a horizontal edge. + if (side == 0) + side = edge.Start.Y == edge.End.Y ? edge.End.X - edge.Start.X : edge.Start.Y - edge.End.Y; + if (Math.Sign(edge.Sweep) * side < 0) inside = !inside; + } + return inside; + } + + private static bool SlabEdgesIntersect(SlabEdge a, SlabEdge b, PlaPlanPoint? shared) + { + if (a.Sweep == 0 && b.Sweep == 0) + { + if (shared is not { } vertex) return SegmentsIntersect(a.Start, a.End, b.Start, b.End); + var x = a.Start == vertex ? a.End : a.Start; + var y = b.Start == vertex ? b.End : b.Start; + return Cross(x, vertex, y) == 0 && ((x.X - vertex.X) * (y.X - vertex.X) + (x.Y - vertex.Y) * (y.Y - vertex.Y)) > 0; + } + if (a.Sweep == 0 || b.Sweep == 0) return LineIntersectsSlabArc(a.Sweep == 0 ? a : b, a.Sweep == 0 ? b : a, shared); + + double dx = b.Center.X - a.Center.X, dy = b.Center.Y - a.Center.Y; + double distance = double.Hypot(dx, dy); + if (distance <= JunctionTolerance) + { + if (Math.Abs(a.Radius - b.Radius) > JunctionTolerance) return false; + double start = Math.Atan2(a.Start.Y - a.Center.Y, a.Start.X - a.Center.X); + return ArcContains(a, b.Start, shared) || ArcContains(a, b.End, shared) || + ArcContains(b, a.Start, shared) || ArcContains(b, a.End, shared) || + ArcContains(b, a.AtAngle(start + a.Sweep / 2), shared); + } + double ux = dx / distance, uy = dy / distance; + if (shared is { } endpoint) + { + // The second circle intersection mirrors the known common endpoint across the line of centers. + double projection = (endpoint.X - a.Center.X) * ux + (endpoint.Y - a.Center.Y) * uy; + var reflected = new PlaPlanPoint(2 * (a.Center.X + projection * ux) - endpoint.X, + 2 * (a.Center.Y + projection * uy) - endpoint.Y); + return ArcContains(a, reflected, shared) && ArcContains(b, reflected, shared); + } + if (distance > a.Radius + b.Radius + JunctionTolerance || + distance < Math.Abs(a.Radius - b.Radius) - JunctionTolerance) return false; + double along = 0.5 * (distance + (a.Radius - b.Radius) * (a.Radius + b.Radius) / distance); + double offset = Math.Sqrt(Math.Max(0, (a.Radius - along) * (a.Radius + along))); + double x0 = a.Center.X + along * ux, y0 = a.Center.Y + along * uy; + return Both(new PlaPlanPoint(x0 - offset * uy, y0 + offset * ux)) || + Both(new PlaPlanPoint(x0 + offset * uy, y0 - offset * ux)); + + bool Both(PlaPlanPoint point) => a.IncludesDirection(point) && b.IncludesDirection(point); + } + + private static bool LineIntersectsSlabArc(SlabEdge line, SlabEdge arc, PlaPlanPoint? shared) + { + double dx = line.End.X - line.Start.X, dy = line.End.Y - line.Start.Y; + double length = double.Hypot(dx, dy); + double ux = dx / length, uy = dy / length; + double x = arc.Center.X - line.Start.X, y = arc.Center.Y - line.Start.Y; + double along = x * ux + y * uy; + if (shared is { } known) + return WithinLineAndArc(2 * along - (known == line.Start ? 0 : length)); + + double across = Math.Abs(x * uy - y * ux); + if (across > arc.Radius + JunctionTolerance) return false; + double offset = Math.Sqrt(Math.Max(0, (arc.Radius - across) * (arc.Radius + across))); + return WithinLineAndArc(along - offset) || WithinLineAndArc(along + offset); + + bool WithinLineAndArc(double t) => t >= -JunctionTolerance && t <= length + JunctionTolerance && + ArcContains(arc, new PlaPlanPoint(line.Start.X + t * ux, line.Start.Y + t * uy), shared); + } + + private static bool ArcContains(SlabEdge arc, PlaPlanPoint point, PlaPlanPoint? shared) => + (shared is not { } vertex || double.Hypot(point.X - vertex.X, point.Y - vertex.Y) > JunctionTolerance) && + arc.IncludesDirection(point); +} diff --git a/src/PlaIO/Internal/ElementReader.SlabColumnCuts.cs b/src/PlaIO/Internal/ElementReader.SlabColumnCuts.cs new file mode 100644 index 0000000..45d38dc --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabColumnCuts.cs @@ -0,0 +1,208 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static double? ReadSlabStructuralLoss(ReadOnlySpan slab, ReadOnlySpan settings, Guid id, + ModelGeometry geometry, PlaBoundingBox box, IReadOnlyList> rings, + out IReadOnlyList? prisms) + { + prisms = null; + if (BinaryPrimitives.ReadUInt16LittleEndian(settings[85..]) != 1) return null; + var skins = BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) switch + { + 1 => geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(settings[73..])) + is > 0 and { } priority ? [new SlabSkin(box.ZMax - box.ZMin, priority)] : null, + 2 => geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])), + _ => null, + }; + if (skins is null || skins.Any(s => !double.IsFinite(s.Thickness) || s.Thickness <= 0 || s.Priority == 0) || + Math.Abs(skins.Sum(s => s.Thickness) - (box.ZMax - box.ZMin)) > JunctionTolerance) + return null; + uint minimum = skins.Min(s => s.Priority); + int? layer = ReadElementLocation(slab, "Slab", 0).LayerIndex; + var cuts = new List(); + IReadOnlyList>? evaluated = rings; + bool resolvedContact = false; + double removed = 0; + if (!HasSupportedSlabContacts(slab, Guid.Empty, Guid.Empty, (key, joint) => + { + if (key != SlabColumnRelation && SlabSolidContactKeepsShape(geometry, id, key, joint, minimum)) + return true; + IReadOnlyList? footprint = null; + bool resolved = key == SlabColumnRelation + ? ReadSlabColumnCut(geometry, id, layer, joint, box, skins, minimum, rings, out var cut, out double volume, out footprint) + : ReadSlabProfileWallCut(geometry, id, layer, key, joint, box, skins, rings, out cut, out volume); + if (!resolved) return false; + resolvedContact = true; + if (cut is not null) + { + // shortcut: overlapping structural cuts require a union before their volumes can be deducted. + if (cuts.Any(p => CutBoxesOverlap(p, cut))) return false; + cuts.Add(cut); + removed += volume; + evaluated = evaluated is not null && footprint is not null + ? SubtractSlabFootprint(evaluated, [footprint], volume / (box.ZMax - box.ZMin)) + : null; + } + return true; + })) return null; + if (resolvedContact && evaluated is not null) prisms = GroupSlabPrisms(evaluated); + return resolvedContact ? removed : null; + } + + private static bool ReadSlabColumnCut(ModelGeometry geometry, Guid slabId, int? slabLayer, Guid junction, + PlaBoundingBox slabBox, SlabSkin[] skins, uint minimum, IReadOnlyList> rings, + out PlaBoundingBox? cut, out double volume, out IReadOnlyList? footprint) + { + cut = null; + volume = 0; + footprint = null; + if (geometry.Read(junction, SlabColumnJunctionClass) is not { } joint || + ReadSingleRelation(joint, SlabColumnRelation, requireSection: true) != slabId) + return false; + Guid memoId = ReadSingleRelation(joint, ColumnSlabRelation, requireSection: true); + var hatch = ReadColumnContactSection(geometry, memoId, ColumnSlabRelation, junction, out var column); + if (hatch.IsEmpty || geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) + is not (> 0 and { } priority)) return false; + if (priority < minimum) return true; + + var location = ReadElementLocation(column, "Column", 0); + if (!SameIntersectionGroup(geometry, location.LayerIndex, slabLayer) || + geometry.StoryElevation(location.HomeStoryIndex) is not { } level || + !column.Slice(304, ColumnEndPlaneFrame.Length).SequenceEqual(ColumnEndPlaneFrame) || + BinaryPrimitives.ReadUInt16LittleEndian(column[368..]) != 1 || + !IsHorizontal(column[312..]) || !IsHorizontal(column[370..]) || + !(ReadDouble(column, 352) < 0 && ReadDouble(column, 410) > 0) || + !IsCorner(column[370..], ReadDouble(column, 312), ReadDouble(column, 320))) + return false; + double low = ReadDouble(column, 328) + level, high = ReadDouble(column, 386) + level; + if (!double.IsFinite(low) || !double.IsFinite(high) || high <= low) return false; + if (high <= slabBox.ZMin || low >= slabBox.ZMax) return true; + double thickness = 0, top = slabBox.ZMax; + foreach (var skin in skins) + { + double bottom = top - skin.Thickness; + if (priority >= skin.Priority) + thickness += Math.Max(0, Math.Min(top, high) - Math.Max(bottom, low)); + top = bottom; + } + if (thickness <= JunctionTolerance) return true; + + if (geometry.Read(memoId, ColumnMemoClass) is not { } memo || + ReadColumnSection(memo, ReadSingleRelation(memo, ColumnMemoRelation, requireSection: true), out var contacts) is not { } sectionId || + geometry.Read(sectionId, RectangularSectionClass) is not { } section || + ReadCenteredRectangle(section, out _) is not { } halfSize) + return false; + var settings = AfterCountedString(column, 735); + if (settings.Length < 95 || ReadDouble(settings, 28) != 0 || !double.IsFinite(ReadDouble(settings, 87))) + return false; + double centerX = ReadDouble(column, 312), centerY = ReadDouble(column, 320), angle = ReadDouble(settings, 87); + if (!double.IsFinite(centerX) || !double.IsFinite(centerY)) return false; + double cos = Math.Cos(angle), sin = Math.Sin(angle); + double x = Math.Abs(cos) * halfSize.X + Math.Abs(sin) * halfSize.Y; + double y = Math.Abs(sin) * halfSize.X + Math.Abs(cos) * halfSize.Y; + var envelope = new PlaBoundingBox(centerX - x, centerY - y, low, centerX + x, centerY + y, high); + if (!CutBoxesOverlap(slabBox, envelope)) return true; + + double area = RectangleIntersectionArea(rings, new PlaPlanPoint(centerX, centerY), angle, halfSize); + if (!double.IsFinite(area) || area < -JunctionTolerance) return false; + if (area <= 0) return true; + var band = new Elevations(Math.Max(low, slabBox.ZMin), Math.Min(high, slabBox.ZMax)); + if (contacts is not null && contacts.Any(c => !ColumnContactKeepsBand(geometry, memoId, junction, c, priority, band))) + return false; + cut = envelope with { ZMin = band.Bottom, ZMax = band.Top }; + volume = area * thickness; + if (low <= slabBox.ZMin && high >= slabBox.ZMax && skins.All(s => s.Priority <= priority)) + footprint = Array.AsReadOnly(new[] + { + Corner(-halfSize.X, -halfSize.Y), Corner(-halfSize.X, halfSize.Y), + Corner(halfSize.X, halfSize.Y), Corner(halfSize.X, -halfSize.Y), + }); + return double.IsFinite(volume); + + PlaPlanPoint Corner(double u, double v) => new(centerX + (cos * u - sin * v), centerY + (sin * u + cos * v)); + } + + private static bool ColumnContactKeepsBand(ModelGeometry geometry, Guid column, Guid activeJunction, + (Guid Key, Guid Id) contact, uint priority, Elevations band) + { + if (contact.Key == ColumnSlabRelation && contact.Id == activeJunction) return true; + var (kind, relation) = contact.Key == ColumnBeamRelation ? (BeamColumnJunctionClass, BeamColumnRelation) : + contact.Key == ColumnWallRelation ? (WallColumnJunctionClass, WallColumnRelation) : (SlabColumnJunctionClass, SlabColumnRelation); + if (geometry.Read(contact.Id, kind) is not { } joint || + ReadSingleRelation(joint, contact.Key, requireSection: true) != column) return false; + Guid peer = ReadSingleRelation(joint, relation, requireSection: true); + if (contact.Key == ColumnBeamRelation) + { + if (ReadBeamPriority(geometry, peer, contact.Id) is > 0 and { } beamPriority && beamPriority <= priority) + return true; + return geometry.Read(peer, BeamMemoClass) is { } memo && HasGeometryRelation(memo, relation, contact.Id) && + ReadBeamPrism(geometry, peer, memo, 0) is { } beam && + BeamSectionElevations(beam, ReadBeamHatch(geometry, peer, memo)) is { } height && + DisjointHeights(height.Bottom, height.Top, band); + } + bool isWall = contact.Key == ColumnWallRelation; + if (geometry.Read(peer, isWall ? WallClass : SlabClass) is not { } body || + !HasGeometryRelation(body, relation, contact.Id)) return false; + var record = body.AsSpan(FindClassFrame(body, isWall ? WallClass : SlabClass)); + var location = ReadElementLocation(record, isWall ? "Wall" : "Slab", 0); + if (isWall && ReadWallPriority(geometry, peer, body) is > 0 and { } wallPriority && wallPriority <= priority) + return true; + if (!isWall && ReadSlabPriority(AfterCountedString(record, ClassElementIdOffset("Slab")), geometry.Attributes) + is > 0 and { } slabPriority && slabPriority <= priority) return true; + if (isWall) return false; + return ReadElevations(record, "Slab") is { } slab && geometry.StoryElevation(location.HomeStoryIndex) is { } level && + DisjointHeights(slab.Bottom + level, slab.Top + level, band); + } + + private static bool CutBoxesOverlap(PlaBoundingBox a, PlaBoundingBox b) => + a.XMin < b.XMax && a.XMax > b.XMin && a.YMin < b.YMax && a.YMax > b.YMin && a.ZMin < b.ZMax && a.ZMax > b.ZMin; + + private static double RectangleIntersectionArea(IReadOnlyList> rings, PlaPlanPoint center, + double angle, (double X, double Y) halfSize) + { + double sin = Math.Sin(angle), cos = Math.Cos(angle), area = 0; + foreach (var ring in rings) + { + var points = new List(ring.Count); + foreach (var p in ring) + { + double x = p.X - center.X, y = p.Y - center.Y; + points.Add(new PlaPlanPoint(cos * x + sin * y, cos * y - sin * x)); + } + points = ClipHalfPlane(points, xAxis: true, halfSize.X, keepBelow: true); + points = ClipHalfPlane(points, xAxis: true, -halfSize.X, keepBelow: false); + points = ClipHalfPlane(points, xAxis: false, halfSize.Y, keepBelow: true); + points = ClipHalfPlane(points, xAxis: false, -halfSize.Y, keepBelow: false); + for (int i = 1; i < points.Count - 1; i++) + area += Cross(points[0], points[i], points[i + 1]) / 2; + } + return area; + } + + private static List ClipHalfPlane(List points, bool xAxis, double limit, bool keepBelow) + { + if (points.Count == 0) return points; + var result = new List(points.Count + 2); + var last = points[^1]; + double a = (xAxis ? last.X : last.Y) - limit; + foreach (var point in points) + { + double b = (xAxis ? point.X : point.Y) - limit; + bool aInside = keepBelow ? a <= 0 : a >= 0, bInside = keepBelow ? b <= 0 : b >= 0; + if (aInside != bInside) + { + double t = a / (a - b); + result.Add(xAxis ? new PlaPlanPoint(limit, last.Y + t * (point.Y - last.Y)) : + new PlaPlanPoint(last.X + t * (point.X - last.X), limit)); + } + if (bInside) result.Add(point); + last = point; + a = b; + } + return result; + } +} diff --git a/src/PlaIO/Internal/ElementReader.SlabCuts.cs b/src/PlaIO/Internal/ElementReader.SlabCuts.cs new file mode 100644 index 0000000..35cd8f0 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabCuts.cs @@ -0,0 +1,424 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid BeamSlabJunctionClass = new("7259c45f-97e3-434a-bc9e-fe3bcf980947"); + private static readonly Guid SlabBeamRelation = new("d50bcd56-a71c-40f8-a3f1-551d14a4762b"); + private static readonly Guid BeamSlabRelation = new("4df5ee09-8368-4f3b-ad64-056115b4c0ab"); + private static readonly Guid SlabLevelDimensionClass = new("690878fa-b11f-46c9-953c-3864d85bdee6"); + private static readonly Guid SlabLevelDimensionRelation = new("9176a8c6-f502-440f-8ef3-f0a700178e4a"); + + private static WallStrip? ReadJoinedWallStrip(ModelGeometry geometry, Guid wallId, WallStrip strip, ElementLocation location) + { + if (geometry.Read(wallId, WallClass) is not { } wall) return null; + int start = FindRelationshipSection(wall, wall.Length); + if (start < 0) return null; + ReadOnlySpan relations = wall.AsSpan(start); + var expanded = strip; + while (relations.Length >= 17) + { + var entry = relations; + if (!TryReadGeometryRelation(ref relations, out byte tag, out Guid key, out _)) return null; + if (key != FirstWallEndRelation && key != SecondWallEndRelation) continue; + if (tag is not (1 or 0x11)) return null; + var ids = ReadRelationIds(entry, relations, tag); + for (int i = 0; i < ids.Length; i += 16) + { + var id = new Guid(ids.Slice(i, 16)); + if (geometry.Read(id, WallWallJunctionClass) is not { } joint || + ReadWallJunctionPeers(joint, wallId, key) is not { } peers || + ReadWallJunctionStation(geometry, joint, strip, WallCapPlanClearance) is not { } station) + return null; + var (along, across) = station; + foreach (var (relation, neighborId) in peers) + { + if (geometry.Read(neighborId, WallClass) is not { } neighbor || + !HasGeometryRelation(neighbor, relation, id)) return null; + var record = neighbor.AsSpan(FindClassFrame(neighbor, WallClass)); + var other = AfterCountedString(record, 197); + var contour = ReadWallContour(geometry, record, neighborId); + (double X0, double Y0, double X1, double Y1)? inline = null; + if (contour is null && HasEmptyWallPlanCache(other)) ReadWallReferencePlan(other, out inline); + if (!SameIntersectionGroup(geometry, location.LayerIndex, ReadElementLocation(record, "Wall", 0).LayerIndex)) + return null; + if (ReadWallStrip(other, contour, inline) is not { } peer) + { + if (Math.Abs(across - strip.Line) > JunctionTolerance || ReadWallReferencePlan(other, out _) is not { } plan || + CrossingWallInterval(strip, plan, station) is not { } interval) return null; + expanded = expanded with { Start = Math.Min(expanded.Start, interval.Start), End = Math.Max(expanded.End, interval.End) }; + continue; + } + if (peer.AlongX == strip.AlongX) + { + // A collinear butt ends at the common station even when the face offsets differ. + if (!(AreCollinearWallEnds(strip, peer) && PointOnStrip(peer, along, across)) && + !WallButtAtStation(strip, peer, station)) + return null; + continue; + } + if (Math.Abs(across - strip.Line) > JunctionTolerance || !PointOnStrip(peer, across, along)) return null; + // Perpendicular cleanup may extend the wall along its axis as far as the peer's outer face. + expanded = expanded with { Start = Math.Min(expanded.Start, peer.AcrossMin), End = Math.Max(expanded.End, peer.AcrossMax) }; + } + } + } + return relations is [0] ? expanded : null; + + static bool PointOnStrip(WallStrip s, double along, double across) => + Math.Abs(across - s.Line) <= JunctionTolerance && along >= s.Start - JunctionTolerance && along <= s.End + JunctionTolerance; + } + + private static (double Along, double Across)? ReadWallJunctionStation(ModelGeometry geometry, ReadOnlySpan joint, + WallStrip strip, double acrossTolerance = JunctionTolerance) + { + Guid pointId = ReadSingleRelation(joint, WallJunctionPointRelation, requireSection: true); + if (geometry.Read(pointId, WallJunctionPointClass) is not { Length: >= 62 } point) return null; + double along = ReadDouble(point, strip.AlongX ? 46 : 54), across = ReadDouble(point, strip.AlongX ? 54 : 46); + return Math.Abs(across - strip.Line) <= acrossTolerance && + along >= strip.Start - JunctionTolerance && along <= strip.End + JunctionTolerance ? (along, across) : null; + } + + private static bool WallButtAtStation(WallStrip a, WallStrip b, (double Along, double Across) station) + { + if (Math.Abs(a.Line - b.Line) > WallCapPlanClearance || + Math.Abs(station.Across - b.Line) > WallCapPlanClearance || + Math.Min(a.AcrossMax, b.AcrossMax) <= Math.Max(a.AcrossMin, b.AcrossMin)) return false; + // Both rectangular prisms terminate at the saved joint station. Only their transverse coordinates can differ. + return AtEnd(a.Start) && AtEnd(b.End) || AtEnd(a.End) && AtEnd(b.Start); + + bool AtEnd(double end) => Math.Abs(end - station.Along) <= JunctionTolerance; + } + + private static (double Start, double End)? CrossingWallInterval(WallStrip strip, PlaWallReferencePlan peer, + (double Along, double Across) station) + { + double dx = peer.End.X - peer.Start.X, dy = peer.End.Y - peer.Start.Y, length = double.Hypot(dx, dy); + double x = (strip.AlongX ? station.Along : station.Across) - peer.Start.X; + double y = (strip.AlongX ? station.Across : station.Along) - peer.Start.Y; + double at = (x * dx + y * dy) / length, offset = (x * dy - y * dx) / length; + double along = (strip.AlongX ? dy : -dx) / length, across = (strip.AlongX ? -dx : dy) / length; + if (Math.Abs(along) <= JunctionTolerance || Math.Abs(offset) > JunctionTolerance || + at < -JunctionTolerance || at > length + JunctionTolerance) return null; + + // Project the intersection of the two wall strips onto the target wall's axis. + double a = (strip.AcrossMin - station.Across) * across, b = (strip.AcrossMax - station.Across) * across; + double first = (Math.Min(peer.OutsideOffset, peer.InsideOffset) - offset - Math.Max(a, b)) / along; + double last = (Math.Max(peer.OutsideOffset, peer.InsideOffset) - offset - Math.Min(a, b)) / along; + return (station.Along + Math.Min(first, last), station.Along + Math.Max(first, last)); + } + + private static List<(Guid Relation, Guid Owner)>? ReadWallJunctionPeers(ReadOnlySpan joint, Guid wall, Guid ownRelation) + { + int start = FindRelationshipSection(joint, joint.Length); + if (start < 0) return null; + var data = joint[start..]; + var peers = new List<(Guid Relation, Guid Owner)>(); + bool found = false; + while (data.Length >= 17) + { + var entry = data; + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out _)) return null; + if (tag == 0x12 && key == WallJunctionPointRelation) continue; + if (tag is not (2 or 0x12) || key != FirstWallEndRelation && key != SecondWallEndRelation) return null; + var ids = ReadRelationIds(entry, data, tag); + for (int i = 0; i < ids.Length; i += 16) + { + var owner = new Guid(ids.Slice(i, 16)); + if (owner == wall) + { + if (key != ownRelation || found) return null; + found = true; + } + else + { + if (owner == Guid.Empty || peers.Exists(p => p.Owner == owner)) return null; + peers.Add((key, owner)); + } + } + } + return found && peers.Count != 0 && data is [0] ? peers : null; + } + + private static bool SlabContactKeepsCuttingBand(ModelGeometry geometry, Guid slab, Guid key, Guid id, uint wallPriority, + double home, (double X0, double Y0, double X1, double Y1) footprint, Elevations band) + { + if (key == WallLabelRelation) return geometry.SlabLabelIsMetadata(slab, id, key); + if (key == ElementPropertyOverrideLink) + return geometry.Read(id, PropertyOverrideClass) is { } property && + ReadSingleRelation(property, key, requireSection: true) == slab; + if (key == CutElementRelation || key == OpeningHostRelation) + return SlabOpeningMissesStrip(geometry, slab, key, id, footprint, home, band); + if (key == SlabLevelDimensionRelation) + return geometry.Read(id, SlabLevelDimensionClass) is { } dimension && + ReadSingleRelation(dimension, key, requireSection: true) == slab; + bool wallContact = key == SlabWallRelation || key == AlternateSlabWallRelation; + if (wallContact) + { + // An equal-priority wall cannot remove the slab skins that cut the target wall. + return ReadSlabWallPeer(geometry, slab, key, id, out Guid wall) is { } other && + ReadWallPriority(geometry, wall, other) is { } priority && (priority <= wallPriority || + SlabContactWallMissesStrip(geometry, wall, other, footprint, home, band)); + } + var (type, ownerRelation) = key == SlabBeamRelation ? (BeamSlabJunctionClass, BeamSlabRelation) : + key == SlabColumnRelation ? (SlabColumnJunctionClass, ColumnSlabRelation) : default; + if (geometry.Read(id, type) is not { } junction || + ReadSingleRelation(junction, key, requireSection: true) != slab) return false; + Guid owner = ReadSingleRelation(junction, ownerRelation, requireSection: true); + if (key == SlabColumnRelation) + return SlabColumnMissesWall(geometry, owner, id, wallPriority, home, footprint, band); + + if (geometry.Read(owner, BeamMemoClass) is not { } memo || !HasGeometryRelation(memo, ownerRelation, id)) return false; + var hatch = ReadBeamHatch(geometry, owner, memo); + if (hatch.IsEmpty || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } beamPriority) + return false; + if (beamPriority < wallPriority) return true; + if (ReadBeamPrism(geometry, owner, memo, home) is not { } beam || BeamSectionExtents(beam, hatch) is not { } section) return false; + if (DisjointHeights(section.Height.Bottom, section.Height.Top, band)) return true; + var (left, right) = ProjectRectangle(footprint, beam.X, beam.Y, beam.Dy, -beam.Dx); + if (right <= section.Left + JunctionTolerance || left >= section.Right - JunctionTolerance) return true; + var (from, to) = ProjectRectangle(footprint, beam.X, beam.Y, beam.Dx, beam.Dy); + var rectangle = ReadBeamRectangle(hatch); + return (to <= JunctionTolerance || from >= beam.Length - JunctionTolerance) && + HasOnlyBeamTargetContact(memo, BeamSlabRelation, id, beam.Owner, PreservesClearance); + + bool PreservesClearance(Guid relation, Guid joint) + { + Guid jointClass = relation == BeamSlabRelation ? BeamSlabJunctionClass : + relation == BeamWallRelation ? WallBeamJunctionClass : + relation == BeamColumnRelation ? BeamColumnJunctionClass : Guid.Empty; + if (jointClass != Guid.Empty) + return geometry.Read(joint, jointClass) is { } body && + ReadSingleRelation(body, relation, requireSection: true) == owner; + + return rectangle is { } own && BeamJointMissesFootprint(geometry, owner, relation, joint, beam, own, home, (from, to)); + } + } + + private static byte[]? ReadSlabWallPeer(ModelGeometry geometry, Guid slab, Guid role, Guid junction, out Guid wall) + { + wall = Guid.Empty; + if ((role != SlabWallRelation && role != AlternateSlabWallRelation) || + geometry.Read(junction, WallSlabJunctionClass) is not { } contact || + ReadSingleRelation(contact, role, requireSection: true) != slab) return null; + wall = ReadSingleRelation(contact, WallSlabRelation, requireSection: true); + return geometry.Read(wall, WallClass) is { } body && HasGeometryRelation(body, WallSlabRelation, junction) ? body : null; + } + + private static bool BeamJointMissesFootprint(ModelGeometry geometry, Guid owner, Guid relation, Guid joint, + BeamPrism beam, (double HalfWidth, double Depth) own, double home, (double Min, double Max) along) + { + if (beam.SinRoll != 0 || ReadBeamAxisJunction(geometry, owner, relation, joint) is not { } link || + geometry.Read(link.Peer, BeamMemoClass) is not { } peerMemo || + !HasGeometryRelation(peerMemo, link.Reciprocal, joint) || + ReadBeamPrism(geometry, link.Peer, peerMemo, home) is not { SinRoll: 0 } peer || + !SameIntersectionGroup(geometry, beam.Layer, peer.Layer) || + !IsOnBeamJoint(beam, link.X, link.Y, IsBeamEndRelation(relation)) || + !IsOnBeamJoint(peer, link.X, link.Y, IsBeamEndRelation(link.Reciprocal)) || + ReadBeamRectangle(ReadBeamHatch(geometry, link.Peer, peerMemo)) is not { } other) + return false; + + // The join can change the beam's end only inside the intersection of the two section strips. + double direction = beam.Dx * peer.Dx + beam.Dy * peer.Dy; + const double levelTolerance = 1e-7; + if (Math.Abs(direction) > JunctionTolerance && + (Math.Abs(own.HalfWidth - other.HalfWidth) > JunctionTolerance || + Math.Abs(own.Depth - other.Depth) > JunctionTolerance || Math.Abs(beam.Z - peer.Z) > levelTolerance)) + return false; + if (ProjectBeamJunctionInterval(beam, peer, link.X, link.Y, -own.HalfWidth, own.HalfWidth, + -other.HalfWidth, other.HalfWidth) is { } reach) + return along.Max < reach.Min - JunctionTolerance || along.Min > reach.Max + JunctionTolerance; + + // At a collinear butt joint each beam continues away from the shared end. + double station = (link.X - beam.X) * beam.Dx + (link.Y - beam.Y) * beam.Dy; + double peerStation = (link.X - peer.X) * peer.Dx + (link.Y - peer.Y) * peer.Dy; + return IsBeamEndRelation(relation) && IsBeamEndRelation(link.Reciprocal) && + beam.Dx * peer.Dy == beam.Dy * peer.Dx && + (beam.Length / 2 - station) * (peer.Length / 2 - peerStation) * direction < 0; + } + + private static bool SharedBeamPreservesSlabCoverage(ModelGeometry geometry, Guid wall, Guid slab, Guid id, + ElementLocation location, double home, uint wallPriority, (double X0, double Y0, double X1, double Y1) footprint) + { + if (geometry.Read(id, BeamSlabJunctionClass) is not { } joint || + ReadSingleRelation(joint, SlabBeamRelation, requireSection: true) != slab) + return false; + Guid beamId = ReadSingleRelation(joint, BeamSlabRelation, requireSection: true); + if (geometry.Read(beamId, BeamMemoClass) is not { } memo || + ReadBeamPrism(geometry, beamId, memo, home) is not { SinRoll: 0 } beam || + !SameIntersectionGroup(geometry, beam.Layer, location.LayerIndex)) + return false; + var hatch = ReadBeamHatch(geometry, beamId, memo); + if (ReadBeamRectangle(hatch) is not { } section || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } priority || + priority < wallPriority || ReadConnectedSlabPriority(geometry, slab, id) is not { } slabPriority || priority < slabPriority) + return false; + + // Where this beam replaces slab material, it must also cut the target wall. + bool cutsWall = false; + var along = ProjectRectangle(footprint, beam.X, beam.Y, beam.Dx, beam.Dy); + return HasOnlyBeamTargetContact(memo, BeamSlabRelation, id, beam.Owner, KeepsBeam) && cutsWall; + + bool KeepsBeam(Guid key, Guid contact) + { + if (key == BeamWallRelation) + { + if (ReadBeamStructuralNeighbor(geometry, beamId, key, contact) is not { } peer || + ReadWallPriority(geometry, peer.Id, peer.Body) is not { } p || p > priority) return false; + if (peer.Id != wall) return true; + if (cutsWall) return false; + cutsWall = true; + return true; + } + if (key == BeamSlabRelation) return BeamWinsContact(geometry, beamId, key, contact, priority); + if (key == BeamColumnRelation) + return TryReadBeamColumnCut(geometry, beamId, contact, priority, out var plan, allowVerifiedNonWrappingWalls: true) && + (plan is null || OpeningPlansDisjoint(footprint, plan.Value)); + return BeamJointMissesFootprint(geometry, beamId, key, contact, beam, section, home, along); + } + } + + private static bool SlabContactWallMissesStrip(ModelGeometry geometry, Guid owner, byte[] body, + (double X0, double Y0, double X1, double Y1) footprint, double home, Elevations band) + { + var record = body.AsSpan(FindClassFrame(body, WallClass)); + var settings = ReadWallSettings(body); + var location = ReadElementLocation(record, "Wall", 0); + if (ReadWallReferencePlan(settings, out var inline) is not { } axis || + !HasBoundedWallReferenceBody(geometry, owner, record)) return false; + if (geometry.StoryElevation(location.HomeStoryIndex) is { } peerHome && + ReadWallReferencePlanes(settings, location, geometry) is { } levels && + DisjointHeights(levels.Bottom + peerHome - home, levels.Top + peerHome - home, band)) return true; + + double dx = axis.End.X - axis.Start.X, dy = axis.End.Y - axis.Start.Y, length = double.Hypot(dx, dy); + var offsets = ProjectRectangle(footprint, axis.Start.X, axis.Start.Y, dy / length, -dx / length); + if (offsets.Max < Math.Min(axis.InsideOffset, axis.OutsideOffset) - JunctionTolerance || + offsets.Min > Math.Max(axis.InsideOffset, axis.OutsideOffset) + JunctionTolerance) + return true; + return ReadWallStrip(settings, ReadWallContour(geometry, record, owner), inline) is { } strip && + ReadJoinedWallStrip(geometry, owner, strip, location) is { } expanded && OpeningPlansDisjoint(footprint, expanded.Footprint); + } + + private static bool HasBoundedWallReferenceBody(ModelGeometry geometry, Guid owner, ReadOnlySpan wall) + { + int start = FindRelationshipSection(wall, wall.Length); + if (start < 0) return false; + var relations = wall[start..]; + while (relations.Length >= 17) + { + var entry = relations; + if (!TryReadGeometryRelation(ref relations, out byte tag, out Guid role, out _)) return false; + if (role == ElementAssemblyRelation) + { + var pairs = ReadRelationIds(entry, relations, tag); + if (tag == 2 && WallIsSubtractionOperator(geometry, owner, pairs)) continue; + if (tag != 1 || pairs.IsEmpty || pairs.Length % 32 != 0) return false; + // A verified subtraction cannot extend the wall outside its reference body. + for (int i = 0; i < pairs.Length; i += 32) + { + Guid slab = new(pairs.Slice(i, 16)), operation = new(pairs.Slice(i + 16, 16)); + if (ReadSubtractionDirection(geometry, owner, slab, operation) is null || + geometry.Read(slab, SlabClass) is not { } operand || + !HasOperationPair(operand, owner, operation, operationTag: 2)) + return false; + } + continue; + } + if (tag == 0x12 && (UnjoinedWallOwnerRelations.Contains(role) || role == DatabaseElementList || + role == WallTopStoryRelation || role == AttributeOwnerRelation) || + tag == 2 && (role == ZoneCalculationRelation || role == AttributeOwnerRelation) || + tag == 0x11 && (UnjoinedWallChildRelations.Contains(role) || role == LinkedElementSettingsRelation || + role == PlanContourRelation)) continue; + if (tag is not (1 or 0x11) || role != DrawingRelation && role != WallLabelRelation && + role != AttachedAnnotationRelation && role != ElementPropertyOverrideLink && role != DoorHostRelation && + role != CutElementRelation && role != OpeningHostRelation && role != WallSlabRelation && role != WallBeamRelation && + role != WallColumnRelation && role != FirstWallEndRelation && role != SecondWallEndRelation) return false; + } + return relations is [0]; + } + + private static bool CollectBeamForSlabCut(ModelGeometry geometry, Guid wallId, Guid slabId, Guid id, + ElementLocation wall, double home, + Elevations slabBand, Elevations bounds, bool cutsBottom, uint wallPriority, + List<(Guid Memo, Guid Junction)> cutters) + { + if (geometry.Read(id, BeamSlabJunctionClass) is not { } joint || + ReadSingleRelation(joint, SlabBeamRelation, requireSection: true) != slabId) + return false; + Guid memoId = ReadSingleRelation(joint, BeamSlabRelation, requireSection: true); + if (geometry.Read(memoId, BeamMemoClass) is not { } memo || + ReadBeamPrism(geometry, memoId, memo, home) is not { SinRoll: 0 } beam || + !SameIntersectionGroup(geometry, beam.Layer, wall.LayerIndex)) + return false; + var hatch = ReadBeamHatch(geometry, memoId, memo); + if (BeamPlanBand(beam, hatch) is not { } band || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } priority || + priority < wallPriority || ReadConnectedSlabPriority(geometry, slabId) is not { } slabPriority || priority < slabPriority || + (cutsBottom + ? band.Top <= slabBand.Top || band.Bottom >= slabBand.Top || band.Top >= bounds.Top + : band.Bottom >= slabBand.Bottom || band.Top <= slabBand.Bottom || band.Bottom <= bounds.Bottom)) + return false; + Guid contact = Guid.Empty; + // The beam may replace part of the slab band and still continue the cut towards the wall's interior. + if (!HasOnlyBeamTargetContact(memo, BeamSlabRelation, id, beam.Owner, KeepsBeam) || contact == Guid.Empty) + return false; + cutters.Add((memoId, contact)); + return true; + + bool KeepsBeam(Guid key, Guid other) + { + if (IsBeamEndRelation(key) || key == FirstBeamCollisionRelation || key == SecondBeamCollisionRelation) + return true; // The union verifies axial and transverse beam contacts after collecting all cutters. + if (key == BeamSlabRelation && geometry.Read(other, BeamSlabJunctionClass) is { } slabJoint && + ReadSingleRelation(slabJoint, key, requireSection: true) == memoId) + { + Guid slabOther = ReadSingleRelation(slabJoint, SlabBeamRelation, requireSection: true); + return ReadConnectedSlabPriority(geometry, slabOther, other) is { } p && p <= priority; + } + if (key != BeamWallRelation || geometry.Read(other, WallBeamJunctionClass) is not { } wallJoint || + ReadSingleRelation(wallJoint, key, requireSection: true) != memoId) return false; + Guid peer = ReadSingleRelation(wallJoint, WallBeamRelation, requireSection: true); + if (geometry.Read(peer, WallClass) is not { } wallRecord || !HasGeometryRelation(wallRecord, WallBeamRelation, other)) + return false; + if (peer != wallId) return ReadWallPriority(geometry, peer, wallRecord) is { } p && p <= priority; + if (contact != Guid.Empty) return false; + contact = other; + return true; + } + } + + private static uint? ReadConnectedSlabPriority(ModelGeometry geometry, Guid slab, Guid junction = default) + { + if (geometry.Read(slab, SlabClass) is not { } body || + junction != Guid.Empty && !HasGeometryRelation(body, SlabBeamRelation, junction)) return null; + var record = body.AsSpan(FindClassFrame(body, SlabClass)); + return ReadSlabPriority(AfterCountedString(record, ClassElementIdOffset("Slab")), geometry.Attributes); + } + + private static bool SlabColumnMissesWall(ModelGeometry geometry, Guid memoId, Guid junction, uint wallPriority, double home, + (double X0, double Y0, double X1, double Y1) footprint, Elevations band) + { + var hatch = ReadColumnContactSection(geometry, memoId, ColumnSlabRelation, junction, out var column, includeCircular: true); + if (hatch.IsEmpty || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not { } priority) + return false; + if (priority < wallPriority) return true; + if (!column.Slice(304, ColumnEndPlaneFrame.Length).SequenceEqual(ColumnEndPlaneFrame) || + BinaryPrimitives.ReadUInt16LittleEndian(column[368..]) != 1) return false; + if (IsHorizontal(column[312..]) && IsHorizontal(column[370..]) && + ReadDouble(column, 352) < 0 && ReadDouble(column, 410) > 0 && + geometry.StoryElevation(ReadElementLocation(column, "Column", 0).HomeStoryIndex) is { } level && + DisjointHeights(ReadDouble(column, 328) + level - home, ReadDouble(column, 386) + level - home, band)) + return true; + return ReadColumnFootprint(column, hatch) is { } plan && + (plan.X1 <= footprint.X0 + JunctionTolerance || plan.X0 >= footprint.X1 - JunctionTolerance || + plan.Y1 <= footprint.Y0 + JunctionTolerance || plan.Y0 >= footprint.Y1 - JunctionTolerance); + } + + private static bool DisjointHeights(double bottom, double top, Elevations band) => + double.IsFinite(bottom) && double.IsFinite(top) && top > bottom && + (top <= band.Bottom + JunctionTolerance || bottom >= band.Top - JunctionTolerance); +} diff --git a/src/PlaIO/Internal/ElementReader.SlabGeometry.cs b/src/PlaIO/Internal/ElementReader.SlabGeometry.cs new file mode 100644 index 0000000..cc708c0 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabGeometry.cs @@ -0,0 +1,302 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid AlternateSlabWallRelation = new("29bce22c-b910-400a-b84a-0b85fb92610e"); + + private readonly record struct SlabOpeningSources(Guid[] Openings, bool CanReconstructSolid); + + private static bool HasSupportedSlabReferencePlane(ReadOnlySpan settings) => + settings.Length >= 25 && (settings[8] is 0 or 3 || settings[8] == 1 && settings.Length >= 89 && + BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) == 2 && + BinaryPrimitives.ReadUInt16LittleEndian(settings[85..]) == 1); + + private static PlaSlabGeometry? ReadSlabGeometry(ReadOnlySpan record, Guid slab, ModelGeometry geometry, PlaBoundingBox box, + out SlabOpeningSources? sources) + { + sources = null; + if (box.ZMax <= box.ZMin) return null; + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + var polygon = ReadSlabOutline(settings); + // The box reader has already validated the frame, extents and contour table. + if (BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) > 0) + return ReadCurvedSlabGeometry(polygon, box) is { } curved ? WithFloorPlanPerimeters(curved) : null; + if (ReadStraightRings(polygon, out double area) is not { } rings) return null; + int points = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]); + int size = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..]); + double volume = area * (box.ZMax - box.ZMin); + bool vertical = HasVerticalSlabEdges(polygon[size..], points - rings.Count); + var openings = vertical ? ReadSlabOpeningSources(record, slab, geometry) : null; + bool hasVerifiedOpenings = openings is { Length: > 0 }; + bool solid = double.IsFinite(volume) && volume > 0 && vertical && + SlabContactsPreservePrism(record, settings, slab, geometry, hasVerifiedOpenings); + if (openings is not null) sources = new SlabOpeningSources(openings, solid); + double? verifiedVolume = solid && !hasVerifiedOpenings ? volume : null; + bool uncut = solid && openings is { Length: 0 }; + IReadOnlyList? prisms = uncut ? Array.AsReadOnly(new[] { new PlaSlabPrism(rings) }) : null; + if (verifiedVolume is null && vertical && openings is { Length: 0 } && + double.IsFinite(volume) && + ReadSlabStructuralLoss(record, settings, slab, geometry, box, rings, out var evaluated) is { } removed && + removed >= 0 && volume > removed) + { + verifiedVolume = volume - removed; + prisms = evaluated; + } + return WithFloorPlanPerimeters(new PlaSlabGeometry(rings, box.ZMin, box.ZMax, area, verifiedVolume) + { + IsUncutVerticalPrism = uncut, + VerticalPrisms = prisms, + }); + } + + private static PlaSlabGeometry WithFloorPlanPerimeters(PlaSlabGeometry slab) + { + double total = 0, holes = 0; + for (int i = 0; i < slab.Rings.Count; i++) + { + var ring = slab.Rings[i]; + double length = 0; + for (int j = 0; j < ring.Count; j++) + length += Distance(ring[j], ring[(j + 1) % ring.Count]); + total += length; + if (i != 0) holes += length; + } + foreach (var arc in slab.Arcs ?? []) + { + var ring = slab.Rings[arc.RingIndex]; + int i = arc.StartVertexIndex; + double chord = Distance(ring[i], ring[(i + 1) % ring.Count]); + double halfSweep = Math.Abs(arc.SweepRadians) / 2; + double extra = chord * (halfSweep / Math.Sin(halfSweep) - 1); + total += extra; + if (arc.RingIndex != 0) holes += extra; + } + return double.IsFinite(total) && double.IsFinite(holes) + ? slab with { FloorPlanPerimeter = total, FloorPlanHolesPerimeter = holes } + : slab; + } + + private static double Distance(PlaPlanPoint a, PlaPlanPoint b) => double.Hypot(b.X - a.X, b.Y - a.Y); + + // The caller validates the contour frame before reading its rings. + private static IReadOnlyList>? ReadStraightRings(ReadOnlySpan polygon, out double area) + { + area = 0; + if (BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0) return null; + int points = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]); + int ringCount = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]); + if (points > 4096) return null; + + var rings = new List>(ringCount); + int endTable = 71 + points * 16; + int start = 0; + for (int ringIndex = 1; ringIndex <= ringCount; ringIndex++) + { + int end = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[(endTable + ringIndex * 4)..]); + var ring = ReadSlabRing(polygon, start, end); + start = end; + + double signedArea = 0; + for (int i = 1; i < ring.Length - 1; i++) + signedArea += Cross(ring[0], ring[i], ring[i + 1]) * 0.5; + if (!double.IsFinite(signedArea) || signedArea == 0 || !IsSimpleRing(ring)) return null; + bool outer = ringIndex == 1; + if (!outer && !IsSeparateHole(rings, ring)) return null; + area += outer ? Math.Abs(signedArea) : -Math.Abs(signedArea); + if ((signedArea > 0) != outer) Array.Reverse(ring); + rings.Add(Array.AsReadOnly(ring)); + } + + return double.IsFinite(area) && area > 0 ? rings.AsReadOnly() : null; + } + + private static PlaPlanPoint[] ReadSlabRing(ReadOnlySpan polygon, int start, int end) + { + var ring = new PlaPlanPoint[end - start - 1]; + for (int i = 0; i < ring.Length; i++) + { + int offset = 71 + (start + i) * 16; + ring[i] = new PlaPlanPoint(ReadDouble(polygon, offset), ReadDouble(polygon, offset + 8)); + } + return ring; + } + + private static bool SlabContactsPreservePrism(ReadOnlySpan record, ReadOnlySpan settings, Guid slab, + ModelGeometry geometry, bool hasVerifiedOpenings) + { + ushort structure = BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]); + if (BinaryPrimitives.ReadUInt16LittleEndian(settings[85..]) != 1 || structure is not (1 or 2)) + return false; + uint? priority = structure == 1 + ? geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(settings[73..])) + : geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])) + ?.Min(skin => skin.Priority); + return HasSupportedSlabContacts(record, Guid.Empty, Guid.Empty, + (key, id) => hasVerifiedOpenings && (key == CutElementRelation || key == OpeningHostRelation) || + SlabSolidContactKeepsShape(geometry, slab, key, id, priority)); + } + + private static Guid[]? ReadSlabOpeningSources(ReadOnlySpan slab, Guid id, ModelGeometry geometry) + { + if (!TryReadRelationTargets(slab, CutElementRelation, out var cuts) || + !TryReadRelationTargets(slab, OpeningHostRelation, out var hosted)) + return null; + var sources = new SortedSet(); + for (int i = 0; i < cuts.Length; i += 16) + { + var (owner, target) = ReadOpeningCut(geometry, new Guid(cuts.Slice(i, 16))); + if (owner == Guid.Empty || target != id || !sources.Add(owner)) return null; + } + for (int i = 0; i < hosted.Length; i += 16) + if (!sources.Contains(new Guid(hosted.Slice(i, 16)))) return null; + return sources.ToArray(); + } + + private static PlaSlabGeometry ApplySlabOpenings(PlaSlabGeometry slab, Guid id, SlabOpeningSources? sources, + Dictionary links, Dictionary geometry, + Dictionary parameters) + { + if (sources is not { } saved) return slab; + double topArea = slab.OutlineArea, bottomArea = slab.OutlineArea; + double removedVolume = 0; + IReadOnlyList>? evaluated = + saved.CanReconstructSolid && saved.Openings.Length > 0 ? slab.Rings : null; + foreach (Guid opening in saved.Openings) + { + if (parameters.GetValueOrDefault(opening).OpeningProfile is null || + links.GetValueOrDefault(opening).Targets?.Contains(id) != true || + geometry.GetValueOrDefault(opening) is not { Cuts: { } cuts, CutVolume: { } volume } cutGeometry) + return slab; + + double sectionArea = volume / cuts.Sum(c => c.Top - c.Bottom); + if (!double.IsFinite(sectionArea) || sectionArea <= 0) return slab; + double depth = 0; + bool bottom = false, top = false, through = false; + foreach (var cut in cuts) + { + if (cut.SlabGuid != id) continue; + if (cut.Bottom < slab.Bottom - JunctionTolerance || cut.Top > slab.Top + JunctionTolerance) + return slab; + depth += cut.Top - cut.Bottom; + through |= cut.Bottom <= slab.Bottom && cut.Top >= slab.Top; + bottom |= Math.Abs(cut.Bottom - slab.Bottom) <= JunctionTolerance; + top |= Math.Abs(cut.Top - slab.Top) <= JunctionTolerance; + } + if (bottom) bottomArea -= sectionArea; + if (top) topArea -= sectionArea; + removedVolume += sectionArea * depth; + if (depth > 0 && evaluated is not null) + evaluated = through && cutGeometry.Rings is { Count: > 0 } rings + ? SubtractSlabFootprint(evaluated, + rings.Select(r => (IReadOnlyList)r.Reverse().ToArray()).ToArray(), sectionArea) + : null; + } + if (!(bottomArea >= 0 && topArea >= 0)) return slab; + double candidate = slab.OutlineArea * (slab.Top - slab.Bottom) - removedVolume; + bool hasVolume = saved.CanReconstructSolid && double.IsFinite(candidate) && candidate > 0; + return slab with + { + TopAreaWithOpenings = topArea, + BottomAreaWithOpenings = bottomArea, + Volume = hasVolume ? candidate : slab.Volume, + VerticalPrisms = hasVolume && evaluated is not null ? GroupSlabPrisms(evaluated) : slab.VerticalPrisms, + }; + } + + private static bool HasVerticalSlabEdges(ReadOnlySpan data, int count) + { + if (data.Length < 16 || !data[8..].StartsWith(new byte[] { 1, 0, 1, 0 }) || + BinaryPrimitives.ReadUInt32LittleEndian(data[12..]) != count || count > (data.Length - 16) / 27) + return false; + for (int i = 0; i < count; i++) + { + var edge = data[(16 + i * 27)..]; + if (BinaryPrimitives.ReadUInt32LittleEndian(edge[4..]) != 2 || + ReadDouble(edge, 8) != Math.PI / 2 || BinaryPrimitives.ReadUInt16LittleEndian(edge[16..]) != 3) + return false; + } + return true; + } + + private static bool SlabSolidContactKeepsShape(ModelGeometry geometry, Guid slab, Guid key, Guid id, uint? priority) + { + if (key == SlabLevelDimensionRelation) + return geometry.Read(id, SlabLevelDimensionClass) is { } dimension && + ReadSingleRelation(dimension, key, requireSection: true) == slab; + if (priority is not > 0) return false; + bool wallContact = key == SlabWallRelation || key == AlternateSlabWallRelation; + var (type, peerRole) = wallContact ? (WallSlabJunctionClass, WallSlabRelation) : + key == SlabBeamRelation ? (BeamSlabJunctionClass, BeamSlabRelation) : default; + if (type == Guid.Empty || geometry.Read(id, type) is not { } joint || + ReadSingleRelation(joint, key, requireSection: true) != slab) return false; + Guid peer = ReadSingleRelation(joint, peerRole, requireSection: true); + if (wallContact) + return geometry.Read(peer, WallClass) is { } wall && HasGeometryRelation(wall, peerRole, id) && + ReadWallPriority(geometry, peer, wall) is > 0 and { } wallPriority && wallPriority <= priority; + if (geometry.Read(peer, BeamMemoClass) is not { } memo || !HasGeometryRelation(memo, peerRole, id)) + return false; + var hatch = ReadBeamHatch(geometry, peer, memo); + return !hatch.IsEmpty && geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) + is > 0 and { } beamPriority && beamPriority < priority; + } + + private static bool IsSimpleRing(IReadOnlyList ring) + { + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + var c = ring[(i + 2) % ring.Count]; + if (a == b || Cross(a, b, c) == 0 && ((a.X - b.X) * (c.X - b.X) + (a.Y - b.Y) * (c.Y - b.Y)) > 0) + return false; + int end = i == 0 ? ring.Count - 1 : ring.Count; + for (int j = i + 2; j < end; j++) + if (SegmentsIntersect(a, b, ring[j], ring[(j + 1) % ring.Count])) return false; + } + return true; + } + + private static bool IsSeparateHole(IReadOnlyList> rings, IReadOnlyList hole) + { + if (!ContainsPoint(rings[0], hole[0])) return false; + for (int i = 0; i < rings.Count; i++) + { + var other = rings[i]; + if (i > 0 && (ContainsPoint(other, hole[0]) || ContainsPoint(hole, other[0]))) return false; + for (int j = 0; j < hole.Count; j++) + for (int k = 0; k < other.Count; k++) + if (SegmentsIntersect(hole[j], hole[(j + 1) % hole.Count], other[k], other[(k + 1) % other.Count])) + return false; + } + return true; + } + + private static bool ContainsPoint(IReadOnlyList ring, PlaPlanPoint p) + { + bool inside = false; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + if ((a.Y > p.Y) != (b.Y > p.Y) && p.X < a.X + (p.Y - a.Y) * (b.X - a.X) / (b.Y - a.Y)) + inside = !inside; + } + return inside; + } + + private static bool SegmentsIntersect(PlaPlanPoint a, PlaPlanPoint b, PlaPlanPoint c, PlaPlanPoint d) + { + 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; + double abC = Cross(a, b, c), abD = Cross(a, b, d); + double cdA = Cross(c, d, a), cdB = Cross(c, d, b); + return !double.IsFinite(abC) || !double.IsFinite(abD) || !double.IsFinite(cdA) || !double.IsFinite(cdB) || + (abC <= 0 && abD >= 0 || abD <= 0 && abC >= 0) && (cdA <= 0 && cdB >= 0 || cdB <= 0 && cdA >= 0); + } + + private static double Cross(PlaPlanPoint a, PlaPlanPoint b, PlaPlanPoint c) => + (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X); +} diff --git a/src/PlaIO/Internal/ElementReader.SlabOpenings.cs b/src/PlaIO/Internal/ElementReader.SlabOpenings.cs new file mode 100644 index 0000000..08bda5a --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabOpenings.cs @@ -0,0 +1,274 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static ReadOnlySpan TopCenterOpeningFrame => [2, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0]; + + private static Elevations? ReadSlabOpeningElevations(ReadOnlySpan settings, Guid opening, PlaOpeningProfile profile, + OpeningLinks links, ModelGeometry geometry, out PlaOpeningGeometry? cutGeometry) + { + cutGeometry = null; + var host = ReadOpeningSlab(geometry, links.Host); + if (host.IsEmpty || geometry.StoryElevation(ReadElementLocation(host, "Slab", 0).HomeStoryIndex) is not { } home || + ReadSlabOpeningLimits(settings, host, 0) is not { } limits || + ReadSlabOpeningPlan(settings, profile) is not { } footprint) + return null; + + var origin = ReadSlabOpeningOrigin(host); + double area = 0; + if (origin is { } hostOrigin) + cutGeometry = ReadPlacedOpening(settings, profile, hostOrigin, footprint, out area); + var cutPlan = OpeningCutPlan(footprint, profile); + bool closed = cutGeometry is not null; + var cuts = new List(); + double bottom = double.PositiveInfinity, top = double.NegativeInfinity; + foreach (Guid target in links.Targets!) + { + var slab = target == links.Host ? host : ReadOpeningSlab(geometry, target); + if (slab.IsEmpty || geometry.StoryElevation(ReadElementLocation(slab, "Slab", 0).HomeStoryIndex) is not { } level || + ReadElevations(slab, "Slab") is not { } planes) + return null; + var polygon = ReadSlabOutline(AfterCountedString(slab, ClassElementIdOffset("Slab"))); + if (ReadOutlineBounds(polygon) is not { } plan || ReadAfterVerticalSlabEdges(polygon).IsEmpty) return null; + + bool fits = false; + if (cutGeometry is not null && origin is { } projectOrigin) + fits = OpeningFitsSlab(polygon, cutGeometry, profile, TranslateOpeningPlan(footprint, projectOrigin)); + if (target != links.Host) + { + if (origin is not { } secondaryOrigin) return null; + var projected = TranslateOpeningPlan(footprint, secondaryOrigin); + // An authored cut target can remain linked after its slab outline moves out of reach. + if (OpeningPlansDisjoint(projected, plan)) continue; + if (!fits && (BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0 || + !SlabPolygonContainsFootprint(polygon, projected, allowBoundary: false))) return null; + } + double shift = level - home; + var band = new Elevations(Math.Max(planes.Bottom + shift, limits.Bottom), Math.Min(planes.Top + shift, limits.Top)); + if (band.Top <= band.Bottom + JunctionTolerance) continue; + if (!TryClipSlabOpening(slab, target, opening, links.Host, footprint, cutPlan, geometry, home, band, origin, + double.IsNegativeInfinity(limits.Bottom) && double.IsPositiveInfinity(limits.Top), + out var intervals, ref closed)) + return null; + if (intervals.Count == 0) continue; + bottom = Math.Min(bottom, intervals[0].Bottom); + top = Math.Max(top, intervals[^1].Top); + closed &= fits; + if (closed) + cuts.AddRange(intervals.Select(i => new PlaOpeningCut(target, i.Bottom + home, i.Top + home))); + } + if (closed && cutGeometry is not null && cuts.Count > 0) + { + var ordered = cuts.OrderBy(c => c.Bottom).ThenBy(c => c.Top).ToArray(); + if (ordered.All(c => double.IsFinite(c.Bottom) && double.IsFinite(c.Top) && c.Top > c.Bottom) && + ordered.Zip(ordered.Skip(1)).All(pair => pair.First.Top <= pair.Second.Bottom + JunctionTolerance)) + { + double volume = ordered.Sum(c => c.Top - c.Bottom) * area; + cutGeometry = cutGeometry with + { + Cuts = Array.AsReadOnly(ordered), + CutVolume = double.IsFinite(volume) && volume > 0 ? volume : null, + }; + } + } + return CheckedElevations(bottom, top); + } + + private static ReadOnlySpan ReadOpeningSlab(ModelGeometry geometry, Guid id) => + geometry.Read(id, SlabClass) is { } record ? record.AsSpan(FindClassFrame(record, SlabClass)) : default; + + private static bool SlabOpeningMissesStrip(ModelGeometry geometry, Guid slab, Guid role, Guid relation, + (double X0, double Y0, double X1, double Y1) strip, double home, Elevations band) + { + var (opening, target) = role == CutElementRelation ? ReadOpeningCut(geometry, relation) : (relation, slab); + if (target != slab || geometry.Read(opening, OpeningClass) is not { } record) return false; + var hostIds = ReadOpeningRelation(record, OpeningHostRelation, owner: true); + if (hostIds.Length != 16) return false; + var host = new Guid(hostIds); + if (role == OpeningHostRelation && host != slab) return false; + var source = ReadOpeningSlab(geometry, host); + if (source.IsEmpty || !HasGeometryRelation(source, OpeningHostRelation, opening) || + geometry.StoryElevation(ReadElementLocation(source, "Slab", 0).HomeStoryIndex) is not { } story) + return false; + var cuts = ReadOpeningRelation(record, OpeningCutRelation); + int reciprocal = 0; + for (int i = 0; i < cuts.Length; i += 16) + { + var id = new Guid(cuts.Slice(i, 16)); + if (role == CutElementRelation ? id == relation : ReadOpeningCut(geometry, id) == (opening, slab) && + HasGeometryRelation(source, CutElementRelation, id)) reciprocal++; + } + if (reciprocal != 1) return false; + + var settings = AfterCountedString(record.AsSpan(FindClassFrame(record, OpeningClass)), ClassElementIdOffset("Opening")); + if (ReadSlabOpeningLimits(settings, source, story - home) is not { } limits) return false; + if (limits.Top <= band.Bottom + JunctionTolerance || limits.Bottom >= band.Top - JunctionTolerance) return true; + if (ReadSlabOpeningOrigin(source) is not { } origin || + ReadOpeningProfile(settings) is not { } profile || ReadSlabOpeningPlan(settings, profile) is not { } plan) + return false; + if (profile.Shape == "Circle" && settings[256..].StartsWith(CenteredOpeningFrame)) + plan = OpeningCutPlan(plan, profile); + else if (profile.Shape is not ("Rectangle" or "Square" or "Custom")) return false; + return OpeningPlansDisjoint(strip, TranslateOpeningPlan(plan, origin)); + } + + private static ReadOnlySpan ReadAfterVerticalSlabEdges(ReadOnlySpan polygon) + { + int count = (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]) - + (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]); + var edges = polygon[(int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..])..]; + return HasVerticalSlabEdges(edges, count) ? edges[(16 + count * 27)..] : default; + } + + private static PlaPlanPoint? ReadSlabOpeningOrigin(ReadOnlySpan host) + { + var polygon = ReadSlabOutline(AfterCountedString(host, ClassElementIdOffset("Slab"))); + if (ReadOutlineBounds(polygon) is null) return null; + var tail = ReadAfterVerticalSlabEdges(polygon); + if (tail.Length < 87 || BinaryPrimitives.ReadUInt32LittleEndian(tail) != 2 || + ReadDouble(tail, 4) != Math.PI / 2 || + !tail[23..].StartsWith(new byte[] { 1, 0, 1, 0 })) + return null; + uint entries = BinaryPrimitives.ReadUInt32LittleEndian(tail[27..]); + if (entries is not (1 or 3)) return null; + int offset = 55 + (int)entries * 8; + if (tail.Length < offset + 24 || ReadDouble(tail, offset + 16) != 0) return null; + double x = ReadDouble(tail, offset), y = ReadDouble(tail, offset + 8); + return double.IsFinite(x) && double.IsFinite(y) ? new PlaPlanPoint(x, y) : null; + } + + private static Elevations? ReadSlabOpeningLimits(ReadOnlySpan settings, ReadOnlySpan host, double storyShift) + { + if (settings.Length < 290 || + ReadDouble(settings, 158) != 1 || ReadDouble(settings, 166) != 0 || ReadDouble(settings, 174) != 0 || + ReadDouble(settings, 182) != 0 || ReadDouble(settings, 190) != 1 || ReadDouble(settings, 198) != 0 || + ReadDouble(settings, 206) != 0 || ReadDouble(settings, 214) != 0 || + ReadDouble(settings, 222) is not (1 or -1)) + return null; + + uint mode = BinaryPrimitives.ReadUInt32LittleEndian(settings[278..]); + if (!settings[256..].StartsWith(CenteredOpeningFrame) && + !(mode == 0 && ReadDouble(settings, 222) == -1 && settings[256..].StartsWith(TopCenterOpeningFrame))) + return null; + if (mode == 0) return new Elevations(double.NegativeInfinity, double.PositiveInfinity); + if (mode != 2) return null; + + var planes = AfterCountedString(host, ClassElementIdOffset("Slab")); + if (!HasSupportedSlabReferencePlane(planes)) return null; + double normal = ReadDouble(settings, 222); + double cap = ReadDouble(planes, 0) + storyShift + ReadDouble(settings, 150) + normal * ReadDouble(settings, 282); + if (!double.IsFinite(cap)) return null; + return normal > 0 ? new Elevations(cap, double.PositiveInfinity) : new Elevations(double.NegativeInfinity, cap); + } + + private static bool TryClipSlabOpening(ReadOnlySpan slab, Guid target, Guid opening, Guid host, + (double X0, double Y0, double X1, double Y1) footprint, (double X0, double Y0, double X1, double Y1) cutPlan, + ModelGeometry geometry, double home, Elevations band, + PlaPlanPoint? origin, bool through, out List intervals, ref bool closed) + { + intervals = []; + var cuts = ReadOpeningRelation(slab, CutElementRelation); + if (cuts.IsEmpty) return false; + var covered = new List(); + for (int i = 0; i < cuts.Length; i += 16) + { + var cut = new Guid(cuts.Slice(i, 16)); + var (peer, peerTarget) = ReadOpeningCut(geometry, cut); + if (peerTarget != target || peer == Guid.Empty) return false; + if (peer == opening) continue; + if (geometry.Read(peer, OpeningClass) is not { } record || !HasGeometryRelation(record, OpeningCutRelation, cut)) + return false; + var owner = ReadOpeningRelation(record, OpeningHostRelation, owner: true); + if (owner.IsEmpty) return false; + var peerHost = new Guid(owner); + var associated = ReadOpeningSlab(geometry, peerHost); + if (associated.IsEmpty || !HasGeometryRelation(associated, OpeningHostRelation, peer) || + geometry.StoryElevation(ReadElementLocation(associated, "Slab", 0).HomeStoryIndex) is not { } level) + return false; + var settings = AfterCountedString(record.AsSpan(FindClassFrame(record, OpeningClass)), ClassElementIdOffset("Opening")); + if (ReadSlabOpeningLimits(settings, associated, level - home) is not { } limits) return false; + + // A through opening adds no plane. Overlapping through profiles need a plan Boolean for the closed cut. + if (double.IsNegativeInfinity(limits.Bottom) && double.IsPositiveInfinity(limits.Top)) + { + if (closed && through) + { + var otherOrigin = peerHost == host ? origin : ReadSlabOpeningOrigin(associated); + closed = origin is { } a && otherOrigin is { } b && + ReadOpeningProfile(settings) is { } otherProfile && + ReadSlabOpeningPlan(settings, otherProfile) is { } other && + OpeningPlansDisjoint(TranslateOpeningPlan(cutPlan, a), TranslateOpeningPlan(OpeningCutPlan(other, otherProfile), b)); + } + continue; + } + double low = Math.Max(band.Bottom, limits.Bottom), high = Math.Min(band.Top, limits.Top); + if (high <= low + JunctionTolerance) continue; + if (peerHost != host || ReadOpeningProfile(settings) is not { } profile || + ReadSlabOpeningPlan(settings, profile) is not { } peerPlan) + return false; + if (OpeningPlansDisjoint(footprint, peerPlan)) + { + closed &= OpeningPlansDisjoint(cutPlan, OpeningCutPlan(peerPlan, profile)); + continue; + } + // shortcut: partial coverage needs a projected polygon union and the slab's placement transform. + if (footprint.X0 < peerPlan.X0 || footprint.X1 > peerPlan.X1 || + footprint.Y0 < peerPlan.Y0 || footprint.Y1 > peerPlan.Y1 || + !OpeningCoversFootprint(settings, profile, footprint)) + return false; + closed &= cutPlan.X0 >= peerPlan.X0 && cutPlan.X1 <= peerPlan.X1 && + cutPlan.Y0 >= peerPlan.Y0 && cutPlan.Y1 <= peerPlan.Y1 && OpeningCoversFootprint(settings, profile, cutPlan); + covered.Add(new Elevations(low, high)); + } + double start = band.Bottom; + foreach (var removed in covered.OrderBy(r => r.Bottom)) + { + if (removed.Bottom > start + JunctionTolerance) + intervals.Add(new Elevations(start, removed.Bottom)); + start = Math.Max(start, removed.Top); + } + if (band.Top > start + JunctionTolerance) intervals.Add(new Elevations(start, band.Top)); + return true; + } + + private static (double X0, double Y0, double X1, double Y1)? ReadSlabOpeningPlan(ReadOnlySpan settings, + PlaOpeningProfile profile) + { + if (profile.Shape == "Custom" && settings[256..].StartsWith(TopCenterOpeningFrame)) return null; + var (x, y) = SlabOpeningProfileOrigin(settings, profile); + var plan = profile.Shape == "Custom" ? ReadOutlineBounds(settings[304..]) : + (-profile.Width / 2, -profile.Height / 2, profile.Width / 2, profile.Height / 2); + if (plan is not { } local) return null; + var (x0, y0, x1, y1) = (x + local.X0, y + local.Y0, x + local.X1, y + local.Y1); + if (!double.IsFinite(x0) || !double.IsFinite(y0) || !double.IsFinite(x1) || !double.IsFinite(y1) || + x1 <= x0 || y1 <= y0) return null; + return (x0, y0, x1, y1); + } + + private static PlaPlanPoint SlabOpeningProfileOrigin(ReadOnlySpan settings, PlaOpeningProfile profile) + { + double y = ReadDouble(settings, 142); + if (settings[256..].StartsWith(TopCenterOpeningFrame)) y -= profile.Height / 2; + return new PlaPlanPoint(ReadDouble(settings, 134), y); + } + + private static bool OpeningCoversFootprint(ReadOnlySpan settings, PlaOpeningProfile profile, + (double X0, double Y0, double X1, double Y1) footprint) + { + var (x, y) = SlabOpeningProfileOrigin(settings, profile); + var local = (footprint.X0 - x, footprint.Y0 - y, footprint.X1 - x, footprint.Y1 - y); + if (profile.Shape is "Circle" or "Ellipse") + { + double dx = Math.Max(Math.Abs(local.Item1), Math.Abs(local.Item3)) / (profile.Width / 2); + double dy = Math.Max(Math.Abs(local.Item2), Math.Abs(local.Item4)) / (profile.Height / 2); + return dx * dx + dy * dy <= 1; + } + if (profile.Shape != "Custom") return true; + var polygon = settings[304..]; + return BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) == 0 && + SlabPolygonContainsFootprint(polygon, local, allowBoundary: false); + } +} diff --git a/src/PlaIO/Internal/ElementReader.SlabWallCuts.cs b/src/PlaIO/Internal/ElementReader.SlabWallCuts.cs new file mode 100644 index 0000000..855abc3 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.SlabWallCuts.cs @@ -0,0 +1,183 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static bool ReadSlabProfileWallCut(ModelGeometry geometry, Guid slab, int? slabLayer, Guid role, Guid contact, + PlaBoundingBox slabBox, SlabSkin[] skins, IReadOnlyList> slabRings, + out PlaBoundingBox? cut, out double volume) + { + cut = null; + volume = 0; + if (role != SlabWallRelation && role != AlternateSlabWallRelation || + geometry.Read(contact, WallSlabJunctionClass) is not { } joint || + ReadSingleRelation(joint, role, requireSection: true) != slab) + return false; + Guid wall = ReadSingleRelation(joint, WallSlabRelation, requireSection: true); + if (geometry.Read(wall, WallClass) is not { } body || !HasOnlyProfileWallSlabContact(body, contact)) return false; + var record = body.AsSpan(FindClassFrame(body, WallClass)); + var settings = AfterCountedString(record, 197); + var location = ReadElementLocation(record, "Wall", 0); + if (ReadSavedWallBox(settings) is not { } wallBox || settings[184] != 0 || + BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) != 3 || + BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1 || + !SameIntersectionGroup(geometry, slabLayer, location.LayerIndex) || + geometry.StoryElevation(location.HomeStoryIndex) is not { } story || + ReadWallReferencePlanes(settings, location, geometry) is not { } wallPlanes || + ReadWallCutRegions(ReadWallProfileVector(geometry, wall, body), geometry) is not { } regions) + return false; + + double x = ReadDouble(settings, 0), y = ReadDouble(settings, 8); + double dx = ReadDouble(settings, 16) - x, dy = ReadDouble(settings, 24) - y; + double length = Math.Sqrt(dx * dx + dy * dy), baseZ = story + wallPlanes.Bottom; + if (!double.IsFinite(length) || length <= 0) return false; + double alongX = dx / length, alongY = dy / length; + double min = regions.Min(r => r.Ring.Min(p => p.X)), max = regions.Max(r => r.Ring.Max(p => p.X)); + double minZ = baseZ + regions.Min(r => r.Ring.Min(p => p.Y)), maxZ = baseZ + regions.Max(r => r.Ring.Max(p => p.Y)); + if (!MatchesWallExtent(wallBox.XMin, wallBox.XMax, x, dx, alongY, min, max) || + !MatchesWallExtent(wallBox.YMin, wallBox.YMax, y, dy, -alongX, min, max) || + !(Math.Abs(minZ - wallBox.ZMin) <= JunctionTolerance && Math.Abs(maxZ - wallBox.ZMax) <= JunctionTolerance && + Math.Abs(maxZ - (story + wallPlanes.Top)) <= JunctionTolerance)) + return false; + if (!CutBoxesOverlap(slabBox, wallBox)) return true; + + var plan = new List>(slabRings.Count); + foreach (var ring in slabRings) + { + var local = ring.Select(p => new PlaPlanPoint( + (p.X - x) * alongY - (p.Y - y) * alongX, + (p.X - x) * alongX + (p.Y - y) * alongY)).ToList(); + plan.Add(ClipHalfPlane(ClipHalfPlane(local, xAxis: false, 0, keepBelow: false), xAxis: false, length, keepBelow: true)); + } + + double top = slabBox.ZMax - baseZ, cutLow = double.PositiveInfinity, cutHigh = double.NegativeInfinity; + foreach (var skin in skins) + { + double low = top - skin.Thickness; + var filled = new List<(double X0, double Y0, double X1, double Y1)>(); + foreach (var region in regions) + { + if (region.Priority <= skin.Priority) continue; + var part = ClipHalfPlane(ClipHalfPlane(region.Ring, xAxis: false, low, keepBelow: false), + xAxis: false, top, keepBelow: true); + if (part.Count < 3 || SignedRingArea(part) == 0) continue; + var bounds = (X0: part.Min(p => p.X), Y0: part.Min(p => p.Y), + X1: part.Max(p => p.X), Y1: part.Max(p => p.Y)); + // shortcut: overlapping material regions need a section union before volumes can be added. + if (filled.Any(r => !OpeningPlansDisjoint(r, bounds))) return false; + double overlap = IntegrateWallCut(plan, part, bounds.X0, bounds.X1); + if (!double.IsFinite(overlap) || overlap < -JunctionTolerance) return false; + if (overlap <= 0) continue; + filled.Add(bounds); + volume += overlap; + cutLow = Math.Min(cutLow, bounds.Y0 + baseZ); + cutHigh = Math.Max(cutHigh, bounds.Y1 + baseZ); + } + top = low; + } + if (volume > 0) cut = wallBox with { ZMin = cutLow, ZMax = cutHigh }; + return double.IsFinite(volume); + } + + private static bool MatchesWallExtent(double min, double max, double origin, double along, double normal, double u0, double u1) => + Math.Abs(min - (origin + Math.Min(0, along) + Math.Min(normal * u0, normal * u1))) <= JunctionTolerance && + Math.Abs(max - (origin + Math.Max(0, along) + Math.Max(normal * u0, normal * u1))) <= JunctionTolerance; + + private static bool HasOnlyProfileWallSlabContact(ReadOnlySpan wall, Guid contact) + { + int start = FindRelationshipSection(wall, wall.Length); + if (start < 0) return false; + var data = wall[start..]; + bool found = false; + while (data.Length >= 17) + { + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out Guid target)) return false; + if (tag == 0x11 && key == WallSlabRelation && target == contact && !found) found = true; + else if ((tag is 1 or 0x11) && key == DrawingRelation || + tag == 0x11 && (UnjoinedWallChildRelations.Contains(key) || key == WallProfileRelation || key == LinkedElementSettingsRelation) || + tag == 0x12 && (UnjoinedWallOwnerRelations.Contains(key) || key == DatabaseElementList || + key == AttributeOwnerRelation || key == WallTopStoryRelation)) continue; + else return false; + } + return found && data is [0]; + } + + private static List<(uint Priority, List Ring)>? ReadWallCutRegions(ReadOnlySpan vector, ModelGeometry geometry) + { + var items = ReadFirstWallHatch(vector, out uint count); + if (items.IsEmpty) return null; + var regions = new List<(uint, List)>(); + int totalPoints = 0; + for (int i = 0; i < count; i++) + { + int size = ReadHatchSize(items, 2); + if (size == 0) return null; + var hatch = items[..size]; + var vertices = StraightSectionVertices(hatch); + if (vertices.IsEmpty || + geometry.Attributes.Material.GetValueOrDefault(BinaryPrimitives.ReadInt32LittleEndian(hatch[18..])) is not (> 0 and { } priority)) + return null; + totalPoints += vertices.Length / 16; + if (totalPoints > 4096) return null; + var ring = new List(vertices.Length / 16); + for (int j = 0; j < vertices.Length; j += 16) + { + double u = ReadDouble(vertices, j), z = ReadDouble(vertices, j + 8); + if (!double.IsFinite(u) || !double.IsFinite(z)) return null; + ring.Add(new PlaPlanPoint(u, z)); + } + double area = SignedRingArea(ring); + if (!double.IsFinite(area) || area == 0 || !IsSimpleRing(ring)) return null; + if (area < 0) ring.Reverse(); + regions.Add((priority, ring)); + items = items[size..]; + if (i + 1 < count) + { + if (items.Length < 16) return null; + items = items[16..]; + } + } + return items.IsEmpty ? regions : null; + } + + private static double SignedRingArea(IReadOnlyList ring) + { + double area = 0; + for (int i = 1; i < ring.Count - 1; i++) + area += Cross(ring[0], ring[i], ring[i + 1]) * 0.5; + return area; + } + + private static double IntegrateWallCut(List> plan, List section, double min, double max) + { + var stations = plan.SelectMany(r => r).Select(p => p.X).Where(u => u > min && u < max) + .Concat(section.Select(p => p.X)).Distinct().Order().ToArray(); + double volume = 0; + for (int i = 1; i < stations.Length; i++) + { + double half = (stations[i] - stations[i - 1]) * 0.5; + double mid = stations[i - 1] + half, offset = half / Math.Sqrt(3); + double left = mid - offset, right = mid + offset; + // Each polygon span is linear between vertex stations, so two-point quadrature integrates their product exactly. + volume += half * (plan.Sum(r => SectionSpan(r, left)) * SectionSpan(section, left) + + plan.Sum(r => SectionSpan(r, right)) * SectionSpan(section, right)); + } + return volume; + } + + private static double SectionSpan(List ring, double x) + { + double span = 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + if ((a.X > x) == (b.X > x)) continue; + double height = a.Y + (x - a.X) * (b.Y - a.Y) / (b.X - a.X); + span += a.X > b.X ? height : -height; + } + return span; + } +} diff --git a/src/PlaIO/Internal/ElementReader.WallCapPlan.cs b/src/PlaIO/Internal/ElementReader.WallCapPlan.cs new file mode 100644 index 0000000..736d762 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.WallCapPlan.cs @@ -0,0 +1,76 @@ +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + // Near-coincident saved outlines can differ by micrometres even where the model joins their edges. + private const double WallCapPlanClearance = 1e-6; + + private readonly record struct WallCapObstacle((double Start, double End) Span, Elevations? Height = null, + IReadOnlyList>? Rings = null, bool HasVerifiedExtent = true) + { + public bool Reaches(double elevation) => Height is not { } height || + elevation >= height.Bottom - JunctionTolerance && elevation <= height.Top + JunctionTolerance; + } + + private static (bool Bottom, bool Top) WallCapsWithMaterial(WallStrip strip, Elevations bounds, List blocked) + { + if (UnblockedWallSpans(strip, blocked.Select(obstacle => obstacle.Span)).Any() || HasWallCapPatch(strip, blocked)) + return (true, true); + // A cutter can reach only one plane. Each plane needs its own surviving patch. + return (HasWallCapPatch(strip, blocked.Where(obstacle => obstacle.Reaches(bounds.Bottom))), + HasWallCapPatch(strip, blocked.Where(obstacle => obstacle.Reaches(bounds.Top)))); + } + + private static bool HasWallCapPatch(WallStrip strip, IEnumerable blocked) + { + var obstacles = blocked.ToArray(); + var slabs = obstacles.Select(obstacle => obstacle.Rings).OfType>>().ToArray(); + return UnblockedWallSpans(strip, obstacles.Where(obstacle => obstacle.Rings is null).Select(obstacle => obstacle.Span)) + .Any(span => HasWallCapPatch(strip, span, slabs)); + } + + private static IEnumerable<(double Start, double End)> UnblockedWallSpans(WallStrip strip, + IEnumerable<(double Start, double End)> blocked) + { + double covered = strip.Start; + foreach (var (from, to) in blocked.OrderBy(span => span.Start)) + { + double stop = Math.Min(from, strip.End); + if (stop > covered + JunctionTolerance) yield return (covered, stop); + covered = Math.Max(covered, to); + if (covered >= strip.End) yield break; + } + if (covered < strip.End - JunctionTolerance) yield return (covered, strip.End); + } + + private static bool HasWallCapPatch(WallStrip strip, (double Start, double End) span, + IReadOnlyList>> slabs) + { + const double gap = WallCapPlanClearance; + var box = (strip with { Start = span.Start, End = span.End }).Footprint; + var interior = (X0: box.X0 + gap, Y0: box.Y0 + gap, X1: box.X1 - gap, Y1: box.Y1 - gap); + return interior.X0 < interior.X1 && interior.Y0 < interior.Y1 && + WallPlanHasGap(interior, slabs, center => slabs.All(slab => SlabMissesPatch(slab, center))) is true; + } + + private static bool SlabMissesPatch(IReadOnlyList> slab, PlaPlanPoint center) + { + if (ContainsPoint(slab[0], center) && !slab.Skip(1).Any(hole => ContainsPoint(hole, center))) return false; + const double gap = WallCapPlanClearance; + foreach (var ring in slab) + { + var previous = ring[^1]; + foreach (var point in ring) + { + double low = 0, high = 1; + if (ClipSegment(previous.X, point.X, center.X - gap, center.X + gap, ref low, ref high) && + ClipSegment(previous.Y, point.Y, center.Y - gap, center.Y + gap, ref low, ref high)) + return false; + previous = point; + } + } + return true; + } +} diff --git a/src/PlaIO/Internal/ElementReader.WallExtrusion.cs b/src/PlaIO/Internal/ElementReader.WallExtrusion.cs new file mode 100644 index 0000000..d6d0c05 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.WallExtrusion.cs @@ -0,0 +1,146 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid ZoneBoundaryCalculationClass = new("ea57dcc5-7231-45df-83dc-792083fc4699"); + private static readonly Guid ZoneCalculationRelation = new("cc4c5518-9f96-4272-8130-5d61c5a351e6"); + + private static bool WallBoundsZones(ModelGeometry geometry, Guid wall, ReadOnlySpan pairs) + { + if (pairs.IsEmpty || pairs.Length % 32 != 0) return false; + for (int i = 0; i < pairs.Length; i += 32) + { + var zone = new Guid(pairs.Slice(i, 16)); + var calculation = new Guid(pairs.Slice(i + 16, 16)); + if (geometry.Read(zone, ZoneClass) is null || + geometry.Read(calculation, ZoneBoundaryCalculationClass) is not { Length: >= 60 } body || + FindRelationshipSection(body, body.Length) != body.Length - 54) + return false; + var relationship = body.AsSpan(body.Length - 54); + // The calculation row uses the same relation as the wall, with the ordered Zone and Wall owners. + if (relationship[0] != 4 || new Guid(relationship[1..17]) != ZoneCalculationRelation || + BinaryPrimitives.ReadUInt32LittleEndian(relationship[17..]) != 2 || new Guid(relationship[21..37]) != zone || + new Guid(relationship[37..53]) != wall || relationship[53] != 0) + return false; + } + return true; + } + + private static PlaWallExtrusion? ReadWallExtrusion(ReadOnlySpan settings, PlaWallReferencePlan? plan, + PlaWallProfile? profile, Elevations planes, double home, PlaBoundingBox box) + { + if (settings[184] != 0 || BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1) return null; + var start = new PlaPlanPoint(ReadDouble(settings, 0), ReadDouble(settings, 8)); + var end = new PlaPlanPoint(ReadDouble(settings, 16), ReadDouble(settings, 24)); + + IReadOnlyList>? rings; + if (plan is { } rectangle) + { + double low = Math.Min(rectangle.OutsideOffset, rectangle.InsideOffset); + double high = Math.Max(rectangle.OutsideOffset, rectangle.InsideOffset); + double height = planes.Top - planes.Bottom; + rings = [[new(low, 0), new(high, 0), new(high, height), new(low, height)]]; + } + else + { + rings = profile is not null ? ReadStraightProfileSection(profile.Components) : null; + } + return rings is null ? null : BuildWallExtrusion(start, end, planes.Bottom + home, rings, box); + } + + private static PlaWallExtrusion? ReadDoorCutWallExtrusion(PlaWallReferencePlan plan, Elevations planes, double home, + PlaBoundingBox box, List<(double Station, double Width, double Bottom, double Top)> apertures) + { + double dx = plan.End.X - plan.Start.X, dy = plan.End.Y - plan.Start.Y; + double length = double.Hypot(dx, dy), height = planes.Top - planes.Bottom; + if (!(length > JunctionTolerance) || !double.IsFinite(length) || !(height > JunctionTolerance)) return null; + + // Sweep the perforated elevation across the thickness to keep each cut face in the wall boundary. + IReadOnlyList> rings = [[new(0, 0), new(length, 0), new(length, height), new(0, height)]]; + foreach (var (station, width, bottom, top) in apertures) + { + double left = station - width / 2, right = station + width / 2; + double low = Math.Max(0, bottom - planes.Bottom), high = Math.Min(height, top - planes.Bottom); + if (!(left > JunctionTolerance && right < length - JunctionTolerance && right > left && + high - low > JunctionTolerance) || + CombinePlanarContours(rings, [[new(left, low), new(left, high), new(right, high), new(right, low)]], + subtract: true) is not { } remainder) + return null; + rings = remainder; + } + + double max = Math.Max(plan.OutsideOffset, plan.InsideOffset), min = Math.Min(plan.OutsideOffset, plan.InsideOffset); + double rx = dy / length, ry = -dx / length; + return BuildWallExtrusion(new(plan.Start.X + rx * max, plan.Start.Y + ry * max), + new(plan.Start.X + rx * min, plan.Start.Y + ry * min), planes.Bottom + home, rings, box); + } + + private static PlaWallExtrusion? BuildWallExtrusion(PlaPlanPoint start, PlaPlanPoint end, double baseElevation, + IReadOnlyList> rings, PlaBoundingBox box) + { + double dx = end.X - start.X, dy = end.Y - start.Y; + double length = double.Hypot(dx, dy); + if (!(length > JunctionTolerance) || !double.IsFinite(length) || GroupPlanarContours(rings) is not { } sections) + return null; + + var points = rings.SelectMany(r => r).ToArray(); + double u0 = points.Min(p => p.X), u1 = points.Max(p => p.X); + double rightX = dy / length, rightY = -dx / length; + var xy = (Math.Min(start.X, end.X) + Math.Min(rightX * u0, rightX * u1), + Math.Min(start.Y, end.Y) + Math.Min(rightY * u0, rightY * u1), + Math.Max(start.X, end.X) + Math.Max(rightX * u0, rightX * u1), + Math.Max(start.Y, end.Y) + Math.Max(rightY * u0, rightY * u1)); + if (!SamePlan(xy, box.XMin, box.YMin, box.XMax, box.YMax) || + !(Math.Abs(baseElevation + points.Min(p => p.Y) - box.ZMin) <= JunctionTolerance && + Math.Abs(baseElevation + points.Max(p => p.Y) - box.ZMax) <= JunctionTolerance)) + return null; + + double volume = rings.Sum(SignedRingArea) * length; + if (!double.IsFinite(volume) || volume <= 0) return null; + var result = new List(sections.Length); + foreach (var section in sections) + { + var contours = new List>(section.Count); + foreach (var ring in section) + contours.Add(Array.AsReadOnly(ring.Select(p => new PlaProfilePoint(p.X, p.Y)).ToArray())); + result.Add(new PlaWallExtrusionSection(contours.AsReadOnly())); + } + return new PlaWallExtrusion(start, end, baseElevation, result.AsReadOnly(), volume); + } + + private static IReadOnlyList>? ReadStraightProfileSection(IReadOnlyList components) + { + IReadOnlyList>? combined = null; + double area = 0, perimeter = 0; + foreach (var component in components) + { + if (component.Arcs is { Count: > 0 } || component.Rings.Count == 0) return null; + var rings = new List>(component.Rings.Count); + foreach (var saved in component.Rings) + { + var ring = saved.Select(p => new PlaPlanPoint(p.U, p.Z)).ToArray(); + double signedArea = SignedRingArea(ring); + if (ring.Length < 3 || !double.IsFinite(signedArea) || signedArea == 0 || !IsSimpleRing(ring)) return null; + if (rings.Count > 0 && !IsSeparateHole(rings, ring)) return null; + if ((signedArea > 0) != (rings.Count == 0)) Array.Reverse(ring); + rings.Add(ring); + for (int i = 0; i < ring.Length; i++) perimeter += Distance(ring[i], ring[(i + 1) % ring.Length]); + } + area += rings.Sum(SignedRingArea); + combined = combined is null ? rings : CombinePlanarContours(combined, rings, subtract: false); + if (combined is null) return null; + } + // The saved material fills must partition the section. + return combined is not null && Math.Abs(combined.Sum(SignedRingArea) - area) <= JunctionTolerance * Math.Max(1, perimeter) + ? combined : null; + } + + private static bool SameWallExtrusion(PlaWallExtrusion? a, PlaWallExtrusion? b) => + a == b || a is not null && b is not null && a.Start == b.Start && a.End == b.End && + a.BaseElevation == b.BaseElevation && a.Volume == b.Volume && a.Sections.Count == b.Sections.Count && + 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))); +} diff --git a/src/PlaIO/Internal/ElementReader.WallProfiles.cs b/src/PlaIO/Internal/ElementReader.WallProfiles.cs new file mode 100644 index 0000000..473e0c2 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.WallProfiles.cs @@ -0,0 +1,167 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static PlaWallProfile? ReadWallProfile(ReadOnlySpan wall, ReadOnlySpan settings, + Guid wallId, ModelGeometry geometry) + { + if (settings.Length < 229 || BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) != 3 || + BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1 || + ReadWallProfileRecord(geometry, wallId, wall) is not { Length: >= 57 } profile || + BinaryPrimitives.ReadUInt16LittleEndian(profile.AsSpan(49)) != 1 || + BinaryPrimitives.ReadUInt16LittleEndian(profile.AsSpan(55)) != 2) + return null; + + int index = BinaryPrimitives.ReadInt32LittleEndian(profile.AsSpan(51)); + if (index <= 0 || ReadProfileComponents(ReadSectionVector(profile, 394)) is not { } components) return null; + return new PlaWallProfile(index, Array.AsReadOnly(components.Select(c => + new PlaWallProfileComponent(c.BuildingMaterialIndex, c.Function, c.CrossSectionArea, c.Rings, c.Arcs)).ToArray())); + } + + private static PlaMemberProfile? ReadMemberProfile(ReadOnlySpan member, Guid owner, bool beam, ModelGeometry geometry) + { + Guid ownerRelation = beam ? BeamMemoRelation : ColumnMemoRelation; + Guid memoId = ReadSingleRelation(member, ownerRelation, 0x11, requireSection: true); + if (geometry.Read(memoId, beam ? BeamMemoClass : ColumnMemoClass) is not { } memo || + ReadSingleRelation(memo, ownerRelation, requireSection: true) != owner) + return null; + + Guid sectionId = ReadSingleRelation(memo, SectionProfileRelation, 0x11, requireSection: true); + if (ReadComplexSectionProfile(geometry, memoId, sectionId) is not { Length: >= 57 } profile || + BinaryPrimitives.ReadUInt16LittleEndian(profile.AsSpan(47)) != 1 || + !profile.AsSpan(53).StartsWith(SectionVectorFrame)) + return null; + + int index = BinaryPrimitives.ReadInt32LittleEndian(profile.AsSpan(49)); + return index > 0 && ReadProfileComponents(ReadSectionVector(profile, 392)) is { } components + ? new PlaMemberProfile(index, components) : null; + } + + private static IReadOnlyList? ReadProfileComponents(ReadOnlySpan vector, + bool allowUnassignedMaterial = false) + { + var items = ReadFirstWallHatch(vector, out uint count); + if (items.IsEmpty) return null; + var components = new List(); + for (int i = 0; i < count; i++) + { + int size = ReadHatchSize(items, 2); + if (size == 0 || ReadProfileComponent(items[..size], allowUnassignedMaterial) is not { } component) return null; + components.Add(component); + items = items[size..]; + if (i + 1 == count) break; + if (items.Length < 16) return null; + items = items[16..]; + } + return items.IsEmpty ? components.AsReadOnly() : null; + } + + private static PlaProfileComponent? ReadProfileComponent(ReadOnlySpan hatch, bool allowUnassignedMaterial) + { + const int pointOffset = 59, pointSize = 16, arcSize = 16, tableHeader = 6, roleOffset = 108; + int material = BinaryPrimitives.ReadInt32LittleEndian(hatch[18..]); + int pointCount = BinaryPrimitives.ReadInt32LittleEndian(hatch[55..]); + int arcTable = pointOffset + pointCount * pointSize; + if (material < 0 || (material == 0 && !allowUnassignedMaterial) || pointCount > 4096 || + hatch.Length - arcTable < tableHeader || + !IsCorner(hatch[pointOffset..], 0, 0) || BinaryPrimitives.ReadUInt16LittleEndian(hatch[arcTable..]) != 1) + return null; + + int arcCount = BinaryPrimitives.ReadInt32LittleEndian(hatch[(arcTable + 2)..]); + int arcStart = arcTable + tableHeader; + if (arcCount < 0 || arcCount > pointCount || arcCount > (hatch.Length - arcStart) / arcSize) return null; + int ringTable = arcStart + arcCount * arcSize; + if (hatch.Length - ringTable < tableHeader || BinaryPrimitives.ReadUInt16LittleEndian(hatch[ringTable..]) != 1) + return null; + int ringEndCount = BinaryPrimitives.ReadInt32LittleEndian(hatch[(ringTable + 2)..]); + int ringStart = ringTable + tableHeader; + if (ringEndCount < 2 || ringEndCount > (pointCount - 1) / 4 + 1 || + ringEndCount > (hatch.Length - ringStart) / sizeof(int) || + BinaryPrimitives.ReadInt32LittleEndian(hatch[ringStart..]) != 0) + return null; + int footer = ringStart + ringEndCount * sizeof(int); + if (hatch.Length - footer <= roleOffset || + BinaryPrimitives.ReadInt32LittleEndian(hatch[(footer - sizeof(int))..]) != pointCount - 1) + return null; + + var sweeps = new Dictionary(arcCount); + for (int p = arcStart; p < ringTable; p += arcSize) + { + int start = BinaryPrimitives.ReadInt32LittleEndian(hatch[p..]); + int end = BinaryPrimitives.ReadInt32LittleEndian(hatch[(p + 4)..]); + double sweep = ReadDouble(hatch, p + 8); + if (start <= 0 || start >= pointCount - 1 || end != start + 1 || + !(Math.Abs(sweep) is > 0 and < Math.Tau) || !sweeps.TryAdd(start, sweep)) return null; + } + + var planRings = new List>(); + var boundaries = new List(); + var rings = new List>(); + var arcs = new List(); + double area = 0; + int first = 1; + for (int i = 1; i < ringEndCount; i++) + { + int last = BinaryPrimitives.ReadInt32LittleEndian(hatch[(ringStart + i * sizeof(int))..]); + if (last < first + 3 || last >= pointCount) return null; + var points = new PlaPlanPoint[last - first]; + var local = new PlaProfilePoint[points.Length]; + for (int j = 0; j < points.Length; j++) + { + int p = pointOffset + (first + j) * pointSize; + double u = ReadDouble(hatch, p), z = ReadDouble(hatch, p + 8); + if (!double.IsFinite(u) || !double.IsFinite(z)) return null; + points[j] = new(u, z); + local[j] = new(u, z); + } + if (!IsCorner(hatch[(pointOffset + last * pointSize)..], points[0].X, points[0].Y)) return null; + + double signedArea = SignedRingArea(points); + var edges = new SlabEdge[points.Length]; + for (int j = 0; j < points.Length; j++) + { + var p = points[j]; + var q = points[(j + 1) % points.Length]; + if (p == q) return null; + if (sweeps.Remove(first + j, out double sweep)) + { + if (ReadCircularEdge(p, q, sweep, out double segmentArea) is not { } edge) return null; + edges[j] = edge; + signedArea += segmentArea; + arcs.Add(new PlaProfileArc(i - 1, j, sweep)); + } + else edges[j] = new SlabEdge(p, q, 0); + } + if (!double.IsFinite(signedArea) || signedArea == 0 || !SlabRingIsSimple(edges) || + (i > 1 && !CurvedHoleFits(points, edges, planRings, boundaries))) return null; + area += (i == 1 ? 1 : -1) * Math.Abs(signedArea); + planRings.Add(points); + boundaries.Add(edges); + rings.Add(Array.AsReadOnly(local)); + first = last + 1; + } + if (sweeps.Count != 0 || !double.IsFinite(area) || area <= 0) return null; + string? function = hatch[footer + roleOffset] switch { 0 => "Other", 1 => "Core", _ => null }; + return new PlaProfileComponent(material, function, area, rings.AsReadOnly(), + arcs.Count == 0 ? null : arcs.AsReadOnly()); + } + + private static bool SameProfile(int? firstIndex, int? secondIndex, + IReadOnlyList? a, IReadOnlyList? b) + { + if (a is null || b is null) return a == b; + if (firstIndex != secondIndex || a.Count != b.Count) return false; + return a.Zip(b).All(pair => + { + var (first, second) = pair; + return (first.BuildingMaterialIndex, first.Function, first.CrossSectionArea) == + (second.BuildingMaterialIndex, second.Function, second.CrossSectionArea) && + first.Rings.Count == second.Rings.Count && + first.Rings.Zip(second.Rings).All(rings => rings.First.SequenceEqual(rings.Second)) && + (first.Arcs ?? []).SequenceEqual(second.Arcs ?? []); + }); + } +} diff --git a/src/PlaIO/Internal/ElementReader.WallReferencePlan.cs b/src/PlaIO/Internal/ElementReader.WallReferencePlan.cs new file mode 100644 index 0000000..83586c9 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.WallReferencePlan.cs @@ -0,0 +1,109 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static PlaWallReferencePlan? ReadWallReferencePlan(ReadOnlySpan settings, + out (double X0, double Y0, double X1, double Y1)? footprint, bool allowEmptyOutline = false) + { + footprint = null; + if (settings.Length < 251 || settings[184] != 0 || settings[238] > 1 || + BinaryPrimitives.ReadUInt16LittleEndian(settings[225..]) is not (1 or 2) || + BinaryPrimitives.ReadUInt16LittleEndian(settings[227..]) != 1 || + BinaryPrimitives.ReadUInt32LittleEndian(settings[239..]) > 4) + return null; + + double x = ReadDouble(settings, 0), y = ReadDouble(settings, 8); + double x1 = ReadDouble(settings, 16), y1 = ReadDouble(settings, 24); + double length = double.Hypot(x1 - x, y1 - y); + double thickness = ReadDouble(settings, 77), offset = ReadDouble(settings, 243); + if (!double.IsFinite(length) || length <= JunctionTolerance || + !double.IsFinite(thickness) || thickness <= JunctionTolerance || thickness != ReadDouble(settings, 85) || + !(offset >= 0 && offset <= thickness)) + return null; + + bool flipped = settings[238] == 1; + double outside = flipped ? offset : -offset; + double inside = flipped ? offset - thickness : thickness - offset; + double rightX = (y1 - y) / length, rightY = (x - x1) / length; + double min = Math.Min(outside, inside), max = Math.Max(outside, inside); + var plan = (Math.Min(x, x1) + Math.Min(rightX * min, rightX * max), + Math.Min(y, y1) + Math.Min(rightY * min, rightY * max), + Math.Max(x, x1) + Math.Max(rightX * min, rightX * max), + Math.Max(y, y1) + Math.Max(rightY * min, rightY * max)); + if (!(allowEmptyOutline && HasEmptyWallOutline(settings)) && !MatchesInlineWallRectangle(settings, + new(x + rightX * max, y + rightY * max), new(x1 + rightX * max, y1 + rightY * max), + new(x1 + rightX * min, y1 + rightY * min), new(x + rightX * min, y + rightY * min), plan)) + return null; + footprint = plan; + return new PlaWallReferencePlan(new PlaPlanPoint(x, y), new PlaPlanPoint(x1, y1), outside, inside); + } + + private static bool HasEmptyWallOutline(ReadOnlySpan settings) + { + if (settings.Length < 400) return false; + var outline = settings[256..323]; + return outline.StartsWith(new byte[] { 0, 0, 2, 1, 59, 0, 0, 0, 1, 31, 0 }) && + ReadDouble(outline, 11) == 1e35 && ReadDouble(outline, 19) == 1e35 && + ReadDouble(outline, 27) == -1e35 && ReadDouble(outline, 35) == -1e35 && + outline[43..].IndexOfAnyExcept((byte)0) < 0; + } + + private static bool HasUncachedDoorWallOutline(ReadOnlySpan wall, ReadOnlySpan settings) => + !HasWallBoxFrame(settings) && HasEmptyWallOutline(settings) && + FindRelationshipSection(wall, wall.Length) - 6 - (wall.Length - settings.Length) == 400 && + !ReadOpeningRelation(wall, DoorHostRelation).IsEmpty; + + private static (double X0, double Y0, double X1, double Y1)? ReadProfileWallRectangle(ReadOnlySpan settings, + PlaPlanPoint start, PlaPlanPoint end, double min, double max, bool allowPartial) + { + double length = double.Hypot(end.X - start.X, end.Y - start.Y); + if (!double.IsFinite(length) || length <= JunctionTolerance) return null; + double rx = (end.Y - start.Y) / length, ry = (start.X - end.X) / length; + var plan = (Math.Min(start.X, end.X) + Math.Min(rx * min, rx * max), Math.Min(start.Y, end.Y) + Math.Min(ry * min, ry * max), + Math.Max(start.X, end.X) + Math.Max(rx * min, rx * max), Math.Max(start.Y, end.Y) + Math.Max(ry * min, ry * max)); + if (MatchesInlineWallRectangle(settings, new(start.X + rx * max, start.Y + ry * max), + new(end.X + rx * max, end.Y + ry * max), new(end.X + rx * min, end.Y + ry * min), + new(start.X + rx * min, start.Y + ry * min), plan)) + return plan; + + if (!allowPartial || start.X != end.X && start.Y != end.Y || + !settings[256..].StartsWith(new byte[] { 0, 0, 2, 1, 247, 0, 0, 0, 0, 31, 0 }) || + ReadRectangularPlan(settings[256..]) is not { } rectangle) return null; + var along = ProjectRectangle(rectangle, start.X, start.Y, -ry, rx); + var across = ProjectRectangle(rectangle, start.X, start.Y, rx, ry); + // A horizontal profile slice can fix the transverse orientation by sharing an exterior face. + return Math.Abs(along.Min) <= JunctionTolerance && Math.Abs(along.Max - length) <= JunctionTolerance && + across.Min >= min - JunctionTolerance && across.Max <= max + JunctionTolerance && + (Math.Abs(across.Min - min) <= JunctionTolerance || Math.Abs(across.Max - max) <= JunctionTolerance) ? plan : null; + } + + private static bool MatchesInlineWallRectangle(ReadOnlySpan settings, PlaPlanPoint a, PlaPlanPoint b, + PlaPlanPoint c, PlaPlanPoint d, (double X0, double Y0, double X1, double Y1) plan) + { + if (settings.Length < 503) return false; + var polygon = settings[256..]; + ReadOnlySpan rectangle = [0, 0, 2, 1, 247, 0, 0, 0, 0, 31, 0]; + if (!polygon.StartsWith(rectangle) || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]) != 5 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[47..]) != 0 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[51..]) != 1 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[151..]) != 0 || + BinaryPrimitives.ReadUInt32LittleEndian(polygon[155..]) != 5 || + !polygon.Slice(71, 16).SequenceEqual(polygon.Slice(135, 16)) || + !SamePlan(plan, ReadDouble(polygon, 11), ReadDouble(polygon, 19), ReadDouble(polygon, 27), ReadDouble(polygon, 35))) + return false; + return MatchesCorner(polygon, 71, a) && MatchesCorner(polygon, 87, b) && + MatchesCorner(polygon, 103, c) && MatchesCorner(polygon, 119, d); + + static bool MatchesCorner(ReadOnlySpan record, int offset, PlaPlanPoint point) => + Math.Abs(ReadDouble(record, offset) - point.X) <= JunctionTolerance && + Math.Abs(ReadDouble(record, offset + 8) - point.Y) <= JunctionTolerance; + } + + private static bool SamePlan((double X0, double Y0, double X1, double Y1) plan, double x0, double y0, double x1, double y1) => + Math.Abs(plan.X0 - x0) <= JunctionTolerance && Math.Abs(plan.Y0 - y0) <= JunctionTolerance && + Math.Abs(plan.X1 - x1) <= JunctionTolerance && Math.Abs(plan.Y1 - y1) <= JunctionTolerance; +} diff --git a/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs b/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs new file mode 100644 index 0000000..8d577c1 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs @@ -0,0 +1,472 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private readonly record struct WallSlabOperation(Elevations Planes, IReadOnlyList> Rings, + int ExtrusionDirection = 0, uint Priority = uint.MaxValue, bool MayLoseMaterial = false); + private readonly record struct WallSlabSweep(Elevations Bounds, bool BottomConfirmed, bool TopConfirmed); + + private static List? ReadWallSlabOperations(ModelGeometry geometry, Guid wall, ReadOnlySpan pairs, + (double X0, double Y0, double X1, double Y1) footprint) + { + if (pairs.IsEmpty || pairs.Length % 32 != 0) return null; + var operands = new Dictionary(); + for (int i = 0; i < pairs.Length; i += 32) + { + var slab = new Guid(pairs.Slice(i, 16)); + var operation = new Guid(pairs.Slice(i + 16, 16)); + if (ReadSubtractionDirection(geometry, wall, slab, operation) is not { } direction || + !operands.TryAdd(slab, (operation, direction))) return null; + } + var operations = new List(); + var nested = new Dictionary>(); + foreach (var (slab, (operation, direction)) in operands) + { + if (geometry.Read(slab, SlabClass) is not { } operand) return null; + var record = operand.AsSpan(FindClassFrame(operand, SlabClass)); + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (ReadWallSlabPlan(geometry, record, settings, out var planes) is not { } rings) + return null; + + uint? priority = ReadSlabOperandPriority(settings, geometry.Attributes); + if (priority is not > 0) return null; + bool mayLoseMaterial = false; + bool hasReciprocal = false; + int? slabLayer = ReadElementLocation(record, "Slab", 0).LayerIndex; + if (!HasSupportedSlabContacts(record, Guid.Empty, Guid.Empty, + (role, id) => role == SlabWallRelation && SlabJunctionIsInactive(geometry, slab, slabLayer, id, fromWall: false) || + SlabContactKeepsCuttingBand(geometry, slab, role, id, priority.Value, 0, footprint, planes) || + WallMayCutOperator(role, id), + acceptsOperatorTarget: (target, link) => + { + if (!IsSlabOperatorTarget(geometry, target, slab, link)) return false; + if (target != wall) return true; + if (hasReciprocal || link != operation) return false; + hasReciprocal = true; + return true; + }, + acceptsTargetOperand: (other, link) => + { + // A nested subtraction cannot change the combined wall cut if the same cutter + // independently cuts the wall in the same direction. + if (!operands.TryGetValue(other, out var replacement) || replacement.Direction != direction || + ReadSubtractionDirection(geometry, slab, other, link) != direction || + geometry.Read(other, SlabClass) is not { } nestedOperand || + !HasOperationPair(nestedOperand, slab, link, operationTag: 2)) + return false; + if (!nested.TryGetValue(slab, out var cutters)) nested.Add(slab, cutters = []); + return cutters.Add(other); + }) || !hasReciprocal) + return null; + operations.Add(new WallSlabOperation(planes, rings, direction, MayLoseMaterial: mayLoseMaterial)); + + bool WallMayCutOperator(Guid role, Guid id) + { + if (!HasSlabWallPeerWithPriority(geometry, slab, role, id)) return false; + // Automatic wall cleanup can remove parts of the saved slab prism. + mayLoseMaterial = true; + return true; + } + } + + if (nested.Count == 0) return operations; + var ready = new Queue(operands.Keys.Where(slab => !nested.ContainsKey(slab))); + var dependents = nested.SelectMany(pair => pair.Value.Select(cutter => (Cutter: cutter, Dependent: pair.Key))) + .ToLookup(edge => edge.Cutter, edge => edge.Dependent); + int verified = 0; + while (ready.TryDequeue(out var cutter)) + { + verified++; + foreach (var dependent in dependents[cutter]) + if (nested[dependent].Remove(cutter) && nested[dependent].Count == 0) ready.Enqueue(dependent); + } + return verified == operands.Count ? operations : null; + } + + private static bool IsSlabOperatorTarget(ModelGeometry geometry, Guid target, Guid slab, Guid link) => + ReadSubtractionDirection(geometry, target, slab, link) is not null && + (geometry.Read(target, WallClass) ?? geometry.Read(target, SlabClass)) is { } other && HasOperationPair(other, slab, link); + + private static bool WallIsSubtractionOperator(ModelGeometry geometry, Guid wall, ReadOnlySpan pairs) + { + if (pairs.IsEmpty || pairs.Length % 32 != 0) return false; + for (int i = 0; i < pairs.Length; i += 32) + { + var target = new Guid(pairs.Slice(i, 16)); + var operation = new Guid(pairs.Slice(i + 16, 16)); + if (ReadSubtractionDirection(geometry, target, wall, operation) is null || + (geometry.Read(target, ElementAssemblyClass) ?? geometry.Read(target, SlabClass) ?? + geometry.Read(target, WallClass)) is not { } body || + !HasOperationPair(body, wall, operation)) return false; + } + return true; + } + + private static bool SlabJunctionIsInactive(ModelGeometry geometry, Guid owner, int? ownerLayer, Guid junction, bool fromWall) + { + var (role, peerRole, peerClass, peerType) = fromWall ? (WallSlabRelation, SlabWallRelation, SlabClass, "Slab") : + (SlabWallRelation, WallSlabRelation, WallClass, "Wall"); + if (ownerLayer is not { } layer || geometry.Attributes.LayerGroup.GetValueOrDefault(layer) is not { } group || + geometry.Read(junction, WallSlabJunctionClass) is not { } link || + ReadSingleRelation(link, role, requireSection: true) != owner) + return false; + Guid peerId = ReadSingleRelation(link, peerRole, requireSection: true); + if (geometry.Read(peerId, peerClass) is not { } peer || !HasGeometryRelation(peer, peerRole, junction) || + ReadElementLocation(peer.AsSpan(FindClassFrame(peer, peerClass)), peerType, 0).LayerIndex is not { } peerLayer || + geometry.Attributes.LayerGroup.GetValueOrDefault(peerLayer) is not { } peerGroup) return false; + return group == 0 || group != peerGroup; + } + + private static List? ReadWallJointSlabBands(ModelGeometry geometry, ElementLocation location, Guid wall, + WallStrip wallStrip, Elevations bounds, List<(Guid Id, Guid Key, uint Priority)> contacts, bool basic, + bool allowSharedBeamCoverage, + out List<(WallSlabOperation Cut, bool IsBottom)> completeCaps) + { + completeCaps = []; + if (geometry.StoryElevation(location.HomeStoryIndex) is not { } home) return null; + var bands = new List(); + foreach (var (joint, _, priority) in contacts) + { + if (ReadWallSlabContact(geometry, wall, joint, out Guid slab) is not { } body) return null; + var record = body.AsSpan(FindClassFrame(body, SlabClass)); + int? slabLayer = ReadElementLocation(record, "Slab", 0).LayerIndex; + if (location.LayerIndex is not { } wallLayer || slabLayer is not { } layer || + geometry.Attributes.LayerGroup.GetValueOrDefault(wallLayer) is not { } wallGroup || + geometry.Attributes.LayerGroup.GetValueOrDefault(layer) is not { } slabGroup) return null; + if (wallGroup == 0 || wallGroup != slabGroup) continue; + var settings = AfterCountedString(record, ClassElementIdOffset("Slab")); + if (ReadSlabPriority(settings, geometry.Attributes) is not { } maximum) return null; + if (maximum < priority) continue; + if (ReadWallSlabPlan(geometry, record, settings, out var planes) is not { } rings) return null; + bool composite = BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) == 2; + var skins = !composite + ? [new SlabSkin(planes.Top - planes.Bottom, maximum)] + : geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])); + if (skins is null) return null; + double high = planes.Top, cuttingBottom = double.PositiveInfinity, cuttingTop = double.NegativeInfinity; + foreach (var skin in skins) + { + if (!double.IsFinite(skin.Thickness) || skin.Thickness <= 0) return null; + double low = high - skin.Thickness; + // Only the part of a slab skin inside the wall's height can lose cutting coverage. + var band = new Elevations(Math.Max(low - home, bounds.Bottom), Math.Min(high - home, bounds.Top)); + if (skin.Priority >= priority && band.Top > band.Bottom) + { + bool mayLoseMaterial = false; + if (!HasSupportedSlabContacts(record, SlabWallRelation, joint, + (key, id) => key == SlabWallRelation && IsSameWallSlabPair(geometry, wall, slab, id) || + SlabContactKeepsCuttingBand(geometry, slab, key, id, skin.Priority, home, wallStrip.Footprint, band) || + allowSharedBeamCoverage && key == SlabBeamRelation && + SharedBeamPreservesSlabCoverage(geometry, wall, slab, id, location, home, priority, wallStrip.Footprint) || + MayLoseAfterWallContact(key, id), + acceptsOperatorTarget: (target, operation) => IsSlabOperatorTarget(geometry, target, slab, operation))) + return null; + bands.Add(new WallSlabOperation(new Elevations(low, high), rings, Priority: skin.Priority, + MayLoseMaterial: mayLoseMaterial)); + cuttingBottom = Math.Min(cuttingBottom, low); + cuttingTop = Math.Max(cuttingTop, high); + + bool MayLoseAfterWallContact(Guid role, Guid id) + { + if (!HasSlabWallPeerWithPriority(geometry, slab, role, id)) return false; + mayLoseMaterial = true; + return true; + } + } + high = low; + } + if (Math.Abs(high - planes.Bottom) > JunctionTolerance) return null; + double floor = bounds.Bottom + home, ceiling = bounds.Top + home; + bool lowerGap = planes.Bottom <= floor + JunctionTolerance && cuttingBottom > floor + JunctionTolerance; + bool upperGap = planes.Top >= ceiling - JunctionTolerance && cuttingTop < ceiling - JunctionTolerance; + if (basic && composite && settings[8] == 0 && double.IsFinite(cuttingBottom) && (lowerGap || upperGap) && + WallPlanHasGap(wallStrip.Footprint, [rings]) is false) + { + // A complete slab cut can remove the wall cap beyond its cutting skins. + if (ClipBySlab(geometry, location, record, settings, wallStrip.Footprint, bounds, bounds.Bottom, bounds.Top, + out var beams, priority, (wall, slab, joint), allowSharedBeamCoverage: allowSharedBeamCoverage) is not { } clip || + beams is not null) + return null; + if (lowerGap && clip.Bottom > bounds.Bottom && Math.Abs(clip.Bottom + home - cuttingTop) <= JunctionTolerance) + completeCaps.Add((new WallSlabOperation(new Elevations(floor, cuttingTop), rings, Priority: priority), true)); + if (upperGap && clip.Top < bounds.Top && Math.Abs(clip.Top + home - cuttingBottom) <= JunctionTolerance) + completeCaps.Add((new WallSlabOperation(new Elevations(cuttingBottom, ceiling), rings, Priority: priority), false)); + } + } + return bands; + } + + private static bool HasSlabWallPeerWithPriority(ModelGeometry geometry, Guid slab, Guid role, Guid id) => + ReadSlabWallPeer(geometry, slab, role, id, out Guid peer) is { } body && ReadWallPriority(geometry, peer, body) is > 0; + + private static Elevations? ResolveJoinedWallSlabs(ModelGeometry geometry, Guid wall, ElementLocation location, + ReadOnlySpan settings, WallStrip strip, Elevations bounds, List<(Guid Id, Guid Key, uint Priority)> contacts, + List? operations, bool basic, uint? compositePriority, List? doorCuts, + out bool unresolvedCoverage, out (double? Bottom, double? Top) verifiedEnds) + { + unresolvedCoverage = false; + verifiedEnds = default; + var slabs = contacts.Where(c => c.Key == WallSlabRelation).ToList(); + bool allowSharedBeamCoverage = basic && slabs.Count > 1 && operations is null && contacts.Exists(c => c.Key == WallBeamRelation); + if (slabs.Count == 0 || !basic && compositePriority is null || + contacts.Any(c => c.Key != WallSlabRelation && c.Key != FirstWallEndRelation && c.Key != SecondWallEndRelation && + !(allowSharedBeamCoverage && c.Key == WallBeamRelation)) || + ReadJoinedWallStrip(geometry, wall, strip, location) is not { } expanded || + ReadWallJointSlabBands(geometry, location, wall, expanded, bounds, slabs, basic, allowSharedBeamCoverage, + out var completeCaps) is not { Count: > 0 } bands) + return null; + if (operations is not null) bands.AddRange(operations); + unresolvedCoverage = bands.Exists(b => b.MayLoseMaterial); + uint strongest = compositePriority ?? slabs[0].Priority; + var strongestBands = bands.Where(b => b.Priority >= strongest).ToList(); + var skins = ReadWallSkinStrips(settings, geometry.Attributes, strip, slabs[0].Priority, strongest); + if (ResolveWallSlabOperations(geometry, location, expanded, bounds, strongestBands, []) is not { } outer) + { + verifiedEnds = ResolveSingleEnd(); + return null; + } + // Combine a separately verified cap with the sweep where the sweep already moves the opposite cap. + var extra = completeCaps.Where(c => c.IsBottom ? outer.Top < bounds.Top : outer.Bottom > bounds.Bottom) + .Select(c => c.Cut).ToArray(); + if (extra.Length != 0) + { + bands.AddRange(extra); + strongestBands.AddRange(extra); + if (ResolveWallSlabOperations(geometry, location, expanded, bounds, strongestBands, []) is not { } bothEnds) + return null; + outer = bothEnds; + } + if (outer == bounds && operations is null) + { + unresolvedCoverage = false; + return null; + } + + if (skins is null || ReadObstacles(outer) is not { } blocked) return null; + if (ResolveWallSlabOperations(geometry, location, strip, bounds, bands, blocked, skins) != outer) + { + verifiedEnds = ResolveSingleEnd(); + return null; + } + return outer; + + List? ReadObstacles(Elevations ends) + { + var result = new List(); + if (doorCuts is not null) result.AddRange(doorCuts); + foreach (var (id, key, priority) in contacts) + { + if (key == WallSlabRelation) continue; + if (!WallKeepsItsPlanes(geometry, wall, id, key, priority, location, ends, strip, basic, compositePriority, + result, out var levels, out _, trackPartialBeamCuts: allowSharedBeamCoverage) || levels != ends) return null; + } + return result; + } + + (double? Bottom, double? Top) ResolveSingleEnd() + { + if (skins is null || allowSharedBeamCoverage || completeCaps.Count != 0 || + geometry.StoryElevation(location.HomeStoryIndex) is not { } home || + SweepWallSlabOperations(home, expanded, bounds, strongestBands.Where(b => !b.MayLoseMaterial), [], null) + is not { Bounds: var envelope } || + ReadObstacles(envelope) is not { } obstacles || + SweepWallSlabOperations(home, strip, bounds, bands, obstacles, skins, confirmEndSections: true) is not { } inner) + return default; + + // The expanded wall with only guaranteed cuts encloses the evaluated wall. + // Material under every possible cut in the authored section is inside it. + return (inner.BottomConfirmed && inner.Bounds.Bottom == envelope.Bottom ? envelope.Bottom : null, + inner.TopConfirmed && inner.Bounds.Top == envelope.Top ? envelope.Top : null); + } + } + + private static (WallStrip Strip, uint Priority)[]? ReadWallSkinStrips(ReadOnlySpan settings, JunctionAttributes attributes, + WallStrip strip, uint lowest, uint highest) + { + if (lowest == highest) return [(strip, highest)]; + if (ReadWallReferencePlan(settings, out _) is not { } plan || + attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[229..])) is not { } skins) + return null; + double normal = strip.AlongX ? Math.Sign(plan.Start.X - plan.End.X) : Math.Sign(plan.End.Y - plan.Start.Y); + double edge = strip.Line + normal * plan.OutsideOffset; + double inside = strip.Line + normal * plan.InsideOffset; + if (Math.Abs(Math.Min(edge, inside) - strip.AcrossMin) > JunctionTolerance || + Math.Abs(Math.Max(edge, inside) - strip.AcrossMax) > JunctionTolerance) return null; + double sign = Math.Sign(inside - edge); + var result = new (WallStrip Strip, uint Priority)[skins.Length]; + for (int i = 0; i < skins.Length; i++) + { + var skin = skins[i]; + double next = edge + sign * skin.Thickness; + result[i] = (strip with { AcrossMin = Math.Min(edge, next), AcrossMax = Math.Max(edge, next) }, skin.Priority); + edge = next; + } + return Math.Abs(edge - inside) <= JunctionTolerance ? result : null; + } + + private static IReadOnlyList>? ReadWallSlabPlan(ModelGeometry geometry, + ReadOnlySpan record, ReadOnlySpan settings, out Elevations planes) + { + planes = default; + var polygon = ReadSlabOutline(settings); + if (geometry.StoryElevation(ReadElementLocation(record, "Slab", 0).HomeStoryIndex) is not { } home || + ReadElevations(record, "Slab") is not { } relative || ReadOutlineBounds(polygon) is null || + ReadStraightRings(polygon, out _) is not { } rings || + !HasVerticalSlabEdges(polygon[(int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[4..])..], + (int)BinaryPrimitives.ReadUInt32LittleEndian(polygon[43..]) - rings.Count) || + CheckedElevations(relative.Bottom + home, relative.Top + home) is not { } world || world.Top <= world.Bottom) + return null; + planes = world; + return rings; + } + + private static uint? ReadSlabOperandPriority(ReadOnlySpan settings, JunctionAttributes attributes) + { + if (ReadSlabPriority(settings, attributes) is not { } priority) return null; + return BinaryPrimitives.ReadUInt16LittleEndian(settings[83..]) == 1 ? priority : + attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..]))?.Min(s => s.Priority); + } + + private static int? ReadSubtractionDirection(ModelGeometry geometry, Guid target, Guid cutter, Guid operation) + { + if (target == Guid.Empty || cutter == Guid.Empty || target == cutter || + geometry.Read(operation, ElementAssemblyMemberClass) is not { Length: 144 } body || + FindRelationshipSection(body, body.Length) != 90) + return null; + uint type = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(52)); + double z = ReadDouble(body, 76); + // Both extrusion directions share the same operation code. + if (!(type == 1 && z == 0 || type == 3 && z is -1 or 1) || + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(56)) != 1 || ReadDouble(body, 60) != 0 || + ReadDouble(body, 68) != 0) return null; + var data = body.AsSpan(90); + return data[0] == 4 && new Guid(data.Slice(1, 16)) == ElementAssemblyRelation && + BinaryPrimitives.ReadUInt32LittleEndian(data[17..]) == 2 && new Guid(data[21..37]) == target && + new Guid(data[37..53]) == cutter && data[53] == 0 ? (int)z : null; + } + + private static bool HasOperationPair(ReadOnlySpan record, Guid other, Guid operation, byte operationTag = 1) + { + int start = FindRelationshipSection(record, record.Length); + if (start < 0) return false; + var data = record[start..]; + int occurrences = 0; + while (data.Length >= 17) + { + var entry = data; + if (!TryReadGeometryRelation(ref data, out byte tag, out Guid key, out _)) return false; + if (key != ElementAssemblyRelation) continue; + var pairs = ReadRelationIds(entry, data, tag); + if (tag is not (1 or 2) || pairs.IsEmpty || pairs.Length % 32 != 0) return false; + if (tag != operationTag) continue; + for (int i = 0; i < pairs.Length; i += 32) + if (new Guid(pairs.Slice(i, 16)) == other && new Guid(pairs.Slice(i + 16, 16)) == operation) occurrences++; + } + return occurrences == 1 && data is [0]; + } + + private static Elevations? ResolveWallSlabOperations(ModelGeometry geometry, ElementLocation location, WallStrip wall, + Elevations bounds, List operations, List blocked, + (WallStrip Strip, uint Priority)[]? skins = null) + { + if (geometry.StoryElevation(location.HomeStoryIndex) is not { } home || + wall.End - wall.Start <= JunctionTolerance || wall.AcrossMax - wall.AcrossMin <= JunctionTolerance) return null; + bool uncertain = operations.Exists(op => op.MayLoseMaterial); + if (SweepWallSlabOperations(home, wall, bounds, operations, blocked, skins, confirmEndSections: uncertain) + is not { BottomConfirmed: true, TopConfirmed: true, Bounds: var complete }) return null; + // Bracket the effects of edited operators by their original prisms and by omitting them. + if (!uncertain) return complete; + return SweepWallSlabOperations(home, wall, bounds, operations.Where(op => !op.MayLoseMaterial), blocked, skins)?.Bounds == complete + ? complete : null; + } + + private static WallSlabSweep? SweepWallSlabOperations(double home, WallStrip wall, Elevations bounds, + IEnumerable operations, List blocked, (WallStrip Strip, uint Priority)[]? skins, + bool confirmEndSections = false) + { + double floor = bounds.Bottom + home, ceiling = bounds.Top + home; + var cuts = operations.Select(o => (Low: o.ExtrusionDirection < 0 ? floor : Math.Max(floor, o.Planes.Bottom), + High: o.ExtrusionDirection > 0 ? ceiling : Math.Min(ceiling, o.Planes.Top), o.Rings, o.Priority)).Where(m => m.High > m.Low).ToArray(); + var heights = cuts.SelectMany(m => new[] { m.Low, m.High }).Append(floor).Append(ceiling).Distinct().Order().ToArray(); + var obstacles = blocked.Select(m => RectangleRing((wall with { Start = m.Span.Start, End = m.Span.End }).Footprint)).ToArray(); + double bottom = double.PositiveInfinity, top = double.NegativeInfinity; + bool bottomConfirmed = false, topConfirmed = false; + for (int i = 1; i < heights.Length; i++) + { + double lo = heights[i - 1], hi = heights[i]; + if (hi <= lo + JunctionTolerance) continue; + var active = cuts.Where(m => m.Low <= lo && m.High >= hi).ToArray(); + bool survives = false; + bool confirmed = false; + foreach (var (strip, priority) in skins ?? [(wall, 0u)]) + { + var masks = active.Where(m => m.Priority >= priority).Select(m => m.Rings).Concat(obstacles).ToArray(); + if (WallPlanHasGap(strip.Footprint, masks) is not { } hasGap) return null; + if (!hasGap) continue; + survives = true; + confirmed = !confirmEndSections || HasWallCapPatch(strip, (strip.Start, strip.End), masks); + if (confirmed) break; + } + if (!survives) continue; + if (lo < bottom) + { + bottom = lo; + bottomConfirmed = confirmed; + } + top = hi; + topConfirmed = confirmed; + } + return CheckedElevations(Math.Abs(bottom - floor) <= JunctionTolerance ? bounds.Bottom : bottom - home, + Math.Abs(top - ceiling) <= JunctionTolerance ? bounds.Top : top - home) is { } ends + ? new WallSlabSweep(ends, bottomConfirmed, topConfirmed) : null; + } + + private static IReadOnlyList> RectangleRing((double X0, double Y0, double X1, double Y1) box) => + [[new(box.X0, box.Y0), new(box.X1, box.Y0), new(box.X1, box.Y1), new(box.X0, box.Y1)]]; + + private static bool? WallPlanHasGap((double X0, double Y0, double X1, double Y1) box, + IReadOnlyList>> masks, Func? acceptsGap = null) + { + if (masks.Count == 0) return true; + if (masks.Sum(mask => mask.Sum(r => (long)r.Count)) > 4096) return null; + var perMask = masks.Select(mask => mask.SelectMany(r => r.Select((p, i) => new PlanarEdge(p, r[(i + 1) % r.Count]))).ToArray()).ToArray(); + var boundary = RectangleRing(box)[0]; + var edges = perMask.SelectMany(mask => mask).Concat(boundary.Select((p, i) => new PlanarEdge(p, boundary[(i + 1) % 4]))).ToArray(); + for (int i = 0; i < edges.Length; i++) + for (int j = i + 1; j < edges.Length; j++) + SplitPlanarEdges(edges[i], edges[j]); + + // Between consecutive vertices and crossings, the order of all boundary edges is fixed. + var slices = edges.SelectMany(e => e.Nodes.Select(n => n.Point.X)).Where(x => x > box.X0 && x < box.X1) + .Append(box.X0).Append(box.X1).Distinct().Order().ToArray(); + for (int i = 1; i < slices.Length; i++) + { + if (slices[i] <= slices[i - 1] + JunctionTolerance) continue; + double x = slices[i - 1] + (slices[i] - slices[i - 1]) / 2; + var intervals = new List<(double Start, double End)>(); + foreach (var mask in perMask) + { + var crossings = mask.Where(e => (e.Start.X > x) != (e.End.X > x)).Select(e => + e.Start.Y + (x - e.Start.X) / (e.End.X - e.Start.X) * (e.End.Y - e.Start.Y)).Order().ToArray(); + if (crossings.Length % 2 != 0 || crossings.Any(y => !double.IsFinite(y))) return null; + for (int j = 0; j < crossings.Length; j += 2) intervals.Add((crossings[j], crossings[j + 1])); + } + double end = box.Y0; + foreach (var (lo, hi) in intervals.OrderBy(p => p.Start)) + { + double stop = Math.Min(lo, box.Y1); + if (stop > end + JunctionTolerance && AcceptsGap(x, end, stop)) return true; + end = Math.Max(end, hi); + if (end >= box.Y1) break; + } + if (end < box.Y1 - JunctionTolerance && AcceptsGap(x, end, box.Y1)) return true; + } + return false; + + bool AcceptsGap(double x, double low, double high) => + acceptsGap is null || acceptsGap(new PlaPlanPoint(x, low + (high - low) / 2)); + } +} diff --git a/src/PlaIO/Internal/ElementReader.cs b/src/PlaIO/Internal/ElementReader.cs new file mode 100644 index 0000000..ca79895 --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.cs @@ -0,0 +1,727 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private const ushort ClassTableKind = 0xFDE9; + private const ushort DirectoryKind = 0xFDEA; + private const int ExtentUnit = 16; + private static readonly Guid DirectoryLayout = new("1f9b53da-bb9f-4f97-b5d9-532843923eac"); + private static readonly Guid ModelDatabaseClass = new("f6a0e521-443b-4eda-b20a-7160cbe09115"); + private static readonly Guid DatabaseElementList = new("bd9b270b-0347-4dcf-92cf-d2d872117ba1"); + private static readonly Guid GridStoreClass = new("e9969c7d-ebe2-42ff-a7dc-ed77e7e274c0"); + private static readonly Guid GridElementList = new("d940e8f4-4d66-4faa-86a1-6bf94c703228"); + private static readonly Guid ObjectClass = new("dbefcec3-1bbf-4867-b8b3-c4f7c859df61"); + private static readonly Guid DoorClass = new("d8f07689-9cfa-4fbe-aeb4-0a60b8e667ee"); + private static readonly Guid OpeningClass = new("6746aa79-7498-4bea-bad8-191cdad31d05"); + private static readonly Guid ZoneClass = new("3ad0332e-efe2-491a-92a6-5b14bfdd7229"); + private static readonly Guid ZoneStampRelation = new("5bbc9f04-754d-408b-8e1b-4f20c33cd868"); + private static readonly UnicodeEncoding Utf16 = new(false, false, true); + private static ReadOnlySpan ElementIdFrame => [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + private static ReadOnlySpan ClassFrame => [1, 0, 9, 0, 0x83, 0, 3, 0, 0, 1]; + + private static readonly Dictionary Names = new() + { + [new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")] = "Beam", + [new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e")] = "Column", + [new("c653c817-a855-4446-aef4-24efb46271aa")] = "CurtainWall", + [DoorClass] = "Door", + [new("342a8b55-7348-486a-850b-1eb1bed031fc")] = "Lamp", + [new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d")] = "Mesh", + [new("e6363c7b-940e-4deb-af95-8b3b39e86bd2")] = "Morph", + [ObjectClass] = "Object", + [OpeningClass] = "Opening", + [new("4c5ae61a-af17-4b85-93e0-005c987d5f5b")] = "Railing", + [new("9d4c7621-51e9-4523-a3ba-f2121777bcbe")] = "Roof", + [new("945c1275-7948-41d4-8744-9d22d72ca486")] = "Slab", + [new("fa0f7f15-29b4-4905-80fa-c6769109847b")] = "Stair", + [new("4f654582-33af-4e52-abfc-c35d46765ec4")] = "Wall", + [ZoneClass] = "Zone", + }; + + internal static bool HasClassTable(PlaDocument document) => + document.Blocks.Any(block => block.Tag == "BL" && block.Kind == ClassTableKind); + + internal static IReadOnlyList ReadClasses(PlaDocument document) + { + var tables = document.Blocks.Where(b => IsRawTable(b, ClassTableKind)).Take(2).ToArray(); + if (tables.Length != 1) + throw new InvalidDataException("The file must contain one supported object class table."); + + ReadOnlySpan data = document.ReadPayload(tables[0]); + if (data.Length < 18 || BinaryPrimitives.ReadUInt16LittleEndian(data) != 0) + throw new InvalidDataException("The object class table has an invalid header."); + + int slots = (data.Length - 2) / 16; + var classes = new List(); + for (int number = 0; number < slots; number++) + { + var guid = new Guid(data.Slice(2 + 16 * number, 16)); + if (guid == Guid.Empty) continue; + if (number > ushort.MaxValue) + throw new InvalidDataException("An object class number exceeds the directory field width."); + classes.Add(new PlaObjectClass((ushort)number, guid, Names.GetValueOrDefault(guid))); + } + if (classes.Count == 0 || data[(2 + 16 * slots)..].IndexOfAnyExcept((byte)0) >= 0) + throw new InvalidDataException("The object class table has no class GUIDs or has an invalid tail."); + return classes.AsReadOnly(); + } + + internal static IReadOnlyList Read(PlaDocument document, IReadOnlyList classes) + { + var types = classes.Where(c => c.Name is not null).ToDictionary(c => c.Number); + var databaseClasses = classes.Where(c => c.Guid == ModelDatabaseClass).Select(c => c.Number).ToHashSet(); + var propertyOverrideClasses = classes.Where(c => c.Guid == PropertyOverrideClass).Select(c => c.Number).ToHashSet(); + var labelClasses = classes.Where(c => c.Guid == ElementLabelClass).Select(c => c.Number).ToHashSet(); + bool useObjectRecords = databaseClasses.Count != 0 || types.Values.Any(c => c.Name == "Zone"); + var elements = new Dictionary(); + var directories = new Dictionary>(); + var databaseRecords = new Dictionary>(); + var sectionRecords = new Dictionary>(); + var libraryParameterRecords = new Dictionary>(); + var propertyOverrideRecords = new Dictionary>(); + var labelRecords = new Dictionary>(); + var sectionClasses = classes.Where(c => IsJunctionGeometryClass(c.Guid)) + .ToDictionary(c => c.Number, c => c.Guid); + var parameterClasses = classes.Where(c => c.Guid == LibraryParameterClass).Select(c => c.Number).ToHashSet(); + foreach (var block in document.Blocks) + { + if (!IsRawTable(block, DirectoryKind)) continue; + ReadOnlySpan data = document.ReadPayload(block); + int header = DirectoryHeaderSize(data, DirectoryLayout); + bool parameterDirectory = header == 0; + if (parameterDirectory) header = DirectoryHeaderSize(data, LibraryParameterDirectory); + if (header == 0) continue; + ulong length = BinaryPrimitives.ReadUInt64LittleEndian(data[(header - 40)..]); + var owner = new Guid(data.Slice(header - 32, 16)); + for (int i = header; i <= data.Length - DirectoryFinder.RecordSize; i += DirectoryFinder.RecordSize) + { + var record = DirectoryFinder.ReadRecord(data[i..]); + if (record.ObjectId == Guid.Empty || record.Count == 0 || record.Position > length || record.Count > length - record.Position) + continue; + + if (parameterClasses.Contains(record.ClassNumber)) + { + if (!libraryParameterRecords.TryGetValue(length, out var tables)) libraryParameterRecords.Add(length, tables = []); + tables.Add(record); + } + if (parameterDirectory) continue; + + if (record.ObjectId == owner && databaseClasses.Contains(record.ClassNumber)) + { + if (!databaseRecords.TryGetValue(length, out var roots)) databaseRecords.Add(length, roots = []); + roots.Add(record); + } + + if (sectionClasses.ContainsKey(record.ClassNumber)) + { + if (!sectionRecords.TryGetValue(length, out var sections)) sectionRecords.Add(length, sections = []); + sections.Add(record); + } + + if (propertyOverrideClasses.Contains(record.ClassNumber)) + { + if (!propertyOverrideRecords.TryGetValue(length, out var overrides)) + propertyOverrideRecords.Add(length, overrides = []); + overrides.Add(record); + } + if (labelClasses.Contains(record.ClassNumber)) + { + if (!labelRecords.TryGetValue(length, out var labels)) labelRecords.Add(length, labels = []); + labels.Add(record); + } + + if (!types.TryGetValue(record.ClassNumber, out var objectClass)) continue; + if (objectClass.Name != "Object") AddElement(elements, record.ObjectId, objectClass); + if (HasBasicParameters(objectClass.Name) && (objectClass.Name != "Object" || useObjectRecords)) + { + if (!directories.TryGetValue(length, out var records)) directories.Add(length, records = []); + records.Add(record); + } + } + } + + var parameters = new Dictionary(); + var indexedParameters = new Dictionary(); + var materialReferences = new Dictionary(); + var locations = new Dictionary(); + var elevations = new Dictionary(); + var retainedWallCaps = new Dictionary(); + var boxes = new Dictionary(); + var beamVolumes = new Dictionary(); + var beamAxes = new Dictionary(); + var wallReferencePlans = new Dictionary(); + var wallProfiles = new Dictionary(); + var wallExtrusions = new Dictionary(); + var wallDoors = new Dictionary?>(); + var wallsNeedingDoorSolids = new HashSet(); + var columnExtrusions = new Dictionary(); + var columnCutMeshes = new Dictionary(); + var memberProfiles = new Dictionary(); + var slabGeometry = new Dictionary(); + var slabOpeningSources = new Dictionary(); + var doorHosts = new Dictionary(); + var doorPlacements = new Dictionary(); + var doorLibraryParts = new Dictionary(); + var doorParameterLinks = new Dictionary(); + var pools = directories.Count != 0 || propertyOverrideRecords.Count != 0 ? document.FindCompressedPools() : []; + var doorParameterTables = elements.Values.Any(element => element.Guid == DoorClass) + ? ReadDoorParameterTables(pools, libraryParameterRecords) : new Dictionary(); + var openingLinks = new Dictionary(); + var openingGeometry = new Dictionary(); + var storyTable = new Lazy>(() => ReadStories(document, classes)); + var partitionTable = new Lazy>(() => ReadStoryPartitions(document, classes, storyTable.Value)); + var savedPropertyOverrides = new Dictionary(); + if (directories.Count != 0 || propertyOverrideRecords.Count != 0) + { + var grids = databaseRecords.Count == 0 ? null : ReadGridElements(document, classes); + var junctionAttributes = new Lazy(() => ReadJunctionAttributes(document, classes)); + var labelOwners = new Lazy(() => ReadLabelOwners(document, labelRecords, labelClasses)); + var window = new List(); + foreach (var pool in pools) + { + byte[] data = pool.Decode(); + ulong units = (ulong)(data.Length / ExtentUnit); + if (data.Length % ExtentUnit == 0 && propertyOverrideRecords.TryGetValue(units, out var overrides)) + ReadPropertyOverrideRecords(data, overrides, savedPropertyOverrides); + var sectionRows = sectionRecords.GetValueOrDefault(units); + if (data.Length % ExtentUnit == 0 && directories.TryGetValue(units, out var records)) + { + var placedElements = new HashSet(); + if (grids is not null && databaseRecords.TryGetValue(units, out var roots)) + { + foreach (var root in roots) + { + var database = ReadIndexedPayload(data, root); + if (database is not null) + ReadRelationshipElements(database, ModelDatabaseClass, DatabaseElementList, placedElements); + } + } + + var stampRecords = records.Any(r => types[r.ClassNumber].Name == "Zone") + ? records.Where(r => types[r.ClassNumber].Guid == ObjectClass).ToLookup(r => r.ObjectId) + : null; + var sections = sectionRows?.ToLookup(r => r.ObjectId); + var geometry = new ModelGeometry(data, sections, sectionClasses, junctionAttributes, storyTable, partitionTable, + labelOwners, doorParameterTables); + foreach (var record in records) + { + var objectClass = types[record.ClassNumber]; + bool isObject = objectClass.Name == "Object"; + if (isObject) + { + if (grids is null || grids.Contains(record.ObjectId) || !placedElements.Contains(record.ObjectId)) continue; + AddElement(elements, record.ObjectId, objectClass); + } + var body = ReadIndexedPayload(data, record); + if (body is null) continue; + int frame = FindClassFrame(body, objectClass.Guid); + const int objectFrameOffset = 49; + bool olderObject = isObject && frame < 0 && + FindClassFrame(body, ObjectClass, version: 0x82) == objectFrameOffset; + if (olderObject) frame = objectFrameOffset; + if (frame >= 0 && objectClass.Name is "Wall" or "Slab") + { + var reference = ReadMaterialReference(body.AsSpan(frame), objectClass.Name == "Wall"); + if (!materialReferences.TryAdd(record.ObjectId, reference) && materialReferences[record.ObjectId] != reference) + materialReferences[record.ObjectId] = default; + } + var fields = olderObject ? new BasicParameters(ReadFramedElementId(body.AsSpan(frame), 163), null, null) : + objectClass.Name == "Zone" && stampRecords is not null ? ReadZoneParameters(body, data, stampRecords) : + ReadBasicParameters(body, objectClass); + var location = frame >= 0 ? ReadElementLocation(body, objectClass.Name!, frame, olderObject) : default; + if (location != default && !locations.TryAdd(record.ObjectId, location) && locations[record.ObjectId] != location) + locations[record.ObjectId] = default; + (double X0, double Y0, double X1, double Y1)? wallFootprint = null; + PlaWallReferencePlan? wallPlan = null; + PlaWallProfile? wallProfile = null; + if (objectClass.Name == "Wall" && frame >= 0) + { + var wall = body.AsSpan(frame); + var settings = AfterCountedString(wall, 197); + wallPlan = ReadWallReferencePlan(settings, out wallFootprint, + allowEmptyOutline: HasUncachedDoorWallOutline(wall, settings)); + if (!wallReferencePlans.TryAdd(record.ObjectId, wallPlan) && wallReferencePlans[record.ObjectId] != wallPlan) + wallReferencePlans[record.ObjectId] = null; + wallProfile = ReadWallProfile(wall, settings, record.ObjectId, geometry); + if (!wallProfiles.TryAdd(record.ObjectId, wallProfile)) + { + var previous = wallProfiles[record.ObjectId]; + if (!SameProfile(previous?.ProfileIndex, wallProfile?.ProfileIndex, previous?.Components, wallProfile?.Components)) + wallProfiles[record.ObjectId] = null; + } + } + PlaMemberProfile? memberProfile = null; + if (frame >= 0 && objectClass.Name is ("Beam" or "Column")) + { + memberProfile = ReadMemberProfile(body.AsSpan(frame), record.ObjectId, objectClass.Name == "Beam", geometry); + if (!memberProfiles.TryAdd(record.ObjectId, memberProfile)) + { + var previous = memberProfiles[record.ObjectId]; + if (!SameProfile(previous?.ProfileIndex, memberProfile?.ProfileIndex, + previous?.Components, memberProfile?.Components)) + memberProfiles[record.ObjectId] = null; + } + } + if (objectClass.Name == "Door" && frame >= 0) + { + var door = body.AsSpan(frame); + Guid host = ReadDoorHost(door, record.ObjectId, geometry); + if (!doorHosts.TryAdd(record.ObjectId, host) && doorHosts[record.ObjectId] != host) + doorHosts[record.ObjectId] = Guid.Empty; + var placement = ReadDoorPlacement(geometry, door, host); + if (!doorPlacements.TryAdd(record.ObjectId, placement) && doorPlacements[record.ObjectId] != placement) + doorPlacements[record.ObjectId] = null; + var library = ReadDoorLibraryPart(geometry, door, record.ObjectId, out var parameterLink); + if (!doorLibraryParts.TryAdd(record.ObjectId, library) && doorLibraryParts[record.ObjectId] != library) + doorLibraryParts[record.ObjectId] = null; + if (!doorParameterLinks.TryAdd(record.ObjectId, parameterLink) && + doorParameterLinks[record.ObjectId] != parameterLink) + doorParameterLinks[record.ObjectId] = default; + } + if (objectClass.Name == "Opening" && frame >= 0) + { + var opening = body.AsSpan(frame); + var links = ReadOpeningLinks(opening, record.ObjectId, geometry, elements); + if (!openingLinks.TryAdd(record.ObjectId, links)) + { + var previous = openingLinks[record.ObjectId]; + if (previous.Host != links.Host) + openingLinks[record.ObjectId] = default; + else if (previous.Targets is null || links.Targets is null || + !previous.Targets.SequenceEqual(links.Targets)) + openingLinks[record.ObjectId] = previous with { Targets = null }; + } + var planes = ReadOpeningElevations(opening, record.ObjectId, fields.OpeningProfile, links, geometry, + elements, out var cutGeometry); + if (!openingGeometry.TryAdd(record.ObjectId, cutGeometry) && + !SameOpeningGeometry(openingGeometry[record.ObjectId], cutGeometry)) + openingGeometry[record.ObjectId] = null; + if (!elevations.TryAdd(record.ObjectId, planes) && elevations[record.ObjectId] != planes) + elevations[record.ObjectId] = null; + } + if (location.HomeStoryIndex.HasValue) + { + var framed = body.AsSpan(frame); + PlaBoundingBox? box = null; + PlaWallExtrusion? wallExtrusion = null; + List? isolatedDoors = null; + bool needsDoorSolid = false; + (double? Bottom, double? Top) retainedCap = default; + PlaColumnExtrusion? columnExtrusion = null; + PlaColumnCutMesh? columnCutMesh = null; + var bounds = objectClass.Name switch + { + "Column" => ReadColumnElevations(framed, record.ObjectId, location, geometry, memberProfile, + out box, out columnExtrusion, out columnCutMesh), + "Wall" => ReadWallElevations(framed, record.ObjectId, location, geometry, wallFootprint, wallPlan, + wallProfile, out box, out wallExtrusion, out isolatedDoors, out needsDoorSolid, out retainedCap), + _ => ReadElevations(framed, objectClass.Name!), + }; + if (bounds is { } planes && objectClass.Name is "Slab" or "Zone") + box = ReadFloorBox(framed, objectClass.Name, planes, geometry.StoryElevation(location.HomeStoryIndex)); + if (objectClass.Name == "Beam" && geometry.StoryElevation(location.HomeStoryIndex) is { } home) + { + var axis = ReadBeamReferenceAxis(framed, record.ObjectId, geometry); + if (!beamAxes.TryAdd(record.ObjectId, axis) && beamAxes[record.ObjectId] != axis) + beamAxes[record.ObjectId] = null; + bounds = ReadBeamGeometry(framed, record.ObjectId, geometry, memberProfile, axis, home, out box, out double? volume); + if (!beamVolumes.TryAdd(record.ObjectId, volume) && beamVolumes[record.ObjectId] != volume) + beamVolumes[record.ObjectId] = null; + } + if (bounds is not null && !elevations.TryAdd(record.ObjectId, bounds) && elevations[record.ObjectId] != bounds) + elevations[record.ObjectId] = null; + if (objectClass.Name == "Wall" && !retainedWallCaps.TryAdd(record.ObjectId, retainedCap) && + retainedWallCaps[record.ObjectId] != retainedCap) + retainedWallCaps[record.ObjectId] = default; + if (box is not null && !boxes.TryAdd(record.ObjectId, box) && boxes[record.ObjectId] != box) + boxes[record.ObjectId] = null; + if (objectClass.Name == "Wall" && !wallExtrusions.TryAdd(record.ObjectId, wallExtrusion) && + !SameWallExtrusion(wallExtrusions[record.ObjectId], wallExtrusion)) + wallExtrusions[record.ObjectId] = null; + if (objectClass.Name == "Wall" && !wallDoors.TryAdd(record.ObjectId, isolatedDoors) && + (isolatedDoors is null || wallDoors[record.ObjectId] is not { } previousDoors || + !isolatedDoors.SequenceEqual(previousDoors))) + wallDoors[record.ObjectId] = null; + if (needsDoorSolid) wallsNeedingDoorSolids.Add(record.ObjectId); + if (objectClass.Name == "Column" && !columnExtrusions.TryAdd(record.ObjectId, columnExtrusion) && + !SameColumnExtrusion(columnExtrusions[record.ObjectId], columnExtrusion)) + columnExtrusions[record.ObjectId] = null; + if (objectClass.Name == "Column" && !columnCutMeshes.TryAdd(record.ObjectId, columnCutMesh) && + !SameColumnCutMesh(columnCutMeshes[record.ObjectId], columnCutMesh)) + columnCutMeshes[record.ObjectId] = null; + if (objectClass.Name == "Slab") + { + SlabOpeningSources? sources = null; + var slab = box is not null ? ReadSlabGeometry(framed, record.ObjectId, geometry, box, out sources) : null; + if (!slabOpeningSources.TryAdd(record.ObjectId, sources)) + { + var previous = slabOpeningSources[record.ObjectId]; + slabOpeningSources[record.ObjectId] = sources is { } found && previous is { } known && + known.Openings.SequenceEqual(found.Openings) + ? known with { CanReconstructSolid = known.CanReconstructSolid && found.CanReconstructSolid } + : null; + } + if (!slabGeometry.TryAdd(record.ObjectId, slab)) + { + if (slab is null || slabGeometry[record.ObjectId] is not { } previous || + (previous.Bottom, previous.Top) != (slab.Bottom, slab.Top) || + previous.Rings.Count != slab.Rings.Count || + previous.Rings.Where((ring, i) => !ring.SequenceEqual(slab.Rings[i])).Any() || + !(previous.Arcs ?? []).SequenceEqual(slab.Arcs ?? [])) + slabGeometry[record.ObjectId] = null; + else if (previous.Volume != slab.Volume) + slabGeometry[record.ObjectId] = slab with { Volume = null }; + } + } + } + AddParameters(indexedParameters, record.ObjectId, fields); + } + } + + foreach (var subgroup in PoolSubgroupReader.ReadPool(data, window)) + { + if (subgroup.Partial || subgroup.Version != 1 || subgroup.ObjectId is not { } id || + !elements.TryGetValue(id, out var objectClass) || objectClass.Number != subgroup.Kind || + objectClass.Name is "Object" or "Zone" || !HasBasicParameters(objectClass.Name) || indexedParameters.ContainsKey(id)) + continue; + + AddParameters(parameters, id, ReadBasicParameters(subgroup.Data, objectClass)); + } + } + foreach (var (id, fields) in indexedParameters) parameters[id] = fields; + } + + var layerNames = locations.Count == 0 ? [] : ReadLayerNames(document, classes); + var stories = locations.Count == 0 ? [] : storyTable.Value; + var storyPartitions = stories.Count == 0 || !locations.Values.Any(l => l.TopStoryPartition != Guid.Empty) + ? [] : partitionTable.Value; + var classifications = ReadClassificationCatalog(document, classes, elements); + var propertyOverrides = ReadPropertyOverrides(document, classes, elements, savedPropertyOverrides); + var result = new List(elements.Count); + foreach (var (id, objectClass) in elements) + { + var fields = parameters.GetValueOrDefault(id); + var location = locations.GetValueOrDefault(id); + var material = materialReferences.GetValueOrDefault(id); + var links = openingLinks.GetValueOrDefault(id); + Guid hostId = objectClass.Name == "Door" ? doorHosts.GetValueOrDefault(id) : links.Host; + var host = locations.GetValueOrDefault(location.Host); + int? layer = objectClass.Name is "Door" or "Opening" ? host.LayerIndex : location.LayerIndex; + int? story = objectClass.Name == "Opening" ? host.HomeStoryIndex : location.HomeStoryIndex; + var homeStory = story is { } storyIndex ? stories.GetValueOrDefault(storyIndex) : default; + double? beamVolume = beamVolumes.GetValueOrDefault(id); + var bounds = story.HasValue && (objectClass.Name != "Opening" || fields.OpeningProfile is not null) + ? elevations.GetValueOrDefault(id) : null; + if (bounds is { StoredProjectBottom: { } boxBottom } wall && + homeStory.Elevation is { } storyElevation && !(Math.Abs(wall.Bottom + storyElevation - boxBottom) <= 1e-8)) + bounds = null; + var box = story.HasValue ? boxes.GetValueOrDefault(id) : null; + var extrusion = box is { } envelope ? wallExtrusions.GetValueOrDefault(id) ?? + ReadIsolatedDoorWall(id, bounds, homeStory.Elevation, envelope) : null; + if (extrusion is null && wallsNeedingDoorSolids.Contains(id)) + { + box = null; + bounds = null; + } + var retainedCap = story.HasValue && !elevations.ContainsKey(id) ? retainedWallCaps.GetValueOrDefault(id) : default; + double? bottom = bounds?.Bottom ?? retainedCap.Bottom; + double? top = bounds?.Top ?? retainedCap.Top; + result.Add(new PlaElement(id, objectClass.Name!, fields.ElementId, fields.WallThickness, fields.WallChordLength) + { + LayerIndex = layer, + LayerName = layer is { } layerIndex ? layerNames.GetValueOrDefault(layerIndex) : null, + HomeStoryIndex = story, + HomeStoryName = homeStory.Name, + TopLinkedStoryIndex = storyPartitions.GetValueOrDefault(location.TopStoryPartition), + BuildingMaterialIndex = material.Material, + CompositeIndex = material.Composite, + HostGuid = hostId != Guid.Empty ? hostId : null, + DoorDimensions = fields.DoorDimensions, + DoorPlacement = hostId != Guid.Empty ? doorPlacements.GetValueOrDefault(id) : null, + DoorWallHoleDimensions = FindDoorParameterTable(id)?.Dimensions, + LibraryPartReference = doorLibraryParts.GetValueOrDefault(id), + OpeningCutElementGuids = links.Targets, + OpeningProfile = fields.OpeningProfile, + OpeningGeometry = fields.OpeningProfile is not null && links.Host != Guid.Empty + ? openingGeometry.GetValueOrDefault(id) : null, + BoundingBox = box, + BeamReferenceAxis = story.HasValue ? beamAxes.GetValueOrDefault(id) : null, + BeamNetVolume = story.HasValue && (beamVolume == 0 || boxes.GetValueOrDefault(id) is not null) + ? beamVolume : null, + WallReferencePlan = wallReferencePlans.GetValueOrDefault(id), + WallProfile = wallProfiles.GetValueOrDefault(id), + WallExtrusion = extrusion, + ColumnExtrusion = story.HasValue && elevations.GetValueOrDefault(id) is not null ? columnExtrusions.GetValueOrDefault(id) : null, + ColumnCutMesh = story.HasValue && elevations.GetValueOrDefault(id) is not null ? columnCutMeshes.GetValueOrDefault(id) : null, + MemberProfile = memberProfiles.GetValueOrDefault(id), + Classifications = classifications.Systems.Count == 0 ? null : + classifications.Assignments.TryGetValue(id, out var assigned) ? assigned.AsReadOnly() : [], + PropertyOverrides = propertyOverrides.GetValueOrDefault(id), + SlabGeometry = story.HasValue && boxes.GetValueOrDefault(id) is not null && slabGeometry.GetValueOrDefault(id) is { } slab + ? ApplySlabOpenings(slab, id, slabOpeningSources.GetValueOrDefault(id), openingLinks, openingGeometry, parameters) + : null, + BottomElevationToHomeStory = bottom, + TopElevationToHomeStory = top, + BottomElevationToProjectZero = ToProjectZero(bottom, homeStory.Elevation), + TopElevationToProjectZero = ToProjectZero(top, homeStory.Elevation), + }); + } + return result.AsReadOnly(); + + DoorParameterTable? FindDoorParameterTable(Guid door) + { + return ResolveDoorParameterTable(doorParameterTables, doorParameterLinks.GetValueOrDefault(door)); + } + + PlaWallExtrusion? ReadIsolatedDoorWall(Guid wall, Elevations? bounds, double? storyElevation, PlaBoundingBox box) + { + if (wallDoors.GetValueOrDefault(wall) is not { } doors || + wallReferencePlans.GetValueOrDefault(wall) is not { } plan || + bounds is not { } planes || storyElevation is not double home) return null; + var apertures = new List<(double Station, double Width, double Bottom, double Top)>(doors.Count); + foreach (Guid door in doors) + { + if (doorHosts.GetValueOrDefault(door) != wall || + doorLibraryParts.GetValueOrDefault(door) != new PlaLibraryPartReference(SimpleDoorOpeningPart, SimpleDoorOpeningRevision) || + doorPlacements.GetValueOrDefault(door) is not { SillElevationToHostStory: { } sill } placement || + parameters.GetValueOrDefault(door).DoorDimensions is not { } nominal || + FindDoorParameterTable(door) is not { NoOversize: true, Dimensions: var dimensions } || + Math.Abs(nominal.Width - dimensions.Width) > JunctionTolerance || + Math.Abs(nominal.Height - dimensions.Height) > JunctionTolerance) + return null; + apertures.Add((placement.DistanceAlongWall, dimensions.Width, sill, sill + dimensions.Height)); + } + return ReadDoorCutWallExtrusion(plan, planes, home, box, apertures); + } + } + + private static bool IsRawTable(PlaBlock block, ushort kind) => + block.Tag == "BL" && block.Kind == kind && block.Version == 1 && block.Mode == PlaBlockMode.Raw; + + private static void AddElement(Dictionary elements, Guid id, PlaObjectClass objectClass) + { + if (!elements.TryAdd(id, objectClass) && elements[id].Guid != objectClass.Guid) + throw new InvalidDataException($"Object {id:D} has conflicting classes in the directories."); + } + + private static HashSet? ReadGridElements(PlaDocument document, IReadOnlyList classes) + { + var classNumbers = classes.Where(c => c.Guid == GridStoreClass).Select(c => c.Number).ToHashSet(); + var grids = new HashSet(); + foreach (var block in document.Blocks) + { + if (block.Tag != "BL" || !classNumbers.Contains(block.Kind)) continue; + if (block.Version != 1 || block.Mode != PlaBlockMode.Raw || + !ReadRelationshipElements(document.ReadPayload(block), GridStoreClass, GridElementList, grids)) + return null; + } + return grids; + } + + private static byte[]? ReadIndexedPayload(ReadOnlySpan pool, ObjectDirectoryRecord record) + { + int offset = (int)(record.Position * ExtentUnit); + var extent = pool.Slice(offset, (int)(record.Count * ExtentUnit)); + if (!BlockHeaderParser.TryParse(extent, 0, extent.Length, out var header, poolSubgroup: true) || + header.Tag != "BL" || header.Version != 1 || + header.Kind != record.ClassNumber || header.Guid != record.ObjectId || + (header.Flags & FdbFormat.FlagExtra) == 0 || header.End > extent.Length - sizeof(uint)) + return null; + + // In this directory layout the four-byte field is outside the packed size. + var packed = extent.Slice((int)header.PayloadOffset + sizeof(uint), (int)header.PackedSize); + if (header.Mode == PlaBlockMode.Raw) return packed.ToArray(); + if (header.Mode == PlaBlockMode.Lz) return QuickLzLevelOne.ReadFrames(packed, (int)header.UnpackedSize); + + var body = new byte[header.UnpackedSize]; + PayloadDecoder.DecodeZeroMask(packed, body, out int written, out _); + return written == body.Length ? body : null; + } + + private static bool ReadRelationshipElements(ReadOnlySpan data, Guid recordClass, + Guid listKind, HashSet elements) + { + const int bodyOffset = 39; + const int relationshipHeaderSize = sizeof(uint) + sizeof(ushort); + if (data.Length < bodyOffset + relationshipHeaderSize || new Guid(data[..16]) != recordClass) + return false; + uint bodySize = BinaryPrimitives.ReadUInt32LittleEndian(data[(bodyOffset - sizeof(uint))..]); + if (bodySize > data.Length - bodyOffset - relationshipHeaderSize) return false; + int sizeOffset = bodyOffset + (int)bodySize; + int relationshipOffset = sizeOffset + sizeof(uint); + if (BinaryPrimitives.ReadUInt32LittleEndian(data[sizeOffset..]) != data.Length - relationshipOffset || + BinaryPrimitives.ReadUInt16LittleEndian(data[relationshipOffset..]) != 1) + return false; + + Span marker = stackalloc byte[17]; + marker[0] = 1; + listKind.TryWriteBytes(marker[1..]); + var relationships = data[(relationshipOffset + sizeof(ushort))..]; + int start = relationships.IndexOf(marker); + if (start < 0 || relationships[(start + 1)..].IndexOf(marker) >= 0) return false; + var list = relationships[(start + marker.Length)..]; + if (list.Length < sizeof(uint)) + throw new InvalidDataException($"The element list {listKind:D} is missing its count."); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(list); + var guids = list[sizeof(uint)..]; + if (count > guids.Length / 16) + throw new InvalidDataException($"The element list {listKind:D} exceeds its relationship section."); + for (int i = 0; i < count; i++) elements.Add(new Guid(guids.Slice(i * 16, 16))); + return true; + } + + private static void AddParameters(Dictionary parameters, Guid id, BasicParameters fields) + { + if (fields.ElementId is null || parameters.TryAdd(id, fields) || parameters[id] == fields) return; + var basic = fields with { OpeningProfile = null, DoorDimensions = null }; + parameters[id] = (parameters[id] with { OpeningProfile = null, DoorDimensions = null }) == basic ? basic : default; + } + + private static int DirectoryHeaderSize(ReadOnlySpan data, Guid layout) + { + if (data.Length >= 40 && new Guid(data.Slice(24, 16)) == layout) return 40; + if (data.Length >= 42 && BinaryPrimitives.ReadUInt16LittleEndian(data) == 0 && + new Guid(data.Slice(26, 16)) == layout) return 42; + return 0; + } + + private static int ClassElementIdOffset(string? name) => name switch + { + "Slab" or "Morph" or "CurtainWall" or "Mesh" or "Opening" or "Railing" or "Stair" => 185, + "Roof" => 197, + "Door" => 286, + "Lamp" or "Object" => 289, + _ => 0, + }; + + private static bool HasBasicParameters(string? name) => + name is "Wall" or "Beam" or "Column" or "Zone" || ClassElementIdOffset(name) != 0; + + private static BasicParameters ReadZoneParameters(ReadOnlySpan zone, ReadOnlySpan pool, + ILookup stampRecords) + { + Span marker = stackalloc byte[19]; + marker[0] = 1; + marker[1] = 0; + marker[2] = 0x11; + ZoneStampRelation.TryWriteBytes(marker[3..]); + int start = zone.IndexOf(marker); + if (start < sizeof(uint) || zone.Length - start < marker.Length + 16 || + zone[(start + 1)..].IndexOf(marker) >= 0 || + BinaryPrimitives.ReadUInt32LittleEndian(zone[(start - sizeof(uint))..]) != zone.Length - start) + return default; + + var stampId = new Guid(zone.Slice(start + marker.Length, 16)); + string? elementId = null; + foreach (var record in stampRecords[stampId]) + { + var stamp = ReadIndexedPayload(pool, record); + if (stamp is null) continue; + string? value = ReadClassElementId(stamp, ObjectClass, ClassElementIdOffset("Object")); + if (value is null) continue; + if (elementId is not null && value != elementId) return default; + elementId = value; + } + return new BasicParameters(elementId, null, null); + } + + private static BasicParameters ReadBasicParameters(ReadOnlySpan data, PlaObjectClass objectClass) + { + int relativeOffset = ClassElementIdOffset(objectClass.Name); + if (objectClass.Name is "Opening" or "Door") + { + int frame = FindClassFrame(data, objectClass.Guid); + if (frame < 0 || relativeOffset > data.Length - frame || + BinaryPrimitives.ReadUInt16LittleEndian(data[(frame + relativeOffset - 2)..]) != 1) + return default; + string? elementId = ReadElementId(data[(frame + relativeOffset)..], out int consumed); + if (elementId is null) return default; + var settings = data[(frame + relativeOffset + consumed)..]; + return objectClass.Name == "Door" + ? new BasicParameters(elementId, null, null, DoorDimensions: ReadDoorDimensions(data[frame..], settings)) + : new BasicParameters(elementId, null, null, ReadOpeningProfile(settings)); + } + if (relativeOffset != 0) + return new BasicParameters(ReadClassElementId(data, objectClass.Guid, relativeOffset), null, null); + + BasicParameters result = default; + while (data.IndexOf(ElementIdFrame) is var offset && offset >= 0) + { + var value = data[(offset + ElementIdFrame.Length)..]; + data = data[(offset + 1)..]; + string? elementId = ReadElementId(value, out int consumed); + if (string.IsNullOrEmpty(elementId)) continue; + if (result.ElementId is not null) return default; + result = new BasicParameters(elementId, null, null); + if (objectClass.Name == "Wall" && value[consumed..] is { Length: >= 93 } tail) + { + double dx = BinaryPrimitives.ReadDoubleLittleEndian(tail[16..]) - BinaryPrimitives.ReadDoubleLittleEndian(tail); + double dy = BinaryPrimitives.ReadDoubleLittleEndian(tail[24..]) - BinaryPrimitives.ReadDoubleLittleEndian(tail[8..]); + double chord = Math.Sqrt(dx * dx + dy * dy); + double thickness = BinaryPrimitives.ReadDoubleLittleEndian(tail[85..]); + result = result with + { + WallChordLength = double.IsFinite(chord) && chord > 0 ? chord : null, + WallThickness = double.IsFinite(thickness) && thickness > 0 && + thickness == BinaryPrimitives.ReadDoubleLittleEndian(tail[77..]) ? thickness : null, + }; + } + } + return result; + } + + private static string? ReadClassElementId(ReadOnlySpan data, Guid classGuid, int relativeOffset) + { + int start = FindClassFrame(data, classGuid); + return start < 0 ? null : ReadFramedElementId(data[start..], relativeOffset); + } + + private static string? ReadFramedElementId(ReadOnlySpan frame, int offset) => + offset >= 2 && offset <= frame.Length && BinaryPrimitives.ReadUInt16LittleEndian(frame[(offset - 2)..]) == 1 + ? ReadElementId(frame[offset..], out _) + : null; + + private static int FindClassFrame(ReadOnlySpan data, Guid classGuid, byte version = 0x83) + { + Span frame = stackalloc byte[26]; + ClassFrame.CopyTo(frame); + frame[4] = version; + classGuid.TryWriteBytes(frame[ClassFrame.Length..]); + int start = data.IndexOf(frame); + return start < 0 || data[(start + 1)..].IndexOf(frame) >= 0 ? -1 : start; + } + + private static string? ReadElementId(ReadOnlySpan value, out int consumed) + { + var elementId = ReadCountedUnicode(value, out consumed); + if (elementId is null || !elementId.Any(char.IsControl)) return elementId; + consumed = 0; + return null; + } + + private static string? ReadCountedUnicode(ReadOnlySpan value, out int consumed) + { + consumed = 0; + if (value.Length < 4) return null; + uint units = BinaryPrimitives.ReadUInt32LittleEndian(value); + if (units > (value.Length - 4) / 2) return null; + int size = (int)units * 2; + try + { + string text = Utf16.GetString(value.Slice(4, size)); + consumed = 4 + size; + return text; + } + catch (DecoderFallbackException) + { + return null; + } + } + + private readonly record struct BasicParameters(string? ElementId, double? WallThickness, double? WallChordLength, + PlaOpeningProfile? OpeningProfile = null, PlaDoorDimensions? DoorDimensions = null); +} diff --git a/src/PlaIO/Internal/EmbeddedLibraryReader.cs b/src/PlaIO/Internal/EmbeddedLibraryReader.cs new file mode 100644 index 0000000..abf987a --- /dev/null +++ b/src/PlaIO/Internal/EmbeddedLibraryReader.cs @@ -0,0 +1,164 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static class EmbeddedLibraryReader +{ + private static readonly Guid AssetClass = new("6faaf82c-c131-4f8b-b1d9-9706144935dd"); + private static readonly Encoding AssetText = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); + + public static PlaEmbeddedLibraryCatalog Read(PlaDocument document, IReadOnlyList classes) + { + var kinds = classes.Where(c => c.Guid == AssetClass).Select(c => c.Number).ToHashSet(); + if (kinds.Count == 0) return new([], []); + var standalone = document.Blocks.Where(IsAsset).ToArray(); + var parts = new List(); + var unreadable = new SortedSet(); + int index = 0; + foreach (var pool in document.FindCompressedPools()) + { + while (index < standalone.Length && standalone[index].Offset < pool.Offset) + ReadStandalone(standalone[index++]); + int first = index; + while (index < standalone.Length && standalone[index].Offset < pool.End) + index++; + if (first == index && !StartsWithAsset(pool)) continue; + + byte[] decoded; + try + { + decoded = pool.Decode(); + } + catch (InvalidDataException) + { + unreadable.Add(pool.Offset); + for (int i = first; i < index; i++) ReadStandalone(standalone[i]); + continue; + } + // A physical index can see blocks through stored frames, even when their headers or payloads span frames. + using var stream = new MemoryStream(decoded, writable: false); + foreach (var block in new BlockScanner(stream, decoded.Length).Scan(startOffset: 0).Where(IsAsset)) + { + var packed = decoded.AsSpan((int)block.PayloadOffset, (int)block.PackedSize); + try + { + ReadPart(ReadPooledPayload(block, packed), block.Guid!.Value, pool.Offset); + } + catch (InvalidDataException) + { + unreadable.Add(pool.Offset); + } + } + } + while (index < standalone.Length) ReadStandalone(standalone[index++]); + return new(parts.AsReadOnly(), unreadable.ToList().AsReadOnly()); + + bool IsAsset(PlaBlock block) => kinds.Contains(block.Kind) && block.Tag == "BL" && block.Version == 1 && + block.Guid is { } id && id != Guid.Empty; + + bool StartsWithAsset(CompressedPool pool) + { + try + { + var prefix = document.ReadPoolPrefix(pool.Offset, FdbFormat.MaxBlockHeaderLength); + return BlockHeaderParser.TryParse(prefix, 0, pool.TotalDecompressed, out var block) && IsAsset(block); + } + catch (InvalidDataException) + { + // No indexed asset points to this pool, so its contents cannot identify it as an asset pool. + return false; + } + } + + void ReadStandalone(PlaBlock block) + { + try + { + ReadPart(document.ReadDirectoryPayload(block), block.Guid!.Value, block.Offset); + } + catch (InvalidDataException) + { + unreadable.Add(block.Offset); + } + } + + void ReadPart(byte[]? body, Guid id, long offset) + { + if (body is null || !TryReadPart(body, id, out var part)) + unreadable.Add(offset); + else if (part is not null) + parts.Add(part); + } + } + + private static byte[]? ReadPooledPayload(PlaBlock block, ReadOnlySpan packed) + { + if (block.Mode == PlaBlockMode.Raw) return packed.ToArray(); + if (block.Mode == PlaBlockMode.Lz) return QuickLzLevelOne.ReadFrames(packed, (int)block.UnpackedSize); + if ((block.UnpackedSize + 7) / 8 > packed.Length) return null; + var output = new byte[block.UnpackedSize]; + PayloadDecoder.DecodeZeroMask(packed, output); + return output; + } + + private static bool TryReadPart(byte[] body, Guid id, out PlaEmbeddedLibraryPart? part) + { + part = null; + var data = body.AsSpan(); + const int frame = 39; + if (data.Length < frame || new Guid(data[..16]) != AssetClass) return false; + uint length = BinaryPrimitives.ReadUInt32LittleEndian(data[(frame - 4)..]); + if (length > data.Length - frame) return false; + var asset = data.Slice(frame, (int)length); + if (!asset.StartsWith(new byte[] { 1, 0, 3, 0, 0 })) return false; + asset = asset[5..]; + if (!TryReadText(ref asset, out var name) || !TryReadText(ref asset, out var type)) return false; + if (type != "model/vnd.gs-gdl") return true; + + const int archiveHeaderSize = 32; + if (name.Length == 0 || asset.Length < archiveHeaderSize || !asset.StartsWith("MYSGCASG"u8)) return false; + uint size = BinaryPrimitives.ReadUInt32LittleEndian(asset[28..]); + var gsm = asset[archiveHeaderSize..]; + if (size != gsm.Length || gsm.Length < 128 || !gsm.StartsWith("WW.\0"u8) || + !gsm[40..].StartsWith("MYS"u8) || gsm[43] is not ((byte)'D' or (byte)'G' or (byte)'M' or (byte)'R' or (byte)'W') || + !(gsm[44..48].SequenceEqual("CASG"u8) || BinaryPrimitives.ReadUInt32LittleEndian(gsm[44..]) == 0) || + !gsm[48..].StartsWith("DAEH"u8) || + BinaryPrimitives.ReadUInt32LittleEndian(gsm[52..]) != 128) return false; + uint sections = BinaryPrimitives.ReadUInt32LittleEndian(gsm[36..]); + if (sections == 0 || sections > (gsm.Length - 128) / 16 || + BinaryPrimitives.ReadUInt32LittleEndian(gsm[56..]) != sections * 16) return false; + for (int i = 128; i < 128 + sections * 16; i += 16) + { + uint offset = BinaryPrimitives.ReadUInt32LittleEndian(gsm[(i + 4)..]); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(gsm[(i + 8)..]); + if (offset < 128 + sections * 16 || offset > size || count > size - offset) return false; + } + var family = new Guid(gsm[72..88]); + var revision = new Guid(gsm[88..104]); + if (family == Guid.Empty || revision == Guid.Empty) return false; + int offsetInBody = frame + (int)length - gsm.Length; + part = new(id, name, family, revision, body.AsMemory(offsetInBody, gsm.Length)); + return true; + } + + private static bool TryReadText(ref Span frame, out string value) + { + value = string.Empty; + if (frame.Length < 6 || BinaryPrimitives.ReadUInt16LittleEndian(frame) != 1) return false; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(frame[2..]); + if (count > (frame.Length - 6) / 2) return false; + int bytes = (int)count * 2; + try + { + value = AssetText.GetString(frame.Slice(6, bytes)); + } + catch (DecoderFallbackException) + { + return false; + } + frame = frame[(6 + bytes)..]; + return true; + } +} diff --git a/src/PlaIO/Internal/PoolReader.cs b/src/PlaIO/Internal/PoolReader.cs index dd3b2a5..4bc4d91 100644 --- a/src/PlaIO/Internal/PoolReader.cs +++ b/src/PlaIO/Internal/PoolReader.cs @@ -73,20 +73,49 @@ public static byte[] Decode(Stream stream, long length, long offset, long maxDec int written = 0; foreach (var frame in frames) { - Span output = decoded.AsSpan(written, frame.UnpackedSize); - if (frame.IsCompressed) - { - byte[] input = new byte[frame.PayloadLength]; - StreamReads.ReadExactlyAt(stream, frame.PayloadOffset, input, "a compressed pool frame"); - QuickLzLevelOne.Decode(input, output); - } + DecodeFrame(stream, frame, decoded.AsSpan(written, frame.UnpackedSize)); + written += frame.UnpackedSize; + } + return decoded; + } + + public static byte[] ReadPrefix(Stream stream, long length, long offset, int size, long maxDecodedBytes) + { + var (range, frames) = ReadLayout(stream, length, offset); + byte[] prefix = new byte[Math.Min(size, range.UnpackedSize)]; + int written = 0; + foreach (var frame in frames) + { + if (written == prefix.Length) break; + int count = Math.Min(prefix.Length - written, frame.UnpackedSize); + var target = prefix.AsSpan(written, count); + if (!frame.IsCompressed) + StreamReads.ReadExactlyAt(stream, frame.PayloadOffset, target, "a stored pool frame prefix"); else { - StreamReads.ReadExactlyAt(stream, frame.PayloadOffset, output, "a stored pool frame"); + if (frame.UnpackedSize > maxDecodedBytes) + throw InvalidPool(offset, $"a frame exceeds the reader's cap of {maxDecodedBytes} bytes"); + var decoded = new byte[frame.UnpackedSize]; + DecodeFrame(stream, frame, decoded); + decoded.AsSpan(0, count).CopyTo(target); } - written += output.Length; + written += count; + } + return prefix; + } + + private static void DecodeFrame(Stream stream, Frame frame, Span output) + { + if (frame.IsCompressed) + { + byte[] input = new byte[frame.PayloadLength]; + StreamReads.ReadExactlyAt(stream, frame.PayloadOffset, input, "a compressed pool frame"); + QuickLzLevelOne.Decode(input, output); + } + else + { + StreamReads.ReadExactlyAt(stream, frame.PayloadOffset, output, "a stored pool frame"); } - return decoded; } private static (PoolRange Range, List Frames) ReadLayout(Stream stream, long length, long offset) diff --git a/src/PlaIO/Internal/QuickLzLevelOne.cs b/src/PlaIO/Internal/QuickLzLevelOne.cs index 6bf553a..e632348 100644 --- a/src/PlaIO/Internal/QuickLzLevelOne.cs +++ b/src/PlaIO/Internal/QuickLzLevelOne.cs @@ -5,6 +5,56 @@ namespace PlaIO.Internal; // QuickLZ 1.5.0 level 1, without streaming. See docs/public-api.md for the public format reference. internal static class QuickLzLevelOne { + internal const int LongFrameHeaderSize = 9; + internal const int ShortFrameHeaderSize = 3; + + internal static bool TryReadFrameHeader(ReadOnlySpan data, long available, int remaining, + out FrameHeader frame) + { + frame = default; + if (data.Length < ShortFrameHeaderSize || (data[0] & 0xFC) != 0x44) return false; + bool longHeader = (data[0] & 2) != 0; + int size = longHeader ? LongFrameHeaderSize : ShortFrameHeaderSize; + if (data.Length < size) return false; + uint packed = longHeader ? BinaryPrimitives.ReadUInt32LittleEndian(data[1..]) : data[1]; + uint unpacked = longHeader ? BinaryPrimitives.ReadUInt32LittleEndian(data[5..]) : data[2]; + if (packed < size || packed > available || packed > Array.MaxLength || unpacked > remaining) return false; + bool compressed = (data[0] & 1) != 0; + long payload = packed - size; + if (compressed ? unpacked > 85 * payload : unpacked != payload) return false; + frame = new FrameHeader(size, (int)packed, (int)unpacked, compressed); + return true; + } + + internal static byte[]? ReadFrames(ReadOnlySpan data, int unpackedSize) + { + if (data.IsEmpty) return null; + var packed = data; + int remaining = unpackedSize; + while (!packed.IsEmpty) + { + if (!TryReadFrameHeader(packed, packed.Length, remaining, out var frame)) return null; + packed = packed[frame.PackedSize..]; + remaining -= frame.UnpackedSize; + } + if (remaining != 0) return null; + var body = new byte[unpackedSize]; + int written = 0; + while (!data.IsEmpty) + { + if (!TryReadFrameHeader(data, data.Length, unpackedSize - written, out var frame)) return null; + var source = data[frame.HeaderSize..frame.PackedSize]; + var target = body.AsSpan(written, frame.UnpackedSize); + if (frame.IsCompressed) Decode(source, target); + else source.CopyTo(target); + written += frame.UnpackedSize; + data = data[frame.PackedSize..]; + } + return body; + } + + internal readonly record struct FrameHeader(int HeaderSize, int PackedSize, int UnpackedSize, bool IsCompressed); + public static void Decode(ReadOnlySpan input, Span output) { Span matches = stackalloc int[4096]; diff --git a/src/PlaIO/Model/PlaBeamReferenceAxis.cs b/src/PlaIO/Model/PlaBeamReferenceAxis.cs new file mode 100644 index 0000000..079319d --- /dev/null +++ b/src/PlaIO/Model/PlaBeamReferenceAxis.cs @@ -0,0 +1,22 @@ +namespace PlaIO.Model; + +/// The directed reference axis saved with a straight or horizontally curved beam. +/// The start point in project XY coordinates. +/// The end point in project XY coordinates. +/// The start elevation in metres above project zero. +/// The end elevation in metres above project zero. +/// Zero for a straight axis or the signed circular sweep in plan. +/// Positive values turn counterclockwise from start to end. +public readonly record struct PlaBeamReferenceAxis(PlaPlanPoint Start, PlaPlanPoint End, + double StartElevationToProjectZero, double EndElevationToProjectZero, double PlanSweepRadians) +{ + private double Chord => double.Hypot(End.X - Start.X, End.Y - Start.Y); + private double Rise => EndElevationToProjectZero - StartElevationToProjectZero; + + /// The length in metres along the saved axis before junction cleanup. + public double Length => PlanSweepRadians == 0 ? double.Hypot(Chord, Rise) + : Chord * (PlanSweepRadians / (2 * Math.Sin(PlanSweepRadians / 2))); + + /// The signed inclination in radians, positive when the axis rises toward its end. + public double InclinationRadians => Math.Atan2(Rise, Chord); +} diff --git a/src/PlaIO/Model/PlaBoundingBox.cs b/src/PlaIO/Model/PlaBoundingBox.cs new file mode 100644 index 0000000..0ccbaf2 --- /dev/null +++ b/src/PlaIO/Model/PlaBoundingBox.cs @@ -0,0 +1,10 @@ +namespace PlaIO.Model; + +/// An axis-aligned 3D bounding box in metres in the project coordinate system. +/// The minimum X coordinate. +/// The minimum Y coordinate. +/// The minimum Z coordinate relative to project zero. +/// The maximum X coordinate. +/// The maximum Y coordinate. +/// The maximum Z coordinate relative to project zero. +public sealed record PlaBoundingBox(double XMin, double YMin, double ZMin, double XMax, double YMax, double ZMax); diff --git a/src/PlaIO/Model/PlaClassificationSystem.cs b/src/PlaIO/Model/PlaClassificationSystem.cs new file mode 100644 index 0000000..7b391b8 --- /dev/null +++ b/src/PlaIO/Model/PlaClassificationSystem.cs @@ -0,0 +1,25 @@ +namespace PlaIO.Model; + +/// A saved classification system and its visible item tree. +/// The system GUID. +/// The system name. +/// The system description. +/// The system source. +/// The saved version label. +/// The saved publication date, or null when absent. +/// The items in depth-first order, with siblings in saved order. +public sealed record PlaClassificationSystem(Guid Guid, string Name, string Description, string Source, + string Version, DateOnly? Date, IReadOnlyList Items); + +/// A saved classification item. +/// The item GUID. +/// The parent item GUID, or null for a top-level item. +/// The item identifier displayed in Archicad. +/// The item name. +/// The item description. +public sealed record PlaClassificationItem(Guid Guid, Guid? ParentGuid, string Id, string Name, string Description); + +/// An element's saved classification. +/// The GUID of the classification system. +/// The GUID of the assigned item in that system. +public readonly record struct PlaClassificationAssignment(Guid SystemGuid, Guid ItemGuid); diff --git a/src/PlaIO/Model/PlaColumnCutMesh.cs b/src/PlaIO/Model/PlaColumnCutMesh.cs new file mode 100644 index 0000000..464e8cd --- /dev/null +++ b/src/PlaIO/Model/PlaColumnCutMesh.cs @@ -0,0 +1,13 @@ +namespace PlaIO.Model; + +/// The evaluated boundary of a column whose remaining section varies along its height or width. +/// The mesh origin in project metres. +/// The vertices in metres relative to the origin. +/// The vertex indices of successive outward-facing triangles. +/// The tight bounds of the remaining solid in project metres. +/// The net volume in cubic metres. +public sealed record PlaColumnCutMesh(PlaColumnMeshPoint Origin, IReadOnlyList Vertices, + IReadOnlyList Indices, PlaBoundingBox BoundingBox, double Volume); + +/// A 3D point with coordinates in metres. +public readonly record struct PlaColumnMeshPoint(double X, double Y, double Z); diff --git a/src/PlaIO/Model/PlaColumnExtrusion.cs b/src/PlaIO/Model/PlaColumnExtrusion.cs new file mode 100644 index 0000000..d4bbdc0 --- /dev/null +++ b/src/PlaIO/Model/PlaColumnExtrusion.cs @@ -0,0 +1,43 @@ +namespace PlaIO.Model; + +/// The evaluated solid of a supported vertical, single-segment column. +/// The column axis in project XY metres. +/// The connected polygonal pieces of its horizontal section in XY metres relative to the axis. +/// Empty when the section is circular. +/// The lower face of the solid. +/// The upper face of the solid. +/// The tight bounds of this solid in project metres. +/// The volume of the evaluated solid in cubic metres, analytic for a circular section. +public sealed record PlaColumnExtrusion(PlaPlanPoint Origin, IReadOnlyList Sections, + PlaColumnEndPlane LowerPlane, PlaColumnEndPlane UpperPlane, PlaBoundingBox BoundingBox, double Volume) +{ + /// The separate horizontal spans left by an interior cut. Null means the solid spans both end planes. + public IReadOnlyList? Spans { get; internal init; } + + /// The analytic radius in metres for a circular section, or null for a polygonal section. + public double? CircularRadius { get; internal init; } + + /// The polygonal area of a horizontal circular cap in square metres, as used in listings. + public double? ScheduledCapArea { get; internal init; } + + /// The polygonal lateral surface area of the circular solid in square metres, when supported. + public double? ScheduledLateralArea { get; internal init; } + + /// The Archicad listing volume of the circular solid in cubic metres, when supported. + public double? ScheduledVolume => ScheduledCapArea * (UpperPlane.Elevation - LowerPlane.Elevation); +} + +/// An uninterrupted full-section span of a column. +/// The lower elevation relative to project zero in metres. +/// The upper elevation relative to project zero in metres. +public readonly record struct PlaColumnSpan(double Bottom, double Top); + +/// One connected column section with a counterclockwise exterior followed by clockwise holes. +/// The section boundaries, without repeated closing vertices. +public sealed record PlaColumnExtrusionSection(IReadOnlyList> Rings); + +/// An end plane whose elevation at local point (x, y) equals Elevation + SlopeX * x + SlopeY * y. +/// The plane elevation at the column axis in project metres. +/// The elevation change per metre along project X. +/// The elevation change per metre along project Y. +public readonly record struct PlaColumnEndPlane(double Elevation, double SlopeX, double SlopeY); diff --git a/src/PlaIO/Model/PlaDoorDimensions.cs b/src/PlaIO/Model/PlaDoorDimensions.cs new file mode 100644 index 0000000..27cc835 --- /dev/null +++ b/src/PlaIO/Model/PlaDoorDimensions.cs @@ -0,0 +1,10 @@ +namespace PlaIO.Model; + +/// The saved nominal dimensions of a Door. +/// The width in metres. +/// The height in metres. +public readonly record struct PlaDoorDimensions(double Width, double Height) +{ + /// The signed sill height in metres relative to its saved anchor, or null if unavailable. + public double? SillHeightFromAnchor { get; init; } +} diff --git a/src/PlaIO/Model/PlaDoorPlacement.cs b/src/PlaIO/Model/PlaDoorPlacement.cs new file mode 100644 index 0000000..538c590 --- /dev/null +++ b/src/PlaIO/Model/PlaDoorPlacement.cs @@ -0,0 +1,9 @@ +namespace PlaIO.Model; + +/// The placement of a Door on the reference line of its straight host wall. +/// The point on the wall reference line in project XY metres. +/// The distance in metres from the directed reference line start. +/// The nominal sill elevation in metres relative to project zero, if available. +/// The nominal sill elevation in metres relative to the wall's home story, if available. +public readonly record struct PlaDoorPlacement(PlaPlanPoint ReferencePoint, double DistanceAlongWall, + double? SillElevationToProjectZero, double? SillElevationToHostStory); diff --git a/src/PlaIO/Model/PlaDoorWallHoleDimensions.cs b/src/PlaIO/Model/PlaDoorWallHoleDimensions.cs new file mode 100644 index 0000000..1ec995c --- /dev/null +++ b/src/PlaIO/Model/PlaDoorWallHoleDimensions.cs @@ -0,0 +1,6 @@ +namespace PlaIO.Model; + +/// The saved GDL wall-hole dimensions of a Door instance, in metres. +/// The value of the instance's wall-hole width parameter. +/// The value of the instance's wall-hole height parameter. +public readonly record struct PlaDoorWallHoleDimensions(double Width, double Height); diff --git a/src/PlaIO/Model/PlaElement.cs b/src/PlaIO/Model/PlaElement.cs new file mode 100644 index 0000000..e966c15 --- /dev/null +++ b/src/PlaIO/Model/PlaElement.cs @@ -0,0 +1,116 @@ +namespace PlaIO.Model; + +/// A model element of a recognized class. +/// The element GUID stored in the file. +/// The recognized Archicad API element type. +/// The stored Element ID, or null if unavailable. +/// The thickness in metres of a recognized constant-width wall, or null. +/// The distance in metres between the endpoints of a wall's reference +/// line, or null. On a curved wall this is the chord length. +public sealed record PlaElement( + Guid Guid, + string Type, + string? ElementId, + double? WallThickness, + double? WallReferenceLineChordLength) +{ + /// The index of the effective layer in this project, or null if unavailable. + public int? LayerIndex { get; init; } + + /// The stored name of the effective layer, or null if unavailable. + public string? LayerName { get; init; } + + /// The project-relative home story number. It can be negative. Null means unavailable. + public int? HomeStoryIndex { get; init; } + + /// The stored home story name, or null if unavailable. A saved empty name is preserved. + public string? HomeStoryName { get; init; } + + /// The project-relative index of the story to which the element's top is linked, or null. + public int? TopLinkedStoryIndex { get; init; } + + /// The saved building material index of a supported basic wall or slab, or null. + public int? BuildingMaterialIndex { get; init; } + + /// The saved composite attribute index of a supported composite wall or slab, or null. + public int? CompositeIndex { get; init; } + + /// Saved assignments in system GUID order. Empty means no assignment in a readable catalog. + /// Null means the catalog is unavailable. + public IReadOnlyList? Classifications { get; init; } + + /// Saved user-defined property overrides in definition GUID order, or null when no override was read. + public IReadOnlyList? PropertyOverrides { get; init; } + + /// The verified GUID of a Door's wall or an Opening's associated element, or null if unavailable. + public Guid? HostGuid { get; init; } + + /// The nominal dimensions of a Door, or null if unavailable. + public PlaDoorDimensions? DoorDimensions { get; init; } + + /// The reference line position and nominal sill of a supported Door, or null if unavailable. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public PlaDoorPlacement? DoorPlacement { get; init; } + + /// The saved wall-hole dimensions supplied by the Door's GDL parameter table, or null. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public PlaDoorWallHoleDimensions? DoorWallHoleDimensions { get; init; } + + /// The library part identity from a Door's reciprocal saved descriptor, or null if unavailable. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public PlaLibraryPartReference? LibraryPartReference { get; init; } + + /// The verified GUIDs of elements cut by an Opening, or null if the list is unavailable. + public IReadOnlyList? OpeningCutElementGuids { get; init; } + + /// The base profile of an Opening, or null if unavailable. + public PlaOpeningProfile? OpeningProfile { get; init; } + + /// The project profile and verified slab cuts of a supported horizontal Opening, or null. + public PlaOpeningGeometry? OpeningGeometry { get; init; } + + /// The reference line and transverse placement of a supported straight wall, or null. + public PlaWallReferencePlan? WallReferencePlan { get; init; } + + /// The saved local cross-section of a supported complex-profile wall, or null if unavailable. + public PlaWallProfile? WallProfile { get; init; } + + /// The evaluated solid of a verified straight prismatic wall, or null. + [System.Text.Json.Serialization.JsonIgnore] + public PlaWallExtrusion? WallExtrusion { get; internal init; } + + /// The evaluated solid of a verified vertical column, or null. + [System.Text.Json.Serialization.JsonIgnore] + public PlaColumnExtrusion? ColumnExtrusion { get; internal init; } + + /// The evaluated mesh of a supported column cut by inclined beams, or null. + [System.Text.Json.Serialization.JsonIgnore] + public PlaColumnCutMesh? ColumnCutMesh { get; internal init; } + + /// The saved local cross-section of a supported single-segment beam or column, or null. + public PlaMemberProfile? MemberProfile { get; init; } + + /// The saved or reconstructed 3D bounding box in project coordinates, or null if unavailable. + public PlaBoundingBox? BoundingBox { get; init; } + + /// The saved beam reference axis in project coordinates, or null if unavailable. + public PlaBeamReferenceAxis? BeamReferenceAxis { get; init; } + + /// The evaluated beam volume in cubic metres, or null if unavailable. + public double? BeamNetVolume { get; init; } + + /// The saved slab outline and its volume when the slab is a verified vertical extrusion. + public PlaSlabGeometry? SlabGeometry { get; init; } + + /// The bottom elevation in metres relative to project zero, or null if unavailable. + public double? BottomElevationToProjectZero { get; init; } + + /// The top elevation in metres relative to project zero, or null if unavailable. + public double? TopElevationToProjectZero { get; init; } + + /// The bottom elevation in metres relative to the home story, or null if unavailable. + public double? BottomElevationToHomeStory { get; init; } + + /// The top elevation in metres relative to the home story, or null if unavailable. + public double? TopElevationToHomeStory { get; init; } +} diff --git a/src/PlaIO/Model/PlaEmbeddedLibraryCatalog.cs b/src/PlaIO/Model/PlaEmbeddedLibraryCatalog.cs new file mode 100644 index 0000000..1ae5f6b --- /dev/null +++ b/src/PlaIO/Model/PlaEmbeddedLibraryCatalog.cs @@ -0,0 +1,21 @@ +namespace PlaIO.Model; + +/// A catalog of the supported embedded GSM library parts in an FDB archive. +/// The verified parts in file order. +/// Physical offsets of standalone asset blocks or asset pools with unreadable data. +public sealed record PlaEmbeddedLibraryCatalog( + IReadOnlyList Parts, IReadOnlyList UnreadableAssetOffsets); + +/// A GSM library part preserved in the archive. +/// The archive record GUID. +/// The saved file name. +/// The main GUID in the GSM header. +/// The revision GUID in the archived GSM header. +/// The original GSM bytes, including its header and sections. +public sealed record PlaEmbeddedLibraryPart( + Guid AssetGuid, string Name, Guid LibraryPartGuid, Guid RevisionGuid, ReadOnlyMemory Data); + +/// The identity stored in a placed element's library part descriptor. +/// The main library part GUID. +/// The revision GUID referenced by the element. +public readonly record struct PlaLibraryPartReference(Guid LibraryPartGuid, Guid RevisionGuid); diff --git a/src/PlaIO/Model/PlaLayer.cs b/src/PlaIO/Model/PlaLayer.cs new file mode 100644 index 0000000..b8345d0 --- /dev/null +++ b/src/PlaIO/Model/PlaLayer.cs @@ -0,0 +1,8 @@ +namespace PlaIO.Model; + +/// A layer attribute in the saved project. +/// The layer's stored attribute GUID. +/// The positive, project-local layer index used by element records. +/// The saved name, or null if the file stores a localization token. +/// The stored intersection group, or null when unavailable. +public sealed record PlaLayer(Guid Guid, int Index, string? Name, uint? IntersectionGroup); diff --git a/src/PlaIO/Model/PlaLayoutBook.cs b/src/PlaIO/Model/PlaLayoutBook.cs new file mode 100644 index 0000000..2b64461 --- /dev/null +++ b/src/PlaIO/Model/PlaLayoutBook.cs @@ -0,0 +1,66 @@ +namespace PlaIO.Model; + +/// The saved layout book. +/// The navigator GUID of the book root. +/// Items in depth-first order, with siblings in saved order. +public sealed record PlaLayoutBook(Guid Guid, IReadOnlyList Items); + +/// An item in the layout book. +/// The navigator item GUID. +/// The parent item's GUID, or the book root GUID for a top-level item. +/// The Archicad navigator type label. +/// The saved name, or null if unavailable. +/// The item identifier displayed in the navigator, or null if unavailable. +/// The source GUID for a layout, master layout or drawing, or null if unavailable. +/// The saved source path of a placed drawing, or null if unavailable or inapplicable. +/// The saved paper size of a master layout or the size inherited by a layout. +public sealed record PlaLayoutBookItem(Guid Guid, Guid ParentGuid, string Type, string? Name, string? Id, + Guid? SourceGuid, string? DrawingSourcePath, PlaLayoutPaperSize? PaperSize) +{ + /// The GUID of the verified layout or master layout database, or null if unavailable. + public Guid? DatabaseGuid { get; init; } + + /// The navigator GUID of the master assigned to this layout, or null if unavailable or inapplicable. + public Guid? MasterLayoutGuid { get; init; } + + /// The saved revision status of a layout, or null if unavailable or inapplicable. + public PlaLayoutRevision? Revision { get; init; } +} + +/// The current document revision of a layout. +/// The revision ID, an empty string when there is no revision, or null if unavailable. +/// The display ID, an empty string when there is no revision, or null if unavailable. +/// Whether the layout has an issued revision. +/// Whether the layout has an open revision. +public sealed record PlaLayoutRevision(string? CurrentRevisionId, string? CurrentFinalRevisionId, + bool HasIssuedRevision, bool HasActualRevision) +{ + /// Issued revisions in saved order, oldest first. + public IReadOnlyList IssuedRevisions { get; init; } = []; + + /// The transmittal set of an open revision, or null if unavailable or inapplicable. + public PlaLayoutTransmittal? OpenTransmittal { get; init; } +} + +/// An issued revision in a layout's history. +/// The GUID of the revision record. +/// The revision ID. +/// The transmittal set that issued this revision. +public sealed record PlaIssuedLayoutRevision(Guid Guid, string Id, PlaLayoutTransmittal Transmittal); + +/// A layout revision's transmittal set. +/// The GUID of the transmittal set. +/// The saved transmittal ID. +/// The saved transmittal name. +/// The UTC issue time, or null while it is open. +/// The saved issuer, or null while it is open. +public sealed record PlaLayoutTransmittal(Guid Guid, string Id, string Name, DateTimeOffset? IssuedAtUtc, string? IssuedBy) +{ + /// Whether the transmittal uses its own ID for the revisions of every included layout. + public bool OverridesRevisionIds { get; init; } +} + +/// The dimensions of a master layout. +/// The paper width in metres. +/// The paper height in metres. +public readonly record struct PlaLayoutPaperSize(double Width, double Height); diff --git a/src/PlaIO/Model/PlaMaterialCatalog.cs b/src/PlaIO/Model/PlaMaterialCatalog.cs new file mode 100644 index 0000000..55df7be --- /dev/null +++ b/src/PlaIO/Model/PlaMaterialCatalog.cs @@ -0,0 +1,31 @@ +namespace PlaIO.Model; + +/// The saved building materials and composite definitions, sorted by project-local index. +/// The building materials. +/// The composite definitions. +public sealed record PlaMaterialCatalog(IReadOnlyList BuildingMaterials, IReadOnlyList Composites); + +/// A building material attribute used by model elements and composite skins. +/// The saved attribute GUID. +/// The positive project-local material index. +/// The saved attribute name. +/// The user-defined material ID, or null if unavailable. +/// The normalized intersection priority from 0 to 999, or null for an unsupported encoding. +public sealed record PlaBuildingMaterial(Guid Guid, int Index, string Name, string? Id, int? ConnectionPriority); + +/// A saved layered construction, in the attribute's skin order. +/// The saved attribute GUID. +/// The positive project-local composite index. +/// The saved attribute name. +/// The total thickness in metres. +/// The saved skins. Walls start at the outside face and slabs start at the top face. +/// The supported element types, or null if the stored usage flags are unsupported. +public sealed record PlaComposite(Guid Guid, int Index, string Name, double TotalThickness, + IReadOnlyList Skins, IReadOnlyList? UseWith); + +/// A layer in a composite definition. +/// The saved reference to a project-local building material. +/// The layer thickness in metres. +/// Whether the layer is part of the core. +/// Whether the layer is a finish. +public readonly record struct PlaCompositeSkin(int BuildingMaterialIndex, double Thickness, bool IsCore, bool IsFinish); diff --git a/src/PlaIO/Model/PlaMemberProfile.cs b/src/PlaIO/Model/PlaMemberProfile.cs new file mode 100644 index 0000000..b59a441 --- /dev/null +++ b/src/PlaIO/Model/PlaMemberProfile.cs @@ -0,0 +1,15 @@ +namespace PlaIO.Model; + +/// The saved cross-section of a supported single-segment beam or column. +/// The saved project-local profile attribute index. +/// The material fills in saved drawing order. +public sealed record PlaMemberProfile(int ProfileIndex, IReadOnlyList Components); + +/// A material fill in a saved cross-section. +/// The project-local building material index, or zero for an unassigned catalog fill. +/// The component role, or null if the saved role is unrecognized. +/// The fill area in square metres, including circular edges and excluding holes. +/// The exterior followed by its holes, in saved vertex order without repeated closing vertices. +/// The circular edges of the rings, or null when all edges are straight. +public record PlaProfileComponent(int BuildingMaterialIndex, string? Function, double CrossSectionArea, + IReadOnlyList> Rings, IReadOnlyList? Arcs); diff --git a/src/PlaIO/Model/PlaObjectClass.cs b/src/PlaIO/Model/PlaObjectClass.cs new file mode 100644 index 0000000..3c139de --- /dev/null +++ b/src/PlaIO/Model/PlaObjectClass.cs @@ -0,0 +1,7 @@ +namespace PlaIO.Model; + +/// A class in the file's object class table. +/// The class number local to this file. +/// The class GUID stored in the file. +/// The Archicad API label for a recognized class, or null. +public sealed record PlaObjectClass(ushort Number, Guid Guid, string? Name); diff --git a/src/PlaIO/Model/PlaOpeningGeometry.cs b/src/PlaIO/Model/PlaOpeningGeometry.cs new file mode 100644 index 0000000..921f8cb --- /dev/null +++ b/src/PlaIO/Model/PlaOpeningGeometry.cs @@ -0,0 +1,17 @@ +namespace PlaIO.Model; + +/// The plan profile and evaluated cut geometry of a supported horizontal Opening. +/// The profile center in project XY coordinates for a parametric shape, or the origin +/// of the saved polygon for a custom shape. +/// The straight profile rings in project XY, with implicit closure. Circular and elliptical +/// profiles use the Opening's width and height around . +/// The verified cut intervals by slab, or null if the cut geometry is unavailable. +/// The combined cut volume in cubic metres, or null if unavailable. +public sealed record PlaOpeningGeometry(PlaPlanPoint Origin, IReadOnlyList>? Rings, + IReadOnlyList? Cuts = null, double? CutVolume = null); + +/// A vertical interval where a slab is cut across the Opening profile. +/// The GUID of the cut slab. +/// The bottom elevation in metres relative to project zero. +/// The top elevation in metres relative to project zero. +public sealed record PlaOpeningCut(Guid SlabGuid, double Bottom, double Top); diff --git a/src/PlaIO/Model/PlaOpeningProfile.cs b/src/PlaIO/Model/PlaOpeningProfile.cs new file mode 100644 index 0000000..2231340 --- /dev/null +++ b/src/PlaIO/Model/PlaOpeningProfile.cs @@ -0,0 +1,7 @@ +namespace PlaIO.Model; + +/// The base profile of an Opening in its extrusion plane. +/// Rectangle, Square, Circle, Ellipse or Custom. +/// The profile width in metres. +/// The profile height in metres. +public sealed record PlaOpeningProfile(string Shape, double Width, double Height); diff --git a/src/PlaIO/Model/PlaProfileAttribute.cs b/src/PlaIO/Model/PlaProfileAttribute.cs new file mode 100644 index 0000000..d3e54aa --- /dev/null +++ b/src/PlaIO/Model/PlaProfileAttribute.cs @@ -0,0 +1,40 @@ +namespace PlaIO.Model; + +/// A saved complex profile definition. +/// The saved attribute GUID. +/// The positive project-local profile index. +/// The saved attribute name. +/// The enabled element types, or null for unsupported flags. +/// The maximum width of the undeformed section in metres, or null if unavailable. +/// The maximum height of the undeformed section in metres, or null if unavailable. +/// Whether a component is marked as core, or null if the section is unavailable. +/// The undeformed material fills in saved drawing order, or null if unavailable. +public sealed record PlaProfileAttribute(Guid Guid, int Index, string Name, IReadOnlyList? UseWith, + double? Width, double? Height, bool? HasCoreSkin, IReadOnlyList? Components) +{ + /// The saved width stretch setting, or null if unavailable. + public PlaProfileStretch? WidthStretch { get; init; } + + /// The saved height stretch setting, or null if unavailable. + public PlaProfileStretch? HeightStretch { get; init; } + + /// Verified named offset modifiers in saved order, or null if the list is unavailable. + public IReadOnlyList? Modifiers { get; init; } +} + +/// Cross-section stretch settings for one local axis. +/// Whether the saved profile can stretch along this axis. +/// The lower boundary in local metres, or null when disabled. +/// The upper boundary in local metres, or null when disabled. +/// The section size in metres after contracting the entire stretch zone, or null if unavailable. +public readonly record struct PlaProfileStretch(bool Enabled, double? Start, double? End, double? MinimumSize); + +/// The identity and saved name of a profile's offset modifier. +/// The GUID of the modifier in this profile. +/// The GUID of the shared named definition. +/// The saved modifier name. +public sealed record PlaProfileModifier(Guid Guid, Guid DefinitionGuid, string Name) +{ + /// The signed default offset in metres measured on the undeformed profile, or null if unavailable. + public double? DefaultValue { get; init; } +} diff --git a/src/PlaIO/Model/PlaPropertyCatalog.cs b/src/PlaIO/Model/PlaPropertyCatalog.cs new file mode 100644 index 0000000..13e5b59 --- /dev/null +++ b/src/PlaIO/Model/PlaPropertyCatalog.cs @@ -0,0 +1,40 @@ +namespace PlaIO.Model; + +/// User-defined property groups and definitions saved in the project. +/// The saved property groups in GUID order. +/// The saved property definitions in GUID order. +public sealed record PlaPropertyCatalog(IReadOnlyList Groups, IReadOnlyList Definitions); + +/// A saved user-defined property group. +/// The group GUID. +/// The group name. +public sealed record PlaPropertyGroup(Guid Guid, string Name); + +/// A saved user-defined property and its classification availability. +/// The property GUID. +/// The GUID of its property group. +/// The displayed name. +/// The saved description. +/// The Archicad data type label, or null for an unsupported encoding. +/// GUIDs of the classification items for which the property is available. +/// The saved choices for a supported enumeration, or null if unavailable or inapplicable. +/// The verified saved default, or null if unavailable. +public sealed record PlaPropertyDefinition(Guid Guid, Guid GroupGuid, string Name, string Description, string? DataType, + IReadOnlyList AvailableClassificationItemGuids, IReadOnlyList? Choices, + PlaPropertyValue? DefaultValue); + +/// A saved enumeration choice. +/// The stored GUID of the choice. +/// Its displayed label. +public sealed record PlaPropertyChoice(Guid Guid, string DisplayValue); + +/// The status and value of a saved property value or default. +/// One of normal, userUndefined or expression. +/// A literal string, integer, double or single choice GUID for a verified normal default. +/// Numeric measurements are in SI units. An undefined or expression default has no literal value. +public sealed record PlaPropertyValue(string Status, object? Value); + +/// A saved override of a user-defined property on an element. +/// The GUID of the property definition in the project catalog. +/// The stored value, or null for an unsupported encoding. +public sealed record PlaPropertyOverride(Guid DefinitionGuid, PlaPropertyValue? Value); diff --git a/src/PlaIO/Model/PlaSlabGeometry.cs b/src/PlaIO/Model/PlaSlabGeometry.cs new file mode 100644 index 0000000..3d31f61 --- /dev/null +++ b/src/PlaIO/Model/PlaSlabGeometry.cs @@ -0,0 +1,52 @@ +namespace PlaIO.Model; + +/// A point in the project XY plane, in metres. +/// The project X coordinate. +/// The project Y coordinate. +public readonly record struct PlaPlanPoint(double X, double Y); + +/// A circular edge of a slab outline. +/// The zero-based ring containing the edge. +/// The zero-based starting vertex. The edge ends at the next vertex, +/// wrapping to the first vertex if necessary. +/// The signed central angle in radians. Positive sweeps are counterclockwise. +public readonly record struct PlaSlabArc(int RingIndex, int StartVertexIndex, double SweepRadians); + +/// One connected part of an evaluated slab with vertical sides. +/// The counterclockwise exterior followed by clockwise holes, in project XY. +public sealed record PlaSlabPrism(IReadOnlyList> Rings); + +/// The saved slab outline and supported horizontal faces and solid volume. +/// The outer boundary followed by holes. Each ring closes implicitly. +/// The outer ring is counterclockwise and holes are clockwise when viewed from above. +/// The bottom elevation relative to project zero in metres. +/// The top elevation relative to project zero in metres. +/// The analytic area inside the saved outline after subtracting its holes, in square metres. +/// The reconstructed solid volume in cubic metres, or null when unavailable. +public sealed record PlaSlabGeometry(IReadOnlyList> Rings, + double Bottom, double Top, double OutlineArea, double? Volume) +{ + /// Whether the saved outline and elevations describe the whole slab as a vertical extrusion. + [System.Text.Json.Serialization.JsonIgnore] + public bool IsUncutVerticalPrism { get; internal init; } + + /// The evaluated solid as connected vertical extrusions from to + /// , or null when that reconstruction is unavailable. + [System.Text.Json.Serialization.JsonIgnore] + public IReadOnlyList? VerticalPrisms { get; internal init; } + + /// The circular edges of the saved rings, or null when every edge is straight. + public IReadOnlyList? Arcs { get; init; } + + /// The total length of the saved exterior and hole boundaries in metres, or null if unavailable. + public double? FloorPlanPerimeter { get; init; } + + /// The total length of the saved hole boundaries in metres, or null if unavailable. + public double? FloorPlanHolesPerimeter { get; init; } + + /// The top face area in square metres after saved holes and verified Opening cuts, or null. + public double? TopAreaWithOpenings { get; init; } + + /// The bottom face area in square metres after saved holes and verified Opening cuts, or null. + public double? BottomAreaWithOpenings { get; init; } +} diff --git a/src/PlaIO/Model/PlaStory.cs b/src/PlaIO/Model/PlaStory.cs new file mode 100644 index 0000000..4bcc57e --- /dev/null +++ b/src/PlaIO/Model/PlaStory.cs @@ -0,0 +1,7 @@ +namespace PlaIO.Model; + +/// A story in the saved project story table. +/// The signed number of the story relative to the project's story zero. +/// The saved story name. An empty name is preserved. +/// The elevation in metres, or null if unavailable. +public sealed record PlaStory(int Index, string Name, double? ElevationToProjectZero); diff --git a/src/PlaIO/Model/PlaWallExtrusion.cs b/src/PlaIO/Model/PlaWallExtrusion.cs new file mode 100644 index 0000000..0fdaa37 --- /dev/null +++ b/src/PlaIO/Model/PlaWallExtrusion.cs @@ -0,0 +1,15 @@ +namespace PlaIO.Model; + +/// A verified straight wall solid formed by sweeping vertical sections between two points in plan. +/// The start of the sweep in project XY metres. +/// The end of the sweep in project XY metres. +/// The project elevation of the section origin in metres. +/// The connected regions of the swept section, which may include openings. +/// The volume of the wall in cubic metres. +public sealed record PlaWallExtrusion(PlaPlanPoint Start, PlaPlanPoint End, double BaseElevation, + IReadOnlyList Sections, double Volume); + +/// The boundaries of one connected wall cross-section in local U/Z coordinates. +/// The counterclockwise exterior followed by clockwise holes. U points to the right +/// when looking from the sweep start to its end, and Z points up. +public sealed record PlaWallExtrusionSection(IReadOnlyList> Rings); diff --git a/src/PlaIO/Model/PlaWallProfile.cs b/src/PlaIO/Model/PlaWallProfile.cs new file mode 100644 index 0000000..1a937ea --- /dev/null +++ b/src/PlaIO/Model/PlaWallProfile.cs @@ -0,0 +1,27 @@ +namespace PlaIO.Model; + +/// The saved cross-section of a placed complex-profile wall. +/// The project-local profile attribute index. +/// The material fills in saved drawing order. +public sealed record PlaWallProfile(int ProfileIndex, IReadOnlyList Components); + +/// A material fill in a saved wall cross-section. +/// The project-local building material index. +/// The component role, or null if the saved role is unrecognized. +/// The fill area in square metres, including circular edges and excluding holes. +/// The exterior followed by its holes, in saved vertex order without repeated closing vertices. +/// The circular edges of the rings, or null when all edges are straight. +public sealed record PlaWallProfileComponent(int BuildingMaterialIndex, string? Function, double CrossSectionArea, + IReadOnlyList> Rings, IReadOnlyList? Arcs) + : PlaProfileComponent(BuildingMaterialIndex, Function, CrossSectionArea, Rings, Arcs); + +/// A point in the local coordinates of a saved profile, in metres. +/// The first saved coordinate in the profile plane. +/// The second saved coordinate in the profile plane. +public readonly record struct PlaProfilePoint(double U, double Z); + +/// A circular edge from the given vertex to its successor, wrapping within the ring. +/// The zero-based ring index. +/// The zero-based index of the first vertex in that ring. +/// The signed central angle in radians. Positive is counterclockwise in the profile plane. +public readonly record struct PlaProfileArc(int RingIndex, int StartVertexIndex, double SweepRadians); diff --git a/src/PlaIO/Model/PlaWallReferencePlan.cs b/src/PlaIO/Model/PlaWallReferencePlan.cs new file mode 100644 index 0000000..e20835d --- /dev/null +++ b/src/PlaIO/Model/PlaWallReferencePlan.cs @@ -0,0 +1,11 @@ +namespace PlaIO.Model; + +/// The saved reference line and transverse placement of a straight constant-width wall before junction cleanup. +/// The reference line start in project XY coordinates. +/// The reference line end in project XY coordinates. +/// The signed distance from the reference line to the outside face in metres. +/// Positive distances point to the right when looking from start to end. +/// The signed distance from the reference line to the inside face in metres, +/// using the same direction as . +public readonly record struct PlaWallReferencePlan(PlaPlanPoint Start, PlaPlanPoint End, + double OutsideOffset, double InsideOffset); diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 15abbc9..3e8f51e 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -103,6 +103,41 @@ public static PlaDocument Open(Stream stream, bool leaveOpen, PlaReaderOptions? /// The block is not one of the of this document. public byte[] ReadPayload(PlaBlock block) => ReadPayload(block, out _); + internal bool PayloadStartsWithClass(PlaBlock block, Guid expectedClass) + { + Span prefix = stackalloc byte[16]; + if (block.UnpackedSize < prefix.Length) return false; + if (block.Mode == PlaBlockMode.Raw) + { + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, prefix, "a block class GUID"); + } + else if (block.Mode == PlaBlockMode.ZeroMask) + { + Span packed = stackalloc byte[18]; + packed = packed[..(int)Math.Min(block.PackedSize, packed.Length)]; + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, packed, "a packed block class GUID"); + PayloadDecoder.DecodeZeroMask(packed, prefix, out int written, out _); + if (written != prefix.Length) return false; + } + else return false; + + return new Guid(prefix) == expectedClass; + } + + internal byte[]? ReadStandalonePayload(PlaBlock block) + { + if (block.PackedSize < QuickLzLevelOne.ShortFrameHeaderSize || block.PackedSize > Array.MaxLength) return null; + Span header = stackalloc byte[(int)Math.Min(block.PackedSize, QuickLzLevelOne.LongFrameHeaderSize)]; + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, header, "a standalone QuickLZ frame header"); + if (!QuickLzLevelOne.TryReadFrameHeader(header, block.PackedSize, (int)block.UnpackedSize, out _)) return null; + + var packed = new byte[block.PackedSize]; + header.CopyTo(packed); + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset + header.Length, packed.AsSpan(header.Length), + $"the payload of the block at 0x{block.Offset:x}"); + return QuickLzLevelOne.ReadFrames(packed, (int)block.UnpackedSize); + } + internal byte[] ReadPayload(PlaBlock block, out int consumed) { ArgumentNullException.ThrowIfNull(block); @@ -112,48 +147,71 @@ internal byte[] ReadPayload(PlaBlock block, out int consumed) if (index < 0 || !ReferenceEquals(_blocks[index], block)) throw new ArgumentException($"The block at 0x{block.Offset:x} is not in the block index of this document.", nameof(block)); + return DecodePayload(block, out consumed); + } + + internal PlaBlock? ReadDirectoryBlock(long origin, ObjectDirectoryRecord record) + { + if (origin < 0 || origin > Length || record.Position > (ulong)(Length - origin) / 16) return null; + long offset = origin + (long)record.Position * 16; + long length = (long)record.Count * 16; + if (length < 11 || length > Length - offset) return null; + + Span header = stackalloc byte[43]; + header = header[..(int)Math.Min(header.Length, length)]; + StreamReads.ReadExactlyAt(_stream, offset, header, $"a directory block header at 0x{offset:x}"); + return BlockHeaderParser.TryParse(header, offset, offset + length, out var block) && + block.Tag == "BL" && block.Version == 1 && block.Guid == record.ObjectId && block.Kind == record.ClassNumber + ? block : null; + } + + internal byte[]? ReadDirectoryPayload(PlaBlock block) => + block.Mode == PlaBlockMode.Lz ? ReadStandalonePayload(block) : DecodePayload(block, out _); + + private byte[] DecodePayload(PlaBlock block, out int consumed) + { switch (block.Mode) { case PlaBlockMode.Raw: - { - // The index accepts raw payloads of at most 2^28 bytes, so the size fits an array. - var payload = new byte[block.PackedSize]; - StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, payload, $"the payload of the block at 0x{block.Offset:x}"); - consumed = payload.Length; - return payload; - } - case PlaBlockMode.ZeroMask: - { - // A mask byte yields at most 8 bytes, so a larger declared size cannot decode; reject it before allocating. - if ((block.UnpackedSize + 7) / 8 > block.PackedSize) - throw new InvalidDataException($"Mode-1 block at 0x{block.Offset:x} declares {block.UnpackedSize} unpacked bytes from {block.PackedSize} packed bytes; a mask byte yields at most 8."); - long needed = Math.Min(block.PackedSize, block.UnpackedSize + (block.UnpackedSize + 7) / 8); - var source = new byte[needed]; - StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, source, $"the payload of the block at 0x{block.Offset:x}"); - var payload = new byte[block.UnpackedSize]; - try { - consumed = PayloadDecoder.DecodeZeroMask(source, payload); + // The index accepts raw payloads of at most 2^28 bytes, so the size fits an array. + var payload = new byte[block.PackedSize]; + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, payload, $"the payload of the block at 0x{block.Offset:x}"); + consumed = payload.Length; + return payload; } - catch (InvalidDataException e) + case PlaBlockMode.ZeroMask: { - throw new InvalidDataException($"Block at 0x{block.Offset:x}: {e.Message}", e); + // A mask byte yields at most 8 bytes, so a larger declared size cannot decode; reject it before allocating. + if ((block.UnpackedSize + 7) / 8 > block.PackedSize) + throw new InvalidDataException($"Mode-1 block at 0x{block.Offset:x} declares {block.UnpackedSize} unpacked bytes from {block.PackedSize} packed bytes; a mask byte yields at most 8."); + long needed = Math.Min(block.PackedSize, block.UnpackedSize + (block.UnpackedSize + 7) / 8); + var source = new byte[needed]; + StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, source, $"the payload of the block at 0x{block.Offset:x}"); + var payload = new byte[block.UnpackedSize]; + try + { + consumed = PayloadDecoder.DecodeZeroMask(source, payload); + } + catch (InvalidDataException e) + { + throw new InvalidDataException($"Block at 0x{block.Offset:x}: {e.Message}", e); + } + return payload; } - return payload; - } case PlaBlockMode.Lz: - { - // The mode-2 token stream references the decompressed output of all preceding blocks, so the whole - // file is decoded from the start and the requested block's output is returned. The cost of a call - // therefore grows with the size of the file. A preceding block that does not decode is a scanner - // false positive and not part of the real stream, so it is skipped. - var window = GlobalStreamDecoder.DecodePrefix(this, block, _options.MaxGlobalStreamBytes); - // The cap is a property of the whole window and the requested block is part of it, so the check runs - // before the block's buffer is allocated. - if (window.Count + block.UnpackedSize > _options.MaxGlobalStreamBytes) - throw new InvalidDataException($"The decoded global stream would grow past {_options.MaxGlobalStreamBytes} bytes (the reader's cap) at the block at 0x{block.Offset:x}."); - return ReadLzPayload(block, window, out _, out consumed); - } + { + // The mode-2 token stream references the decompressed output of all preceding blocks, so the whole + // file is decoded from the start and the requested block's output is returned. The cost of a call + // therefore grows with the size of the file. A preceding block that does not decode is a scanner + // false positive and not part of the real stream, so it is skipped. + var window = GlobalStreamDecoder.DecodePrefix(this, block, _options.MaxGlobalStreamBytes); + // The cap is a property of the whole window and the requested block is part of it, so the check runs + // before the block's buffer is allocated. + if (window.Count + block.UnpackedSize > _options.MaxGlobalStreamBytes) + throw new InvalidDataException($"The decoded global stream would grow past {_options.MaxGlobalStreamBytes} bytes (the reader's cap) at the block at 0x{block.Offset:x}."); + return ReadLzPayload(block, window, out _, out consumed); + } default: throw new NotSupportedException($"Block at 0x{block.Offset:x} uses an unknown payload mode {block.Mode}."); } @@ -213,6 +271,67 @@ public IReadOnlyList FindDirectories() return found.AsReadOnly(); } + /// Whether the block index contains an object class table, before checking its contents. + public bool HasObjectClassTable => ElementReader.HasClassTable(this); + + /// Reads the file's object class numbers and GUIDs, with names for recognized classes. + /// A supported class table is missing, malformed or ambiguous. + public IReadOnlyList ReadObjectClasses() + { + ObjectDisposedException.ThrowIf(_disposed, this); + return ElementReader.ReadClasses(this); + } + + /// Reads supported embedded GSM library parts and reports unreadable asset blocks. + /// The catalog reads archived data directly. The GSM revision may differ from the revision in a placed + /// element's library reference. The method does not load linked libraries or execute GSM scripts. + /// The object class table is unusable. + public PlaEmbeddedLibraryCatalog ReadEmbeddedLibraryCatalog() + { + ObjectDisposedException.ThrowIf(_disposed, this); + return EmbeddedLibraryReader.Read(this, ReadObjectClasses()); + } + + /// Reads recognized model elements and the basic parameters available in their saved records. + /// See the element reader documentation for supported types and parameters. + /// The class table is unusable, an element has conflicting types, + /// a recognized element or grid list is truncated, a recognized classification catalog or property record is invalid, + /// or a compressed pool cannot be decoded. + public IReadOnlyList ReadElements() => ElementReader.Read(this, ReadObjectClasses()); + + /// Reads the saved project stories in ascending story index order. + /// Returns an empty list if there is no supported story table. + /// The object class table or a recognized story table is invalid. + public IReadOnlyList ReadStories() => ElementReader.ReadStoryCatalog(this, ReadObjectClasses()); + + /// Reads the identifiable saved project layers in ascending layer index order. + /// The object class table is invalid or layer records conflict. + public IReadOnlyList ReadLayers() => ElementReader.ReadLayerCatalog(this, ReadObjectClasses()); + + /// Reads saved building material and composite attributes in ascending project-local index order. + /// The object class table is invalid or material attribute records conflict. + public PlaMaterialCatalog ReadMaterialCatalog() => ElementReader.ReadMaterialCatalog(this, ReadObjectClasses()); + + /// Reads the saved complex profile definitions in ascending project-local index order. + /// The class table is invalid or profile attribute records conflict. + public IReadOnlyList ReadProfileCatalog() => ElementReader.ReadProfileCatalog(this, ReadObjectClasses()); + + /// Reads saved classification systems in GUID order and their items in depth-first order. + /// Returns an empty list if the file has no supported classification catalog. + /// The class table, a recognized classification record or its tree is invalid. + public IReadOnlyList ReadClassificationSystems() => + ElementReader.ReadClassificationCatalog(this, ReadObjectClasses()).Systems; + + /// Reads saved user-defined property groups and definitions in GUID order. + /// Includes definitions that are unused by the recognized model elements. + /// The class table, a recognized property record or its group link is invalid. + public PlaPropertyCatalog ReadPropertyCatalog() => ElementReader.ReadPropertyCatalog(this, ReadObjectClasses()); + + /// Reads the saved layout book, its layouts and placed drawing entries in navigator order. + /// The layout book, or null if the file has no supported layout book. + /// A recognized layout record or navigator link is invalid. + public PlaLayoutBook? ReadLayoutBook() => ElementReader.ReadLayoutBook(this, ReadObjectClasses()); + /// Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. The first /// call scans the file; later calls return the cached list, so the pool objects stay identical. public IReadOnlyList FindCompressedPools() @@ -229,6 +348,9 @@ internal byte[] DecodePool(long offset) return PoolReader.Decode(_stream, Length, offset, _options.MaxDecodedPoolBytes); } + internal byte[] ReadPoolPrefix(long offset, int size) => + PoolReader.ReadPrefix(_stream, Length, offset, size, _options.MaxDecodedPoolBytes); + /// The window that decoding builds while the pools are read in order: /// the tail of the pool-stream reconstruction up to the pool with index (that /// pool excluded). Reading the pools in file order advances the window, so every pool decodes once; a read that diff --git a/tests/PlaIO.Tests/CliTests.cs b/tests/PlaIO.Tests/CliTests.cs index d21fadc..7e00a23 100644 --- a/tests/PlaIO.Tests/CliTests.cs +++ b/tests/PlaIO.Tests/CliTests.cs @@ -76,11 +76,122 @@ public void InputsThatCannotBeUsedExitWithTwo() string bimx = Write("b.bimx", Synthetic.Bimx(Synthetic.SimplePng(), [1, 2])); Assert.Equal(2, Run("blocks", bimx).Code); Assert.Equal(2, Run("directory", bimx).Code); + Assert.Equal(2, Run("stories", bimx).Code); + Assert.Equal(2, Run("layers", bimx).Code); + Assert.Equal(2, Run("materials", bimx).Code); + Assert.Equal(2, Run("profiles", bimx).Code); + Assert.Equal(2, Run("classifications", bimx).Code); + Assert.Equal(2, Run("properties", bimx).Code); + Assert.Equal(2, Run("layouts", bimx).Code); Assert.Equal(2, Run("info", Write("cut.pla", Synthetic.Header()[..20])).Code); Assert.Equal(2, Run("info", Write("bad.bimx", Synthetic.Bimx([1, 2, 3], []))).Code); Assert.Equal(2, Run("info", "a\0b").Code); } + [Fact] + public void ProfilesWritesProjectProfileAttributes() + { + Guid id = Guid.NewGuid(); + var (code, output, error) = Run("profiles", Write("profiles.pln", ElementReaderTests.ProfileCatalogFile(id))); + Assert.Equal(0, code); + Assert.Empty(error); + using var json = JsonDocument.Parse(output); + var profile = Assert.Single(json.RootElement.GetProperty("profiles").EnumerateArray()); + Assert.Equal(id, profile.GetProperty("guid").GetGuid()); + Assert.Equal(3, profile.GetProperty("index").GetInt32()); + Assert.Equal("Профиль", profile.GetProperty("name").GetString()); + Assert.True(profile.GetProperty("hasCoreSkin").GetBoolean()); + } + + [Fact] + public void ClassificationsWritesCatalogAndElementsReferenceItsItems() + { + var fixture = ElementReaderTests.ClassificationFixture(); + string file = Write("classifications.pln", fixture.File); + var (code, output, error) = Run("classifications", file); + Assert.Equal(0, code); + Assert.Empty(error); + using var catalog = JsonDocument.Parse(output); + var system = catalog.RootElement.GetProperty("classificationSystems")[0]; + Assert.Equal(fixture.First, system.GetProperty("guid").GetGuid()); + Assert.Equal("2024-02-29", system.GetProperty("date").GetString()); + Assert.Equal(fixture.Branch, system.GetProperty("items")[1].GetProperty("parentGuid").GetGuid()); + + (code, output, error) = Run("elements", file); + Assert.Equal(0, code); + Assert.Empty(error); + using var elements = JsonDocument.Parse(output); + var element = Assert.Single(elements.RootElement.GetProperty("elements").EnumerateArray(), + value => value.GetProperty("guid").GetGuid() == fixture.Classified); + var classification = element.GetProperty("classifications")[0]; + Assert.Equal(fixture.First, classification.GetProperty("systemGuid").GetGuid()); + Assert.Equal(fixture.Leaf, classification.GetProperty("itemGuid").GetGuid()); + } + + [Fact] + public void PropertiesWritesGroupsAndTypedDefinitionValues() + { + var fixture = ElementReaderTests.PropertyCatalogFixture(withOverride: true); + string file = Write("properties.pln", fixture.File); + var (code, output, error) = Run("properties", file); + Assert.Equal(0, code); + Assert.Empty(error); + using var json = JsonDocument.Parse(output); + var group = Assert.Single(json.RootElement.GetProperty("groups").EnumerateArray()); + var definition = Assert.Single(json.RootElement.GetProperty("definitions").EnumerateArray(), + value => value.GetProperty("guid").GetGuid() == fixture.Length); + Assert.Equal(fixture.Group, group.GetProperty("guid").GetGuid()); + Assert.Equal(fixture.Group, definition.GetProperty("groupGuid").GetGuid()); + Assert.Equal("length", definition.GetProperty("dataType").GetString()); + Assert.Equal(0.125, definition.GetProperty("defaultValue").GetProperty("value").GetDouble()); + + (code, output, error) = Run("elements", file); + Assert.Equal(0, code); + Assert.Empty(error); + using var elements = JsonDocument.Parse(output); + var element = Assert.Single(elements.RootElement.GetProperty("elements").EnumerateArray()); + var saved = Assert.Single(element.GetProperty("propertyOverrides").EnumerateArray(), + value => value.GetProperty("definitionGuid").GetGuid() == fixture.Length); + Assert.Equal(0.5, saved.GetProperty("value").GetProperty("value").GetDouble()); + } + + [Fact] + public void LayoutsWritesTheBookAndPlacedEntries() + { + var fixture = ElementReaderTests.LayoutBookFixture(); + var (code, output, error) = Run("layouts", Write("book.pln", fixture.File)); + Assert.Equal(0, code); + Assert.Empty(error); + using var json = JsonDocument.Parse(output); + var book = json.RootElement.GetProperty("layoutBook"); + Assert.Equal(fixture.Book, book.GetProperty("guid").GetGuid()); + var drawing = book.GetProperty("items")[2]; + Assert.Equal("DrawingItem", drawing.GetProperty("type").GetString()); + Assert.Equal(fixture.Items[1].Guid, drawing.GetProperty("parentGuid").GetGuid()); + Assert.Equal(fixture.Items[2].SourceGuid, drawing.GetProperty("sourceGuid").GetGuid()); + var layout = book.GetProperty("items")[1]; + Assert.Equal(fixture.Items[1].DatabaseGuid, layout.GetProperty("databaseGuid").GetGuid()); + Assert.Equal(fixture.Items[1].MasterLayoutGuid, layout.GetProperty("masterLayoutGuid").GetGuid()); + Assert.Equal(0.420, layout.GetProperty("paperSize").GetProperty("width").GetDouble()); + } + + [Fact] + public void LayoutsWritesIssuedAndOpenRevisionData() + { + var fixture = ElementReaderTests.LayoutBookFixture(revisions: "mixed"); + var (code, output, error) = Run("layouts", Write("revisions.pln", fixture.File)); + Assert.Equal(0, code); + Assert.Empty(error); + using var json = JsonDocument.Parse(output); + var revision = json.RootElement.GetProperty("layoutBook").GetProperty("items")[1].GetProperty("revision"); + Assert.True(revision.GetProperty("hasIssuedRevision").GetBoolean()); + Assert.True(revision.GetProperty("hasActualRevision").GetBoolean()); + Assert.Equal("A", revision.GetProperty("issuedRevisions")[1].GetProperty("id").GetString()); + Assert.Equal("Draft", revision.GetProperty("openTransmittal").GetProperty("id").GetString()); + Assert.Equal("01", revision.GetProperty("currentRevisionId").GetString()); + Assert.Equal(JsonValueKind.Null, revision.GetProperty("currentFinalRevisionId").ValueKind); + } + [Fact] public void InfoOnFdbPrintsHeaderFieldsAndBlockCounts() { @@ -153,6 +264,28 @@ public void DirectoryWithoutOutPrintsOnlyTheSummary() Assert.Equal(2, output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length); } + [Fact] + public void ElementsPrintsTheReadOnlyModelAsJson() + { + Guid id = Guid.NewGuid(); + string input = Write("model.pln", ElementReaderTests.WallFile(id)); + var (code, output, error) = Run("elements", input); + Assert.Equal(0, code); + Assert.Empty(error); + using var json = JsonDocument.Parse(output); + var element = Assert.Single(json.RootElement.GetProperty("elements").EnumerateArray()); + Assert.Equal(id, element.GetProperty("guid").GetGuid()); + Assert.Equal("Wall", element.GetProperty("type").GetString()); + Assert.Equal("Wall-1", element.GetProperty("elementId").GetString()); + Assert.Equal(0.25, element.GetProperty("wallThickness").GetDouble()); + Assert.Equal(5, element.GetProperty("wallReferenceLineChordLength").GetDouble()); + Assert.Equal(JsonValueKind.Null, element.GetProperty("topLinkedStoryIndex").ValueKind); + Assert.Equal(JsonValueKind.Null, element.GetProperty("bottomElevationToProjectZero").ValueKind); + Assert.Equal(JsonValueKind.Null, element.GetProperty("topElevationToProjectZero").ValueKind); + Assert.Equal(JsonValueKind.Null, element.GetProperty("bottomElevationToHomeStory").ValueKind); + Assert.Equal(JsonValueKind.Null, element.GetProperty("topElevationToHomeStory").ValueKind); + } + [Fact] public void OutputThatCannotBeReplacedExitsWithTwoAndLeavesNoTemporaryFile() { diff --git a/tests/PlaIO.Tests/ElementReaderTests.Classifications.cs b/tests/PlaIO.Tests/ElementReaderTests.Classifications.cs new file mode 100644 index 0000000..bfb7bab --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.Classifications.cs @@ -0,0 +1,129 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsClassificationTreesAndElementAssignments(bool olderFrame) + { + var fixture = ClassificationFixture(olderFrame: olderFrame); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var systems = document.ReadClassificationSystems(); + Assert.Collection(systems, first => + { + Assert.Equal((fixture.First, "System А", "Two\r\nlines", "", "3.1", new DateOnly(2024, 2, 29)), + (first.Guid, first.Name, first.Description, first.Source, first.Version, first.Date!.Value)); + Assert.Equal([new PlaClassificationItem(fixture.Branch, null, "B", "", ""), + new PlaClassificationItem(fixture.Leaf, fixture.Branch, "B.1", "Деталь", ""), + new PlaClassificationItem(fixture.Sibling, null, "A", "", "")], first.Items); + }, second => + { + Assert.Equal(fixture.Second, second.Guid); + Assert.Equal(fixture.Other, Assert.Single(second.Items).Guid); + }); + + var elements = document.ReadElements().ToDictionary(e => e.Guid); + Assert.Equal(2, elements.Count); + Assert.Equal([new PlaClassificationAssignment(fixture.First, fixture.Leaf), + new PlaClassificationAssignment(fixture.Second, fixture.Other)], elements[fixture.Classified].Classifications); + Assert.Empty(elements[fixture.Unclassified].Classifications!); + } + + [Theory] + [InlineData("missing child")] + [InlineData("wrong parent")] + [InlineData("truncated links")] + [InlineData("conflicting assignments")] + public void RejectsMalformedClassificationCatalog(string problem) + { + using var document = PlaDocument.Open(new MemoryStream(ClassificationFixture(problem).File)); + Assert.Throws(document.ReadElements); + if (problem != "conflicting assignments") + Assert.Throws(document.ReadClassificationSystems); + } + + internal static (byte[] File, Guid First, Guid Second, Guid Branch, Guid Leaf, Guid Sibling, Guid Other, + Guid Classified, Guid Unclassified) ClassificationFixture(string? problem = null, bool olderFrame = false) + { + Guid systemClass = new("420f4c27-70b8-43c2-9d9d-f74ef1ee9b47"); + Guid itemClass = new("9be1f9d1-13d9-45ff-813e-01c7846cd0c2"); + Guid meshClass = new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d"); + Guid rootLink = new("e88a0cef-00c8-45d1-ae13-80c6616ad0f8"); + Guid treeLink = new("8d79244e-35bb-412f-8148-2b4a8839159a"); + Guid assignment = new("9534032d-da8d-4c44-b42b-6363688cafc6"); + Guid first = new("00000001-0000-0000-0000-000000000000"), second = new("00000002-0000-0000-0000-000000000000"); + Guid firstRoot = Guid.NewGuid(), secondRoot = Guid.NewGuid(); + Guid branch = Guid.NewGuid(), leaf = Guid.NewGuid(), sibling = Guid.NewGuid(), other = Guid.NewGuid(); + Guid classified = Guid.NewGuid(), unclassified = Guid.NewGuid(), outsideModel = Guid.NewGuid(); + byte[] leafAssignments = Relation(2, assignment, classified, outsideModel); + if (problem == "truncated links") leafAssignments = leafAssignments[..^16]; + var blocks = new List + { + ClassTable((6, systemClass), (7, itemClass), (8, meshClass)), + ElementDirectory(false, new ObjectDirectoryRecord(8, 2, 1, classified), new ObjectDirectoryRecord(8, 3, 1, unclassified)), + System(second, secondRoot, "System B"), + Item(secondRoot, "internal-b", "", Relation(0x12, rootLink, second), Relation(0x11, treeLink, other)), + Item(other, "C", "", Relation(0x12, treeLink, secondRoot), Relation(0x12, assignment, classified)), + System(first, firstRoot, "System А"), + Item(firstRoot, "internal-a", "", Relation(0x12, rootLink, first), Relation(1, treeLink, branch, sibling)), + Item(branch, "B", "", Relation(0x12, treeLink, firstRoot), Relation(0x11, treeLink, leaf)), + Item(sibling, "A", "", Relation(0x12, treeLink, firstRoot), + problem == "conflicting assignments" ? Relation(0x12, assignment, classified) : []) + }; + if (problem != "missing child") + blocks.Add(Item(leaf, "B.1", "Деталь", Relation(0x12, treeLink, problem == "wrong parent" ? sibling : branch), + leafAssignments)); + return (Synthetic.Fdb(blocks.ToArray()), first, second, branch, leaf, sibling, other, classified, unclassified); + + byte[] System(Guid id, Guid root, string name) => + ClassificationBlock(6, id, systemClass, 1, olderFrame, + [Text(name), Text("3.1"), [0xE8, 7, 2, 0, 29, 0], Text("Two\r\nlines"), Text("")], + [Relation(0x11, rootLink, root)]); + + byte[] Item(Guid id, string code, string name, params byte[][] relations) => + ClassificationBlock(7, id, itemClass, 3, olderFrame, [Text(code), Text(name), Text("")], relations); + + static byte[] Text(string value) + { + var header = new byte[6]; + header[0] = 1; + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(2), value.Length); + return Synthetic.Concat(header, Encoding.Unicode.GetBytes(value)); + } + + static byte[] Relation(byte tag, Guid key, params Guid[] targets) + { + int headerSize = tag is 1 or 2 ? 21 : 17; + var relation = new byte[headerSize + 16 * targets.Length]; + relation[0] = tag; + key.TryWriteBytes(relation.AsSpan(1)); + if (headerSize == 21) + BinaryPrimitives.WriteInt32LittleEndian(relation.AsSpan(17), targets.Length); + for (int i = 0; i < targets.Length; i++) + targets[i].TryWriteBytes(relation.AsSpan(headerSize + 16 * i)); + return relation; + } + } + + private static byte[] ClassificationBlock(ushort kind, Guid id, Guid type, byte fieldKind, + bool olderFrame, byte[][] fields, byte[][] relations) + { + byte[] bodyFrame = [1, 0, olderFrame ? (byte)0x82 : (byte)0x83, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, fieldKind, 0]; + var body = Synthetic.Concat([bodyFrame, .. fields, new byte[] { olderFrame ? (byte)0 : (byte)1 }]); + var links = Synthetic.Concat([new byte[] { 1, 0 }, .. relations, new byte[] { 0 }]); + var prefix = new byte[39]; + type.TryWriteBytes(prefix); + BinaryPrimitives.WriteInt32LittleEndian(prefix.AsSpan(35), body.Length); + var length = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(length, links.Length); + var payload = Synthetic.Concat(prefix, body, length, links); + return Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(payload), ver: 1, + kind: kind, guid: id, unpacked: (uint)payload.Length, extra: 1); + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.DoorParameters.cs b/tests/PlaIO.Tests/ElementReaderTests.DoorParameters.cs new file mode 100644 index 0000000..c11fda1 --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.DoorParameters.cs @@ -0,0 +1,138 @@ +using System.Buffers.Binary; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + [InlineData(5)] + [InlineData(6)] + public void ReadsDoorWallHoleDimensionsAcrossPoolsOnlyWithVerifiedOwners(int variation) + { + Guid doorClass = new("d8f07689-9cfa-4fbe-aeb4-0a60b8e667ee"); + Guid libraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f"); + Guid tableClass = new("11db227d-dbe4-45af-88b6-6fddea993f71"); + Guid libraryRole = new("672f1c46-64f3-41f5-8a4a-ffdfd86bcbfd"); + Guid tableRole = new("76ebf0a4-c2ef-483f-a1a8-28d3adde99a0"); + Guid door = Guid.NewGuid(), descriptor = Guid.NewGuid(), table = Guid.NewGuid(); + Guid family = Guid.NewGuid(), revision = Guid.NewGuid(); + var doorBody = WithGeometryRelations(FramedElementId(doorClass, 286, "Door"), GeometryRelation(0x11, libraryRole, descriptor)); + byte[] descriptorData = new byte[89]; + libraryClass.TryWriteBytes(descriptorData); + new byte[] { 1, 0, 131, 0, 3, 0, 0, 0, 1, 0, 2, 0 }.CopyTo(descriptorData, 39); + family.TryWriteBytes(descriptorData.AsSpan(51)); + revision.TryWriteBytes(descriptorData.AsSpan(67)); + var descriptorBody = WithGeometryRelations(descriptorData, GeometryRelation(0x12, libraryRole, door), + GeometryRelation(0x11, tableRole, variation == 6 ? Guid.NewGuid() : table)); + + const int tableSize = 8 + 2 * 72; + byte[] tableData = new byte[57 + tableSize + 24]; + tableClass.TryWriteBytes(tableData); + new byte[] { 1, 0, 8, 0, 131, 0, 3, 0, 0, 0, 1, 0, 1, 0 }.CopyTo(tableData, 39); + BinaryPrimitives.WriteUInt32LittleEndian(tableData.AsSpan(35), (uint)tableData.Length - 39); + BinaryPrimitives.WriteUInt32LittleEndian(tableData.AsSpan(53), tableSize); + BinaryPrimitives.WriteUInt32LittleEndian(tableData.AsSpan(57), variation == 4 ? uint.MaxValue : 2); + WriteLengthParameter(tableData.AsSpan(65, 72), "ac_wallhole_width"u8, 1.125); + WriteLengthParameter(tableData.AsSpan(137, 72), variation == 5 ? "ac_wallhole_width"u8 : "ac_wallhole_height"u8, + variation == 3 ? double.NaN : 2.25); + var tableBody = WithGeometryRelations(tableData, variation == 0 ? GeometryRelation(0x12, tableRole, descriptor) : + GeometryRelationList(2, tableRole, variation == 2 ? Guid.NewGuid() : descriptor, Guid.NewGuid())); + + byte[] doorPool = new byte[2048], tablePool = new byte[512]; + Synthetic.Block(PlaBlockMode.Raw, doorBody, ver: 1, guid: door, extra: 1, kind: 1).CopyTo(doorPool, 0); + Synthetic.Block(PlaBlockMode.Raw, descriptorBody, ver: 1, guid: descriptor, extra: 1, kind: 2).CopyTo(doorPool, 1024); + Synthetic.Block(PlaBlockMode.Raw, tableBody, ver: 1, guid: table, extra: 1, kind: 3).CopyTo(tablePool, 0); + byte[] tableDirectory = new byte[40]; + BinaryPrimitives.WriteUInt64LittleEndian(tableDirectory, 32); + new Guid("34d77468-1d98-45b9-958d-1eea37423cb5").TryWriteBytes(tableDirectory.AsSpan(24)); + using var doc = Open(ClassTable((1, doorClass), (2, libraryClass), (3, tableClass)), + OwnedDirectory(false, Guid.Empty, 128, new(1, 0, 64, door), new(2, 64, 64, descriptor)), + Synthetic.Block(PlaBlockMode.Raw, + Synthetic.Concat(tableDirectory, Synthetic.Record(new(3, 0, 32, table))), ver: 1), + Pool(tablePool), Pool(doorPool)); + + var element = Assert.Single(doc.ReadElements()); + Assert.Equal(new PlaLibraryPartReference(family, revision), element.LibraryPartReference); + Assert.Equal(variation is 0 or 1 ? new PlaDoorWallHoleDimensions(1.125, 2.25) : (PlaDoorWallHoleDimensions?)null, + element.DoorWallHoleDimensions); + + } + + private static void WriteLengthParameter(Span row, ReadOnlySpan name, double value) + { + BinaryPrimitives.WriteUInt16LittleEndian(row[8..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(row[24..], value); + name.CopyTo(row[32..]); + BinaryPrimitives.WriteUInt32LittleEndian(row[68..], sizeof(double)); + } + + private static byte[] PlainDoorPassageTable(Guid tableClass, Guid role, Guid descriptor, bool positiveOversize, int revealType, + bool pocket, bool centeredPocket) + { + (string Name, ushort Type, int Value)[] settings = + [ + ("AC_WallType", 0, 1), + ("gs_leaf_optype_m", 0, pocket ? 25 : 1), + ("gs_wallhole_nominal", 13, 1), + ("gs_reveal_type_int", 0, revealType), + ("gs_closure_type_int", 0, 1), + ("gs_trimtype_out_int", 0, 1), + ("gs_trimtype_in_int", 0, 1), + ("iThresholdType", 0, pocket ? -1 : 2), + ("gs_sunShade_iType", 0, 1), + ("gs_sidelight_left", 13, 0), + ("gs_sidelight_right", 13, 0), + ("gs_sill_outside", 13, 0), + ("gs_board_inside", 13, 0), + ("gs_shutRoll_cutWallBehind", 13, 0), + ("gs_shutLam_cutWallBehind", 13, 0), + ("bMasonryArch", 13, 0), + ]; + (string Name, double Value)[] lengths = []; + if (pocket) + { + settings = [.. settings, ("gs_pocket_door_frame", 13, 1), ("gs_pocket_frame", 13, 0), + ("gs_leaf_center", 13, centeredPocket ? 1 : 0), ("bThreshold", 13, 0)]; + lengths = [("gs_leaf_offset", 0.01), ("gs_leaf_undercut", 0), ("gs_leaf_thk", 0.04), + ("ac_leaf_height", 2.05), ("ac_leaf_width", 0.6), ("gs_leaf_panel_width", 0.6), + ("gs_frame_thk", 0.06), ("gs_frame_width", 0.05), ("gs_frame_width_left", 0.04), + ("gs_frame_width_right", 0.04), ("gs_frame_width_upper", 0.04)]; + } + int count = settings.Length + lengths.Length + 6; + int size = 8 + 72 * count; + byte[] bytes = new byte[57 + size + 24]; + tableClass.TryWriteBytes(bytes); + new byte[] { 1, 0, 8, 0, 131, 0, 3, 0, 0, 0, 1, 0, 1, 0 }.CopyTo(bytes, 39); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(35), (uint)bytes.Length - 39); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(53), (uint)size); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(57), (uint)count); + WriteLengthParameter(bytes.AsSpan(65, 72), "ac_wallhole_width"u8, pocket ? 0.7 : 0.5); + WriteLengthParameter(bytes.AsSpan(137, 72), "ac_wallhole_height"u8, pocket ? 2.1 : 2); + WriteLengthParameter(bytes.AsSpan(209, 72), "ac_left_oversize"u8, positiveOversize ? 0.125 : 0); + WriteLengthParameter(bytes.AsSpan(281, 72), "ac_right_oversize"u8, 0); + WriteLengthParameter(bytes.AsSpan(353, 72), "ac_lower_oversize"u8, 0); + WriteLengthParameter(bytes.AsSpan(425, 72), "ac_upper_oversize"u8, 0); + for (int i = 0; i < settings.Length; i++) + { + var (name, type, value) = settings[i]; + var row = bytes.AsSpan(497 + i * 72, 72); + BinaryPrimitives.WriteUInt16LittleEndian(row[8..], type); + BinaryPrimitives.WriteInt32LittleEndian(row[24..], value); + System.Text.Encoding.ASCII.GetBytes(name, row[32..64]); + } + for (int i = 0; i < lengths.Length; i++) + { + var (name, value) = lengths[i]; + WriteLengthParameter(bytes.AsSpan(497 + (settings.Length + i) * 72, 72), + System.Text.Encoding.ASCII.GetBytes(name), value); + } + return WithGeometryRelations(bytes, GeometryRelation(0x12, role, descriptor)); + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.EmbeddedLibrary.cs b/tests/PlaIO.Tests/ElementReaderTests.EmbeddedLibrary.cs new file mode 100644 index 0000000..830a10c --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.EmbeddedLibrary.cs @@ -0,0 +1,103 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(PlaBlockMode.Raw, false)] + [InlineData(PlaBlockMode.ZeroMask, false)] + [InlineData(PlaBlockMode.Lz, false)] + [InlineData(PlaBlockMode.Raw, true)] + [InlineData(PlaBlockMode.ZeroMask, true)] + [InlineData(PlaBlockMode.Lz, true)] + public void ReadsValidatedEmbeddedLibraryAssets(PlaBlockMode mode, bool pooled) + { + Guid assetClass = new("6faaf82c-c131-4f8b-b1d9-9706144935dd"); + Guid assetId = Guid.NewGuid(), family = Guid.NewGuid(), revision = Guid.NewGuid(); + Guid unknownId = Guid.NewGuid(), invalidId = Guid.NewGuid(), shortId = Guid.NewGuid(), invalidTextId = Guid.NewGuid(); + const ushort assetKind = 19; + var gsm = new byte[148]; + "WW.\0"u8.CopyTo(gsm); + "MYSDCASGDAEH"u8.CopyTo(gsm.AsSpan(40)); + if (mode == PlaBlockMode.ZeroMask) + { + gsm[43] = (byte)'W'; + gsm.AsSpan(44, 4).Clear(); + } + BinaryPrimitives.WriteUInt32LittleEndian(gsm.AsSpan(36), 1); + BinaryPrimitives.WriteUInt32LittleEndian(gsm.AsSpan(52), 128); + BinaryPrimitives.WriteUInt32LittleEndian(gsm.AsSpan(56), 16); + Assert.True(family.TryWriteBytes(gsm.AsSpan(72))); + Assert.True(revision.TryWriteBytes(gsm.AsSpan(88))); + "TEST"u8.CopyTo(gsm.AsSpan(128)); + BinaryPrimitives.WriteUInt32LittleEndian(gsm.AsSpan(132), 144); + BinaryPrimitives.WriteUInt32LittleEndian(gsm.AsSpan(136), 4); + "DATA"u8.CopyTo(gsm.AsSpan(144)); + var badSection = (byte[])gsm.Clone(); + BinaryPrimitives.WriteUInt32LittleEndian(badSection.AsSpan(136), 5); + const string name = "Дверь.gsm"; + byte[][] assets = + [ + Asset(mode, assetId, Text(name), "model/vnd.gs-gdl", gsm), + Asset(PlaBlockMode.Raw, unknownId, Text("finish.jpg"), "image/jpeg", [1]), + Asset(PlaBlockMode.Raw, invalidId, Text("bad.gsm"), "model/vnd.gs-gdl", badSection), + Asset(PlaBlockMode.Raw, shortId, Text("short.gsm"), "model/vnd.gs-gdl", gsm[..100]), + Asset(PlaBlockMode.Raw, invalidTextId, [1, 0, 1, 0, 0, 0, 0, 0xD8], "model/vnd.gs-gdl", gsm), + ]; + byte[] classes = ClassTable((assetKind, assetClass)); + using var doc = pooled + ? Open(classes, Synthetic.QuickLzPool(assets.SelectMany(asset => new[] { asset[..1], asset[1..^3], asset[^3..] }) + .Select(part => ((uint)part.Length, Synthetic.QuickLzFrame(part, part.Length, 0x46))).ToArray())) + : Open([classes, .. assets]); + + var result = doc.ReadEmbeddedLibraryCatalog(); + var part = Assert.Single(result.Parts); + Assert.Equal(assetId, part.AssetGuid); + Assert.Equal(name, part.Name); + Assert.Equal(family, part.LibraryPartGuid); + Assert.Equal(revision, part.RevisionGuid); + Assert.Equal(gsm, part.Data.ToArray()); + if (pooled) + { + Assert.DoesNotContain(doc.Blocks, b => b.Kind == assetKind); + Assert.Equal(Assert.Single(doc.FindCompressedPools()).Offset, Assert.Single(result.UnreadableAssetOffsets)); + } + else + { + Assert.Equal(doc.Blocks.Where(b => b.Guid == invalidId || b.Guid == shortId || b.Guid == invalidTextId).Select(b => b.Offset), + result.UnreadableAssetOffsets); + } + + byte[] Asset(PlaBlockMode storage, Guid id, byte[] title, string mediaType, byte[] content) + { + byte[] archive = new byte[32]; + "MYSGCASG"u8.CopyTo(archive); + BinaryPrimitives.WriteUInt32LittleEndian(archive.AsSpan(28), (uint)content.Length); + byte[] fields = Synthetic.Concat([1, 0, 3, 0, 0], title, Text(mediaType), archive, content); + byte[] record = new byte[39]; + Assert.True(assetClass.TryWriteBytes(record)); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(35), (uint)fields.Length); + byte[] body = Synthetic.Concat(record, fields); + var packed = storage switch + { + PlaBlockMode.Lz => Synthetic.QuickLzFrame(body, body.Length, 0x46), + PlaBlockMode.ZeroMask => Synthetic.ZeroMask(body), + _ => body, + }; + return Synthetic.Block(storage, packed, ver: 1, unpacked: (uint)body.Length, guid: id, kind: assetKind); + } + + static byte[] Text(string value) + { + var field = new byte[6 + value.Length * 2]; + BinaryPrimitives.WriteUInt16LittleEndian(field, 1); + BinaryPrimitives.WriteUInt32LittleEndian(field.AsSpan(2), (uint)value.Length); + Encoding.Unicode.GetBytes(value, field.AsSpan(6)); + return field; + } + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.Layouts.cs b/tests/PlaIO.Tests/ElementReaderTests.Layouts.cs new file mode 100644 index 0000000..6274a46 --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.Layouts.cs @@ -0,0 +1,399 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsLayoutBookInSavedOrder(bool prefixedDirectory) + { + var fixture = LayoutBookFixture(prefixedDirectory); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var book = Assert.IsType(document.ReadLayoutBook()); + Assert.Equal(fixture.Book, book.Guid); + Assert.Equal(fixture.Items, book.Items); + } + + [Theory] + [InlineData("wrong parent")] + [InlineData("wrong metadata owner")] + [InlineData("duplicate child")] + [InlineData("wrong database owner")] + [InlineData("wrong master assignment")] + public void RejectsInconsistentLayoutBookLinks(string problem) + { + using var document = PlaDocument.Open(new MemoryStream(LayoutBookFixture(false, problem).File)); + Assert.Throws(document.ReadLayoutBook); + } + + [Fact] + public void ReadsLayoutHierarchyWhenLayoutDatabasesAreUnavailable() + { + var fixture = LayoutBookFixture(includeDatabases: false); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var book = Assert.IsType(document.ReadLayoutBook()); + Assert.Equal(fixture.Items, book.Items); + var layout = Assert.Single(book.Items, item => item.Type == "LayoutItem"); + Assert.Null(layout.MasterLayoutGuid); + Assert.Null(layout.PaperSize); + } + + [Theory] + [InlineData(false, null)] + [InlineData(true, null)] + [InlineData(true, "wrong last entry prefix")] + [InlineData(false, "ambiguous drawing view")] + public void ResolvesInternalDrawingFromTheSavedViewLink(bool shortEntry, string? problem) + { + var fixture = LayoutBookFixture(shortEntry, problem, internalDrawing: true, shortMemoEntry: shortEntry); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var book = Assert.IsType(document.ReadLayoutBook()); + Assert.Equal(fixture.Items, book.Items); + var drawing = Assert.Single(book.Items, item => item.Type == "DrawingItem"); + Assert.Equal(problem is null, drawing.SourceGuid.HasValue); + } + + [Theory] + [InlineData("empty", "", false, false, 0)] + [InlineData("first", "Z", true, false, 1)] + [InlineData("history", "A", true, false, 2)] + [InlineData("open", "01", false, true, 0)] + [InlineData("mixed", "01", true, true, 2)] + public void ReadsSavedLayoutRevisions(string scenario, string? current, bool issued, bool open, int count) + { + var fixture = LayoutBookFixture(revisions: scenario); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var book = Assert.IsType(document.ReadLayoutBook()); + var revision = Assert.IsType(Assert.Single(book.Items, item => item.Type == "LayoutItem").Revision); + Assert.Equal(current, revision.CurrentRevisionId); + Assert.Equal(open ? null : current, revision.CurrentFinalRevisionId); + Assert.Equal(issued, revision.HasIssuedRevision); + Assert.Equal(open, revision.HasActualRevision); + Assert.Equal(new[] { "Z", "A" }.Take(count), revision.IssuedRevisions.Select(entry => entry.Id)); + foreach (var entry in revision.IssuedRevisions) + { + Assert.Equal("Issue for " + entry.Id, entry.Transmittal.Name); + Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1_700_000_000), entry.Transmittal.IssuedAtUtc); + Assert.Equal("Author", entry.Transmittal.IssuedBy); + } + Assert.Equal(open ? "Draft" : null, revision.OpenTransmittal?.Id); + Assert.Null(revision.OpenTransmittal?.IssuedAtUtc); + Assert.Null(Assert.Single(book.Items, item => item.Type == "DrawingItem").Revision); + } + + [Theory] + [InlineData("01", "01", null, "02")] + [InlineData("00", "01|03|00", null, "04")] + [InlineData("R099", "R099", null, "R100")] + [InlineData("T-Y", "T-Y", null, "T-Z")] + [InlineData("R-Z", "R-Z", null, "R-ZA")] + [InlineData("Manual", "01|03", "03", "04")] + [InlineData("rev", "REV", null, "rev")] + [InlineData("ending!", "ending!", null, null)] + public void ResolvesOpenLayoutRevisionIdFromSavedNumbering(string numberingBase, string issuedIds, + string? earlierOverride, string? expected) + { + var fixture = LayoutBookFixture(revisions: "mixed", revisionNumbers: issuedIds.Split('|'), + revisionBase: numberingBase, earlierOverride: earlierOverride); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var book = Assert.IsType(document.ReadLayoutBook()); + var revision = Assert.IsType(Assert.Single(book.Items, item => item.Type == "LayoutItem").Revision); + Assert.True(revision.HasActualRevision); + Assert.True(revision.HasIssuedRevision); + Assert.Equal(expected, revision.CurrentRevisionId); + Assert.Null(revision.CurrentFinalRevisionId); + } + + [Fact] + public void UsesTheOpenTransmittalIdWhenItOverridesRevisionNumbering() + { + using var document = PlaDocument.Open(new MemoryStream(LayoutBookFixture(revisions: "override").File)); + var book = Assert.IsType(document.ReadLayoutBook()); + var revision = Assert.IsType(Assert.Single(book.Items, item => item.Type == "LayoutItem").Revision); + Assert.Equal("Draft", revision.CurrentRevisionId); + Assert.Null(revision.CurrentFinalRevisionId); + Assert.True(revision.OpenTransmittal?.OverridesRevisionIds); + } + + [Theory] + [InlineData("wrong revision owner")] + [InlineData("wrong transmittal member")] + [InlineData("truncated transmittal")] + public void RejectsInconsistentLayoutRevisionLinks(string problem) + { + using var document = PlaDocument.Open(new MemoryStream(LayoutBookFixture(problem: problem, revisions: "history").File)); + Assert.Throws(document.ReadLayoutBook); + } + + [Fact] + public void RejectsARevisionNumberingOverrideWithTheWrongOwner() + { + var fixture = LayoutBookFixture(problem: "wrong override owner", revisions: "mixed", earlierOverride: "03"); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + Assert.Throws(document.ReadLayoutBook); + } + + internal static (byte[] File, Guid Book, PlaLayoutBookItem[] Items) LayoutBookFixture(bool prefixedDirectory = false, + string? problem = null, bool includeDatabases = true, bool internalDrawing = false, bool shortMemoEntry = false, + string? revisions = null, string[]? revisionNumbers = null, string revisionBase = "01", string? earlierOverride = null) + { + Guid directoryType = new("06957baa-872a-40ea-b18b-2d4d1bcef8f0"); + Guid tree = new("33788fbb-8e6c-4a8d-a816-705f8d1ce5c6"); + Guid setting = new("22a736de-07dc-49d4-9ab1-df90d9118b23"); + Guid source = new("fe91e636-9138-4f5d-9d85-b5d11ed2387b"); + Guid metadata = new("6cbbd184-9a9c-4907-8363-ee7dd8141394"); + Guid layoutSource = new("90515593-8e6f-4ce1-9c2c-5746fc32716a"); + Guid masterSource = new("e03210e5-e70a-45da-8184-64835d8aeb6a"); + Guid layoutDatabaseLink = new("b1ddeca8-d51c-41c2-9a1a-77a1bcb3a5bb"); + Guid masterDatabaseLink = new("4b952067-803c-4aee-bc0d-8d1bbd107c6f"); + Guid assignment = new("980d1d7e-00c4-4f38-a77b-92108e7b660b"); + Guid drawingDatabaseLink = new("daade85d-fe69-4343-8254-4655416e28f6"); + Guid databaseDrawingLink = new("ac4d07f4-7e7c-4337-8bec-c82b034f4216"); + Guid drawingMemoLink = new("004ca348-04da-4f8b-bf94-22d0e313040b"); + Guid drawingViewLink = new("77201cab-66f6-4947-831d-c851ba54217d"); + Guid navigatorViewLink = new("bd38ee00-e866-43d5-a407-2437516d65d0"); + Guid revisionStateLink = new("6c8ed16c-a969-4a25-9f40-1ab657dc6b50"); + Guid revisionOverrideLink = new("a0e2f86f-4496-4a59-bbbe-ef3a6f1267a9"); + Guid issuedRevisionLink = new("9d374292-829a-4553-a3e0-6631d9a0110c"); + Guid issuedTransmittalLink = new("3b14d41d-2596-4cb7-8767-21309d216a9c"); + Guid openTransmittalLink = new("2421d43e-0a52-4d18-acfb-54e6262d9dbc"); + Guid[] classes = + [ + new("2bbbecb3-0ecd-4228-897b-cc6ffb35d37f"), new("983b7466-b012-43db-a637-bc6f93076c34"), + new("cf1797c1-69ec-4648-b5c5-57f898ab530b"), new("973bdcc9-e2f6-464f-85fb-833be20f5de5"), + new("6253793e-0a1f-4691-811b-4900cba006d1"), new("9d76eef2-a7cf-43b2-b09b-6d83d9607baa"), + new("10440840-10b2-4cab-99d7-54f8af93da44"), new("af0e45a5-fb37-4d8e-9132-d739c85efb91"), + new("2092ceaa-500d-4520-b62a-63403a643735"), new("31f5f16f-4b9e-41a8-9a32-f006ed168560"), + new("39b16f73-c419-4640-8ceb-682d7a0e8ff9"), new("93de1151-dc0a-4fe6-b394-54d7430988b5"), + new("8c3b244d-a5a4-45d6-b917-ce005c1c6161"), new("f080c777-1d2e-40df-91b4-c6169b14e516"), + new("32acaf3c-26b8-4593-926c-f81a205550ba"), new("041e23dd-9fca-4a53-9633-8865f82a3a40"), + new("2dbe8c52-93b3-46b5-a0a9-2492c45c2ab3"), new("ba3407e3-8afd-4eb7-9f53-f197ff35c20e"), + new("89967df1-d45d-4078-9278-9b637f992e7b"), new("169571f5-0665-4fec-8070-5e14962eaf1a"), + new("2c2d6560-da21-4610-b3b8-fe05f4b5c431"), new("ad6bafb9-a10c-4258-aad3-97f97ac5d1ae"), + new("8535adec-7d22-4334-8dfa-d3318ff35d23"), + ]; + Guid root = Guid.NewGuid(), book = Guid.NewGuid(), subset = Guid.NewGuid(), sheet = Guid.NewGuid(); + Guid masterFolder = Guid.NewGuid(), master = Guid.NewGuid(), drawing = Guid.NewGuid(); + Guid sheetData = Guid.NewGuid(), masterData = Guid.NewGuid(), drawingData = Guid.NewGuid(); + Guid sheetText = Guid.NewGuid(), masterText = Guid.NewGuid(), drawingText = Guid.NewGuid(), paper = Guid.NewGuid(); + Guid sheetDatabase = Guid.NewGuid(), masterDatabase = Guid.NewGuid(); + Guid drawingElement = Guid.NewGuid(), memo = Guid.NewGuid(), view = Guid.NewGuid(), viewKey = Guid.NewGuid(); + Guid sheetSettings = Guid.NewGuid(), state = Guid.NewGuid(), openIssue = Guid.NewGuid(); + + var extents = new List<(ushort Kind, Guid Id, byte[] Body)>(); + var revisionBlocks = new List(); + Add(1, root, [1], Link(0x11, tree, book)); + Add(2, book, [1], Link(0x12, tree, root), + problem == "duplicate child" ? Link(1, tree, subset, subset, masterFolder) : Link(1, tree, subset, masterFolder)); + var subsetPrefix = Frame(17, 10); + new byte[] { 1, 0, 3, 0, 8, 1 }.CopyTo(subsetPrefix, 0); + Add(3, subset, Synthetic.Concat(subsetPrefix, Text("04"), [1], Text("Детали")), + Link(0x12, tree, book), Link(0x11, tree, sheet)); + var sheetPrefix = Frame(25, 18); + sheetPrefix[0] = 1; + sheetPrefix[1] = 1; + Add(4, sheet, Synthetic.Concat(sheetPrefix, Text("04.1")), + Link(0x12, tree, problem == "wrong parent" ? book : subset), Link(0x11, tree, drawing), + Link(0x12, source, sheetData), Link(0x12, layoutSource, sheetData), + revisions is null ? [] : Link(0x11, setting, sheetSettings)); + Add(5, masterFolder, [1], Link(0x12, tree, book), Link(0x11, tree, master)); + Add(6, master, [1], Link(0x12, tree, masterFolder), Link(0x12, source, masterData), + Link(0x12, masterSource, masterData), Link(0x11, setting, paper)); + Add(7, drawing, [1], Link(0x12, tree, sheet), Link(0x12, source, drawingData)); + Add(8, sheetData, [1], Link(0x11, source, sheet), Link(0x12, metadata, sheetText)); + Add(9, masterData, [1], Link(0x11, source, master), Link(0x12, metadata, masterText)); + Add(10, drawingData, [1], Link(0x11, source, drawing), Link(0x12, metadata, drawingText)); + Add(11, sheetText, Synthetic.Concat(Frame(17, 10), Text("Stored"), Text("Разрез")), + Link(0x11, metadata, problem == "wrong metadata owner" ? masterData : sheetData), + Link(0x12, layoutDatabaseLink, sheetDatabase)); + Add(12, masterText, Synthetic.Concat(Frame(17, 10), Text(""), Text("A3")), Link(0x11, metadata, masterData), + Link(0x12, masterDatabaseLink, masterDatabase)); + var sourceType = new byte[] { 0, 0, 0, 0, internalDrawing ? (byte)0x14 : (byte)0x32, 0x80, 0, 0 }; + var drawingFrame = Frame(60, 14); + new byte[] { 1, 6, 0 }.CopyTo(drawingFrame, 20); + drawingElement.TryWriteBytes(drawingFrame.AsSpan(23)); + var drawingPath = internalDrawing ? @"\Views\Drawing" : ""; + Add(13, drawingText, Synthetic.Concat(drawingFrame, Text("Чертёж"), Text("1"), new byte[40], Text(drawingPath), sourceType), + Link(0x11, metadata, drawingData), Link(0x12, drawingDatabaseLink, sheetDatabase)); + var paperFrame = Frame(71, 12); + paperFrame[54] = 2; + BinaryPrimitives.WriteDoubleLittleEndian(paperFrame.AsSpan(55), 0.420); + BinaryPrimitives.WriteDoubleLittleEndian(paperFrame.AsSpan(63), 0.297); + Add(14, paper, paperFrame, Link(0x12, setting, master)); + if (revisions is not null) + { + bool isOpen = revisions is "open" or "mixed" or "override"; + string[] numbers = revisionNumbers ?? (revisions is "history" or "mixed" ? ["Z", "A"] : revisions == "first" ? ["Z"] : []); + var issued = new List(numbers.Length); + foreach (string number in numbers) + { + Guid revision = Guid.NewGuid(), issue = Guid.NewGuid(); + issued.Add(revision); + revisionBlocks.Add(Record(21, revision, Synthetic.Concat([2, 0, 1, 0, 0x83, 0, 3, 0, 0, 0], Text(number)), + Link(0x12, issuedRevisionLink, problem == "wrong revision owner" ? paper : sheetSettings), + Link(0x12, issuedTransmittalLink, issue))); + AddTransmittal(issue, number, problem == "wrong transmittal member" ? sheet : revision, + closed: true, overridesRevisionIds: number == earlierOverride); + } + byte[] history = issued.Count == 0 ? [] : Link(issued.Count == 1 ? (byte)0x11 : (byte)1, issuedRevisionLink, issued.ToArray()); + Add(14, sheetSettings, [1], Link(0x12, setting, sheet), Link(0x11, revisionStateLink, state), history); + byte[] overrideLink = []; + if (earlierOverride is not null) + { + Guid saved = Guid.NewGuid(); + Add(23, saved, Synthetic.Concat([1, 0, 0x83, 0, 3, 0, 0, 0], Text(earlierOverride)), + Link(0x12, revisionOverrideLink, problem == "wrong override owner" ? paper : state)); + overrideLink = Link(0x11, revisionOverrideLink, saved); + } + Add(20, state, Synthetic.Concat([1, 0, 1, 0, 0x83, 0, 3, 0, 0, 0], Text(revisionBase), Text("")), + Link(0x12, revisionStateLink, sheetSettings), isOpen ? Link(0x12, openTransmittalLink, openIssue) : [], overrideLink); + if (isOpen) AddTransmittal(openIssue, "Draft", state, closed: false, overridesRevisionIds: revisions == "override"); + } + if (internalDrawing) + { + Add(19, view, [1], Link(0x12, navigatorViewLink, viewKey)); + if (problem == "ambiguous drawing view") + Add(19, Guid.NewGuid(), [1], Link(0x12, navigatorViewLink, viewKey)); + } + + var data = new byte[512 * extents.Count]; + int headerOffset = prefixedDirectory ? 2 : 0; + byte[] directory = new byte[headerOffset + 40 + 30 * extents.Count]; + BinaryPrimitives.WriteInt64LittleEndian(directory.AsSpan(headerOffset), data.Length / 16); + Guid.NewGuid().TryWriteBytes(directory.AsSpan(headerOffset + 8)); + directoryType.TryWriteBytes(directory.AsSpan(headerOffset + 24)); + for (int i = 0; i < extents.Count; i++) + { + var (kind, id, bytes) = extents[i]; + bytes.CopyTo(data, 512 * i); + Synthetic.Record(new ObjectDirectoryRecord(kind, (ulong)i * 32, 32, id)) + .CopyTo(directory, headerOffset + 40 + 30 * i); + } + var blocks = new List + { + ClassTable(classes.Select((c, i) => ((ushort)(i + 1), c)).ToArray()), + Synthetic.Block(PlaBlockMode.Raw, directory, ver: 1, kind: 0xFDEA), + Pool(data), + }; + blocks.AddRange(revisionBlocks); + if (includeDatabases) + { + Guid linkedMetadata = problem == "wrong database owner" ? masterText : sheetText; + if (internalDrawing) + { + var table = new byte[headerOffset + 40 + 90]; + BinaryPrimitives.WriteInt64LittleEndian(table.AsSpan(headerOffset), 96); + sheetDatabase.TryWriteBytes(table.AsSpan(headerOffset + 8)); + new Guid("1f9b53da-bb9f-4f97-b5d9-532843923eac").TryWriteBytes(table.AsSpan(headerOffset + 24)); + Synthetic.Record(new ObjectDirectoryRecord(15, 0, 32, sheetDatabase)).CopyTo(table, headerOffset + 40); + Synthetic.Record(new ObjectDirectoryRecord(17, 32, 32, drawingElement)).CopyTo(table, headerOffset + 70); + Synthetic.Record(new ObjectDirectoryRecord(18, 64, 32, problem == "wrong last entry prefix" ? Guid.NewGuid() : memo)) + .CopyTo(table, headerOffset + 100); + var pool = new byte[3 * 512]; + Record(15, sheetDatabase, [1], Link(0x12, assignment, masterDatabase), Link(0x11, layoutDatabaseLink, linkedMetadata), + Link(0x11, drawingDatabaseLink, drawingText), Link(0x11, databaseDrawingLink, drawingElement)).CopyTo(pool, 0); + Record(17, drawingElement, [1], Link(0x12, databaseDrawingLink, sheetDatabase), + Link(0x11, drawingMemoLink, memo)).CopyTo(pool, 512); + Record(18, memo, [1], Link(0x12, drawingMemoLink, drawingElement), Link(0x12, drawingViewLink, viewKey)).CopyTo(pool, 1024); + if (shortMemoEntry) table = table[..^2]; + blocks.Add(Synthetic.Block(PlaBlockMode.Raw, table, ver: 1, kind: 0xFDEA)); + blocks.Add(Pool(pool)); + } + else + AddDatabase(15, sheetDatabase, 32, Link(0x12, assignment, masterDatabase), + Link(0x11, layoutDatabaseLink, linkedMetadata)); + AddDatabase(16, masterDatabase, 40, Link(0x11, masterDatabaseLink, masterText), + Link(1, assignment, problem == "wrong master assignment" ? Guid.NewGuid() : sheetDatabase)); + } + var file = Synthetic.Fdb(blocks.ToArray()); + return (file, book, + [ + new PlaLayoutBookItem(subset, book, "SubsetItem", "Детали", "04", null, null, null), + new PlaLayoutBookItem(sheet, subset, "LayoutItem", "Разрез", "04.1", sheetData, null, includeDatabases ? new(0.420, 0.297) : null) + { + DatabaseGuid = includeDatabases ? sheetDatabase : null, + MasterLayoutGuid = includeDatabases ? master : null + }, + new PlaLayoutBookItem(drawing, sheet, "DrawingItem", "Чертёж", "1", + internalDrawing ? (problem is null ? view : null) : drawingData, drawingPath, null), + new PlaLayoutBookItem(masterFolder, book, "MasterFolderItem", null, null, null, null, null), + new PlaLayoutBookItem(master, masterFolder, "MasterLayoutItem", "A3", "A3", masterData, null, new(0.420, 0.297)) + { + DatabaseGuid = includeDatabases ? masterDatabase : null + }, + ]); + + void Add(ushort kind, Guid id, byte[] fields, params byte[][] links) => + extents.Add((kind, id, Record(kind, id, fields, links))); + + void AddTransmittal(Guid id, string number, Guid member, bool closed, bool overridesRevisionIds) + { + if (problem == "truncated transmittal") + { + var truncated = new byte[35]; + classes[21].TryWriteBytes(truncated); + revisionBlocks.Add(Synthetic.Block(PlaBlockMode.Raw, truncated, ver: 1, kind: 22, guid: id, extra: 1)); + return; + } + var time = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(time, 1_700_000_000); + var tail = new byte[13]; + tail[8] = overridesRevisionIds ? (byte)1 : (byte)0; + tail[^1] = closed ? (byte)1 : (byte)0; + var fields = Synthetic.Concat([0x83, 0, 3, 0, 0, 0], Text(number), Text("Issue for " + number), + time, Text(closed ? "Author" : ""), tail); + var header = new byte[6] { 1, 2, 0, 0, 0, 0 }; + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(2), fields.Length); + revisionBlocks.Add(Record(22, id, Synthetic.Concat(header, fields), + Link(0x11, closed ? issuedTransmittalLink : openTransmittalLink, member))); + } + + void AddDatabase(ushort kind, Guid id, uint units, params byte[][] links) + { + blocks.Add(OwnedDirectory(prefixedDirectory, id, units, new ObjectDirectoryRecord(kind, 0, units, id))); + var bytes = new byte[units * 16]; + Record(kind, id, [1], links).CopyTo(bytes, 0); + blocks.Add(Pool(bytes)); + } + + byte[] Record(ushort kind, Guid id, byte[] fields, params byte[][] links) + { + var prefix = new byte[39]; + classes[kind - 1].TryWriteBytes(prefix); + BinaryPrimitives.WriteUInt32LittleEndian(prefix.AsSpan(35), (uint)fields.Length); + var relations = Synthetic.Concat([new byte[] { 1, 0 }, .. links, new byte[] { 0 }]); + var size = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(size, (uint)relations.Length); + byte[] body = Synthetic.Concat(prefix, fields, size, relations); + return Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, kind: kind, guid: id, extra: 1); + } + + static byte[] Frame(int length, int version) + { + var bytes = new byte[length]; + new byte[] { 0x83, 0, 3, 0, 0, 0 }.CopyTo(bytes, version); + return bytes; + } + + static byte[] Text(string text) + { + byte[] frame = [1, 0, 0, 0, 0, 0]; + BinaryPrimitives.WriteInt32LittleEndian(frame.AsSpan(2), text.Length); + return Synthetic.Concat(frame, Encoding.Unicode.GetBytes(text)); + } + + static byte[] Link(byte tag, Guid key, params Guid[] ids) + { + var prefix = new byte[tag == 1 ? 21 : 17]; + prefix[0] = tag; + key.TryWriteBytes(prefix.AsSpan(1)); + if (tag == 1) BinaryPrimitives.WriteInt32LittleEndian(prefix.AsSpan(17), ids.Length); + return Synthetic.Concat([prefix, .. ids.Select(id => id.ToByteArray())]); + } + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.Properties.cs b/tests/PlaIO.Tests/ElementReaderTests.Properties.cs new file mode 100644 index 0000000..0a40da5 --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.Properties.cs @@ -0,0 +1,215 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsUserPropertyCatalogWithAvailabilityChoicesAndDefaults(bool framed) + { + var fixture = PropertyCatalogFixture(framed: framed); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var catalog = document.ReadPropertyCatalog(); + Assert.Equal(new PlaPropertyGroup(fixture.Group, "Параметры"), Assert.Single(catalog.Groups)); + var byType = catalog.Definitions.ToDictionary(p => p.DataType!); + Assert.Equal(5, byType.Count); + Assert.All(byType.Values, definition => Assert.Equal(fixture.Group, definition.GroupGuid)); + var length = byType["length"]; + Assert.Equal(fixture.Length, length.Guid); + Assert.Equal("Размер", length.Name); + Assert.Equal("Две\r\nстроки", length.Description); + Assert.Equal([fixture.FirstClass, fixture.SecondClass], length.AvailableClassificationItemGuids); + Assert.Null(length.Choices); + Assert.Equal(new PlaPropertyValue("normal", 0.125), length.DefaultValue); + Assert.Equal([fixture.SecondClass], byType["integer"].AvailableClassificationItemGuids); + Assert.Equal(new PlaPropertyValue("userUndefined", null), byType["integer"].DefaultValue); + Assert.Empty(byType["string"].AvailableClassificationItemGuids); + Assert.Equal(new PlaPropertyValue("expression", null), byType["string"].DefaultValue); + var single = byType["singleEnum"]; + Assert.Equal([new PlaPropertyChoice(fixture.Choice, "Étage")], single.Choices); + Assert.Equal(new PlaPropertyValue("normal", fixture.Choice), single.DefaultValue); + Assert.Equal(new PlaPropertyValue("userUndefined", null), byType["multiEnum"].DefaultValue); + } + + [Theory] + [InlineData("wrong group")] + [InlineData("short choice")] + [InlineData("missing selected choice")] + [InlineData("truncated availability")] + [InlineData("truncated compressed chain")] + public void RejectsMalformedUserPropertyCatalog(string error) + { + using var document = PlaDocument.Open(new MemoryStream(PropertyCatalogFixture(error).File)); + Assert.Throws(document.ReadPropertyCatalog); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ReadsOnlyOverridesLinkedByTheirDefinition(bool reciprocal) + { + var fixture = PropertyCatalogFixture(reciprocal ? null : "unlinked override", withOverride: true); + using var document = PlaDocument.Open(new MemoryStream(fixture.File)); + var element = Assert.Single(document.ReadElements()); + Assert.Equal(fixture.Element, element.Guid); + if (!reciprocal) + { + Assert.Null(element.PropertyOverrides); + return; + } + var overrides = element.PropertyOverrides!.ToDictionary(entry => entry.DefinitionGuid); + Assert.Equal(2, overrides.Count); + Assert.Equal(new PlaPropertyValue("normal", 0.5), overrides[fixture.Length].Value); + Assert.Equal(new PlaPropertyValue("normal", fixture.Choice), overrides[fixture.Single].Value); + } + + internal static (byte[] File, Guid Group, Guid Length, Guid FirstClass, Guid SecondClass, Guid Choice, + Guid Single, Guid Element) PropertyCatalogFixture(string? error = null, bool framed = false, bool withOverride = false, + bool classified = false) + { + Guid groupType = new("e9cdf1dc-9117-46b6-bd32-5adba41a52c2"); + Guid propertyType = new("1f11a777-d5f5-4336-9b5a-963800153712"); + Guid groupLink = new("6f061922-6cfd-40c7-bb63-bcb4ed6c577a"); + Guid availability = new("b0b13d7f-53e9-444e-81aa-a11e9b3227fd"); + Guid overrideType = new("8dd49051-b081-4f20-a4a7-f6375145640d"); + Guid overrideLink = new("6d8a4425-a61e-4dd0-8978-9f90fac91e16"); + Guid elementLink = new("7306b00e-ff8d-4051-a8b3-f76cfc597704"); + Guid meshType = new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d"); + Guid scalarType = new("512896ad-f784-49fb-b45e-b741e45ccc7a"); + Guid enumType = new("87fecb96-0931-4ca1-a911-ac6ba507502a"); + Guid realValue = new("e0bf337e-40c2-43c4-86e5-fb8f2186d7f1"); + Guid intValue = new("bea7c323-acfb-4de4-83fa-22f8439fb713"); + Guid textValue = new("b0485a4f-f7a8-4798-a06a-8efa6ec97e59"); + Guid singleValue = new("7f8ba35b-ed11-4752-aff1-d4bcf0a0317d"); + Guid multipleValue = new("deb5c8a0-7fd8-4428-a1d4-1ef876cbf0be"); + + Guid group = Guid.NewGuid(), length = Guid.NewGuid(), integer = Guid.NewGuid(), text = Guid.NewGuid(); + Guid single = Guid.NewGuid(), multiple = Guid.NewGuid(), choice = Guid.NewGuid(), secondChoice = Guid.NewGuid(); + Guid firstClass = Guid.NewGuid(), secondClass = Guid.NewGuid(); + Guid systemType = new("420f4c27-70b8-43c2-9d9d-f74ef1ee9b47"); + Guid itemType = new("9be1f9d1-13d9-45ff-813e-01c7846cd0c2"); + Guid element = Guid.NewGuid(), lengthOverride = Guid.NewGuid(), choiceOverride = Guid.NewGuid(); + var lengthFrame = Value(realValue, 0, BitConverter.GetBytes(0.125)); + var intFrame = Value(intValue, 3, []); + var formula = Synthetic.Concat([2, 0, 2, 0, 2, 0, 0, 0, 1, 0, 1, 1, 0], Guid.NewGuid().ToByteArray(), + new byte[64]); + var singleFrame = Value(singleValue, 0, (error == "missing selected choice" ? Guid.NewGuid() : choice).ToByteArray()); + var multiFrame = Value(multipleValue, 3, []); + var list = Relation(1, availability, firstClass, secondClass); + if (error == "truncated availability") list = list[..^16]; + + bool linkOverrides = withOverride && error != "unlinked override"; + var blocks = new List + { + ClassTable((5, groupType), (6, propertyType), (7, overrideType), (8, meshType), (9, systemType), (10, itemType)), + Record(group, groupType, 5, Synthetic.Concat(Text("Параметры"), Text(""), [0]), + Relation(1, groupLink, length, integer, text, single, multiple)), + Definition(length, "Размер", "Две\r\nстроки", Scalar(2, 1, lengthFrame), list, + linkOverrides ? Relation(0x11, overrideLink, lengthOverride) : []), + Definition(integer, "Count", "", Scalar(1, 0, intFrame), Relation(0x11, availability, secondClass)), + Definition(text, "Formula", "", Scalar(3, 0, formula)), + Definition(single, "Pick one", "", Enumeration(choice, false, singleFrame), + classified ? Relation(0x11, availability, secondClass) : [], + linkOverrides ? Relation(0x11, overrideLink, choiceOverride) : []), + Definition(multiple, "Pick several", "", Enumeration(secondChoice, true, multiFrame)) + }; + if (withOverride) + { + var pool = new byte[3 * 512]; + Override(lengthOverride, length, realValue, BitConverter.GetBytes(0.5)).CopyTo(pool, 512); + Override(choiceOverride, single, singleValue, choice.ToByteArray()).CopyTo(pool, 1024); + blocks.Add(OwnedDirectory(false, Guid.Empty, 96, new(8, 0, 32, element), new(7, 32, 32, lengthOverride), + new(7, 64, 32, choiceOverride))); + blocks.Add(Pool(pool)); + } + if (classified) + { + Guid system = Guid.NewGuid(), root = Guid.NewGuid(); + Guid rootLink = new("e88a0cef-00c8-45d1-ae13-80c6616ad0f8"); + Guid treeLink = new("8d79244e-35bb-412f-8148-2b4a8839159a"); + Guid assignment = new("9534032d-da8d-4c44-b42b-6363688cafc6"); + blocks.Add(ClassificationBlock(9, system, systemType, 1, false, + [Text("Classes"), Text("1"), [0xE8, 7, 2, 0, 29, 0], Text(""), Text("")], + [Relation(0x11, rootLink, root)])); + blocks.Add(ClassificationBlock(10, root, itemType, 3, false, [Text("root"), Text(""), Text("")], + [Relation(0x12, rootLink, system), Relation(0x11, treeLink, secondClass)])); + blocks.Add(ClassificationBlock(10, secondClass, itemType, 3, false, [Text("B"), Text(""), Text("")], + [Relation(0x12, treeLink, root), Relation(0x12, assignment, element)])); + } + return (Synthetic.Fdb(blocks.ToArray()), group, length, firstClass, secondClass, choice, single, element); + + byte[] Override(Guid id, Guid definition, Guid valueClass, byte[] value) + { + byte[] prefix = new byte[39]; + overrideType.TryWriteBytes(prefix); + var fields = Synthetic.Concat([2, 0, 1, 0, 3, 0, 0], valueClass.ToByteArray(), [2, 0, 2, 0, 0, 0, 0, 0], value); + BinaryPrimitives.WriteInt32LittleEndian(prefix.AsSpan(35), fields.Length); + var links = Synthetic.Concat([1, 0], Relation(0x12, elementLink, element), + Relation(0x12, overrideLink, definition), [0]); + return Synthetic.Block(PlaBlockMode.Raw, Synthetic.Concat(prefix, fields, BitConverter.GetBytes(links.Length), links), + ver: 1, kind: 7, guid: id, extra: 1); + } + + byte[] Definition(Guid id, string name, string description, byte[] value, params byte[][] links) => + Record(id, propertyType, 6, Synthetic.Concat(Text(name), Text(description), value, [1]), + [.. links, Relation(0x12, groupLink, error == "wrong group" ? Guid.NewGuid() : group)]); + + byte[] Scalar(byte kind, byte unit, byte[] value) => + Synthetic.Concat(scalarType.ToByteArray(), [1, 0, kind, 0, unit, 0, 0, 0, 1, 0], value); + + byte[] Enumeration(Guid key, bool multi, byte[] value) + { + var header = new byte[] { 2, 0, 2, 0, 1, 0, 3, 0, 1, 0, 1, 0, 0, 0 }; + if (error == "short choice") return Synthetic.Concat(enumType.ToByteArray(), header); + return Synthetic.Concat(enumType.ToByteArray(), header, [2], key.ToByteArray(), textValue.ToByteArray(), + [2, 0, 2, 0, 0, 0, 0, 0], Text("Étage"), [1, 0, 1, 0, 0, 0], key.ToByteArray(), + [1, 0, 0, 0, 0, 0, multi ? (byte)1 : (byte)0, 0, 0, 0, 0, 1, 0], value); + } + + static byte[] Value(Guid valueClass, byte status, byte[] bytes) => + Synthetic.Concat([1, 0], valueClass.ToByteArray(), [2, 0, 2, 0, status, 0, 0, 0], bytes); + + byte[] Record(Guid id, Guid type, ushort kind, byte[] fields, params byte[][] relations) + { + var envelope = new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var body = new byte[kind == 5 ? 61 : 57]; + type.TryWriteBytes(body); + if (kind == 5) + { + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(39), 0x0102); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(41), fields.Length + envelope.Length); + } + else + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(39), 3); + envelope.CopyTo(body, body.Length - envelope.Length); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(35), body.Length + fields.Length - 39); + var tail = Synthetic.Concat([new byte[] { 1, 0 }, .. relations, new byte[] { 0 }]); + var payload = Synthetic.Concat(body, fields, BitConverter.GetBytes(tail.Length), tail); + if (kind == 6 && (framed || error == "truncated compressed chain")) + { + var first = Synthetic.QuickLzFrame(payload[..^16], payload.Length - 16, 0x46); + var literalTail = Synthetic.Concat([0, 0, 0, 0x80], payload[^16..]); + var second = Synthetic.QuickLzFrame(literalTail, 16, 0x45); + if (error == "truncated compressed chain") second = second[..^1]; + return Synthetic.Block(PlaBlockMode.Lz, Synthetic.Concat(first, second), ver: 1, kind: kind, guid: id, + unpacked: (uint)payload.Length, extra: 1); + } + return Synthetic.Block(PlaBlockMode.Raw, payload, ver: 1, kind: kind, guid: id); + } + + static byte[] Text(string value) => + Synthetic.Concat([1, 0], BitConverter.GetBytes(value.Length), Encoding.Unicode.GetBytes(value)); + + static byte[] Relation(byte tag, Guid key, params Guid[] targets) + { + var header = Synthetic.Concat([tag], key.ToByteArray()); + if (tag == 1) header = Synthetic.Concat(header, BitConverter.GetBytes(targets.Length)); + return Synthetic.Concat([header, .. targets.Select(id => id.ToByteArray())]); + } + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.WallDoorCuts.cs b/tests/PlaIO.Tests/ElementReaderTests.WallDoorCuts.cs new file mode 100644 index 0000000..45b2afd --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.WallDoorCuts.cs @@ -0,0 +1,101 @@ +using System.Buffers.Binary; +using PlaIO.Model; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + internal static (byte[] File, Guid Wall) WallWithDoorCutsFixture(double sill, double secondStation, bool reverse, + double oversize = 0, bool unsupportedRelation = false, double width = 1, double firstStation = 2) + { + Guid doorClass = new("d8f07689-9cfa-4fbe-aeb4-0a60b8e667ee"); + Guid libraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f"); + Guid tableClass = new("11db227d-dbe4-45af-88b6-6fddea993f71"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid libraryRole = new("672f1c46-64f3-41f5-8a4a-ffdfd86bcbfd"); + Guid parameterRole = new("76ebf0a4-c2ef-483f-a1a8-28d3adde99a0"); + Guid hostRole = new("1f6bfe02-d60c-40ae-9ac8-c3953ce12814"); + Guid family = new("f6fab810-3a56-4c74-8eb8-b58738a9ee9b"); + Guid revision = new("0adb90d2-efb3-4a46-ae2b-35a98d9eef91"); + Guid wall = Guid.NewGuid(), first = Guid.NewGuid(), second = Guid.NewGuid(), table = Guid.NewGuid(); + Guid firstPart = Guid.NewGuid(), secondPart = Guid.NewGuid(); + + byte[] wallBody = WallWithPlanes(1, -3.75)[..609]; + var settings = wallBody.AsSpan(209); + BinaryPrimitives.WriteDoubleLittleEndian(settings[77..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(settings[85..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(settings, reverse ? 6 : 0); + BinaryPrimitives.WriteDoubleLittleEndian(settings[8..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], reverse ? 0 : 6); + BinaryPrimitives.WriteDoubleLittleEndian(settings[24..], 2); + settings[238] = reverse ? (byte)1 : (byte)0; + BinaryPrimitives.WriteDoubleLittleEndian(settings[243..], 0.0625); + new byte[] { 0, 0, 2, 1, 59, 0, 0, 0, 1, 31, 0 }.CopyTo(settings[256..]); + BinaryPrimitives.WriteDoubleLittleEndian(settings[267..], 1e35); + BinaryPrimitives.WriteDoubleLittleEndian(settings[275..], 1e35); + BinaryPrimitives.WriteDoubleLittleEndian(settings[283..], -1e35); + BinaryPrimitives.WriteDoubleLittleEndian(settings[291..], -1e35); + wallBody = WithGeometryRelations(wallBody, GeometryRelationList(1, hostRole, first, second), + unsupportedRelation ? GeometryRelation(0x11, Guid.NewGuid(), Guid.NewGuid()) : []); + byte[] model = new byte[5 * 1024]; + var records = new List(); + Add(1, wall, wallBody); + AddDoor(first, firstPart, firstStation); + AddDoor(second, secondPart, secondStation); + + const int size = 8 + 6 * 72; + byte[] tableBody = new byte[57 + size + 24]; + tableClass.TryWriteBytes(tableBody); + new byte[] { 1, 0, 8, 0, 131, 0, 3, 0, 0, 0, 1, 0, 1, 0 }.CopyTo(tableBody, 39); + BinaryPrimitives.WriteUInt32LittleEndian(tableBody.AsSpan(35), (uint)tableBody.Length - 39); + BinaryPrimitives.WriteUInt32LittleEndian(tableBody.AsSpan(53), size); + BinaryPrimitives.WriteUInt32LittleEndian(tableBody.AsSpan(57), 6); + WriteLengthParameter(tableBody.AsSpan(65, 72), "ac_wallhole_width"u8, width); + WriteLengthParameter(tableBody.AsSpan(137, 72), "ac_wallhole_height"u8, 2); + WriteLengthParameter(tableBody.AsSpan(209, 72), "ac_left_oversize"u8, oversize); + WriteLengthParameter(tableBody.AsSpan(281, 72), "ac_right_oversize"u8, 0); + WriteLengthParameter(tableBody.AsSpan(353, 72), "ac_lower_oversize"u8, 0); + WriteLengthParameter(tableBody.AsSpan(425, 72), "ac_upper_oversize"u8, 0); + byte[] tablePool = new byte[1024]; + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(tableBody, GeometryRelationList(2, parameterRole, firstPart, secondPart)), + ver: 1, guid: table, extra: 1, kind: 4).CopyTo(tablePool, 0); + var file = Synthetic.Fdb(ClassTable((1, WallClass), (2, doorClass), (3, libraryClass), (4, tableClass), (5, storyClass)), + OwnedDirectory(false, Guid.Empty, 320, records.ToArray()), + OwnedDirectory(false, Guid.Empty, 64, new ObjectDirectoryRecord(4, 0, 64, table)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 5), Pool(model), Pool(tablePool)); + return (file, wall); + + void Add(ushort kind, Guid id, byte[] body) + { + int slot = records.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(model, slot * 1024); + records.Add(new(kind, (ulong)slot * 64, 64, id)); + } + + void AddDoor(Guid door, Guid part, double station) + { + byte[] descriptor = new byte[89]; + libraryClass.TryWriteBytes(descriptor); + new byte[] { 1, 0, 131, 0, 3, 0, 0, 0, 1, 0, 2, 0 }.CopyTo(descriptor, 39); + family.TryWriteBytes(descriptor.AsSpan(51)); + revision.TryWriteBytes(descriptor.AsSpan(67)); + Add(3, part, WithGeometryRelations(descriptor, GeometryRelation(0x12, libraryRole, door), + GeometryRelation(0x11, parameterRole, table))); + var framed = FramedElementId(doorClass, 286, "D"); + WriteLocation(framed.AsSpan(175), 1, -1); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(185), 1); + BinaryPrimitives.WriteDoubleLittleEndian(framed.AsSpan(202), width); + BinaryPrimitives.WriteDoubleLittleEndian(framed.AsSpan(210), 2); + BinaryPrimitives.WriteUInt32LittleEndian(framed.AsSpan(268), 1); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(272), 83); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(274), 2); + byte[] placement = new byte[72]; + new byte[] { 0, 1, 0, 14, 0, 0, 0, 63, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }.CopyTo(placement, 0); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(24), station); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(48), 1); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(64), sill); + Add(2, door, WithGeometryRelations(Synthetic.Concat(framed, placement), + GeometryRelation(0x11, libraryRole, part), GeometryRelation(0x12, hostRole, wall))); + } + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.cs b/tests/PlaIO.Tests/ElementReaderTests.cs new file mode 100644 index 0000000..63529cd --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.cs @@ -0,0 +1,4828 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(false, true)] + [InlineData(true, true)] + [InlineData(true, false)] + public void ReadsMaterialCatalogIncludingPhysicalDirectoryEntries(bool hidden, bool validRoot) + { + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid compositeClass = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid materialId = Guid.NewGuid(), compositeId = Guid.NewGuid(), rootId = Guid.NewGuid(); + var material = NamedAttribute(materialClass, 'M', 8, 47); + var materialBody = material.AsSpan(61); + BinaryPrimitives.WriteUInt32LittleEndian(materialBody[37..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(materialBody[41..], 'X'); + BinaryPrimitives.WriteUInt32LittleEndian(materialBody[43..], 5508); + var materialBlock = Align16(Synthetic.Block(PlaBlockMode.Raw, material, ver: 1, kind: 6, guid: materialId)); + + var composite = NamedAttribute(compositeClass, 'C', 5, 45 + 2 * 23); + var compositeBody = composite.AsSpan(61); + BinaryPrimitives.WriteUInt16LittleEndian(compositeBody[6..], 12); + BinaryPrimitives.WriteDoubleLittleEndian(compositeBody[35..], 0.2); + BinaryPrimitives.WriteUInt16LittleEndian(compositeBody[43..], 2); + for (int i = 0; i < 2; i++) + { + var skin = compositeBody[(45 + 23 * i)..]; + new byte[] { 5, 1, 17, 0, 0, 0, 1, 0 }.CopyTo(skin); + BinaryPrimitives.WriteUInt16LittleEndian(skin[8..], 8); + skin[14] = i == 0 ? (byte)5 : (byte)1; + BinaryPrimitives.WriteDoubleLittleEndian(skin[15..], i == 0 ? 0.025 : 0.175); + } + var compositeBlock = Align16(Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(composite), ver: 1, + unpacked: (uint)composite.Length, kind: 7, guid: compositeId, extra: 1)); + var classes = Align16(ClassTable((6, materialClass), (7, compositeClass))); + PlaDocument document; + if (!hidden) + document = Open(classes, compositeBlock, materialBlock); + else + { + var root = Align16(Synthetic.Block(PlaBlockMode.Raw, new byte[8], ver: 1, kind: 8, guid: rootId)); + uint rootUnits = (uint)root.Length / 16, compositeUnits = (uint)compositeBlock.Length / 16; + uint materialPosition = rootUnits + compositeUnits, materialUnits = (uint)materialBlock.Length / 16; + var header = new byte[40]; + BinaryPrimitives.WriteUInt64LittleEndian(header, materialPosition + materialUnits); + new Guid("90b1e208-3b15-45e1-854c-23f5368b97cc").TryWriteBytes(header.AsSpan(24)); + var directory = Align16(Synthetic.Block(PlaBlockMode.Raw, Synthetic.Concat(header, + Synthetic.Record(new ObjectDirectoryRecord(8, 0, rootUnits, validRoot ? rootId : Guid.NewGuid())), + Synthetic.Record(new ObjectDirectoryRecord(7, rootUnits, compositeUnits, compositeId)), + Synthetic.Record(new ObjectDirectoryRecord(6, materialPosition, materialUnits, materialId))), + ver: 1, kind: 0xFDEB)); + const ushort carrierKind = 9; + int payloadLength = root.Length + compositeBlock.Length; + int carrierHeader = Synthetic.Block(PlaBlockMode.Raw, new byte[payloadLength], kind: carrierKind).Length - payloadLength; + var carrier = Synthetic.Block(PlaBlockMode.Raw, Synthetic.Concat(new byte[16 - carrierHeader], root, compositeBlock), + kind: carrierKind); + document = Open(classes, directory, carrier, materialBlock); + Assert.DoesNotContain(document.Blocks, block => block.Guid == compositeId); + } + + using (document) + { + var catalog = document.ReadMaterialCatalog(); + Assert.Equal(new PlaBuildingMaterial(materialId, 8, "M", "X", 750), Assert.Single(catalog.BuildingMaterials)); + if (!validRoot) + Assert.Empty(catalog.Composites); + else + { + var recovered = Assert.Single(catalog.Composites); + Assert.Equal((compositeId, 5, "C", 0.2), (recovered.Guid, recovered.Index, recovered.Name, recovered.TotalThickness)); + Assert.Equal(["Wall", "Slab"], recovered.UseWith); + Assert.Equal([new PlaCompositeSkin(8, 0.025, false, true), new PlaCompositeSkin(8, 0.175, true, false)], recovered.Skins); + } + } + + static byte[] Align16(byte[] block) + { + Array.Resize(ref block, (block.Length + 15) & ~15); + return block; + } + static byte[] NamedAttribute(Guid type, char name, int index, int length) + { + var data = new byte[61 + length]; + type.TryWriteBytes(data); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(data, 47); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(55), 1); + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(59), name); + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(61), 1); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(63), index); + return data; + } + } + + [Theory] + [InlineData(true, 1)] + [InlineData(true, 2)] + [InlineData(false, 1)] + [InlineData(false, 2)] + [InlineData(false, 3)] + public void ReadsMaterialReferenceForSupportedWallsAndSlabs(bool wall, ushort structure) + { + byte[] body = wall ? WallWithPlanes(8, -3.75) : RectangularSlab(true); + var settings = body.AsSpan(wall ? 209 : 191); + int typeOffset = wall ? 225 : 83; + BinaryPrimitives.WriteUInt16LittleEndian(settings[typeOffset..], structure); + BinaryPrimitives.WriteInt32LittleEndian(settings[(typeOffset - 10)..], 8); + BinaryPrimitives.WriteUInt16LittleEndian(settings[(typeOffset + 4)..], 5); + + var element = ReadElementWithStory(wall ? WallClass : SlabClass, body); + Assert.Equal(structure == 1 ? 8 : (int?)null, element.BuildingMaterialIndex); + Assert.Equal(structure == 2 ? 5 : (int?)null, element.CompositeIndex); + } + private static readonly Guid WallClass = new("4f654582-33af-4e52-abfc-c35d46765ec4"); + private static readonly Guid BeamClass = new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca"); + private static readonly Guid ObjectClass = new("dbefcec3-1bbf-4867-b8b3-c4f7c859df61"); + private static readonly Guid SlabClass = new("945c1275-7948-41d4-8744-9d22d72ca486"); + private static readonly Guid DatabaseClass = new("f6a0e521-443b-4eda-b20a-7160cbe09115"); + private static readonly Guid GridStoreClass = new("e9969c7d-ebe2-42ff-a7dc-ed77e7e274c0"); + private static readonly Guid ProfileAttributeClass = new("31ab5131-81ae-4181-a714-7e4d3dd1a91d"); + + [Fact] + public void ReadsProfileCatalogAndMeasuresArcExtrema() + { + Guid first = Guid.NewGuid(), second = Guid.NewGuid(), unsupported = Guid.NewGuid(); + using var doc = Open(ClassTable((7, ProfileAttributeClass)), + CatalogProfileBlock(second, 9, flags: 32, material: 8, core: false), + CatalogProfileBlock(first, 2, flags: 31, material: 0, core: true), + CatalogProfileBlock(unsupported, 12, flags: 4, material: 0, core: false, withSection: false)); + Assert.Collection(doc.ReadProfileCatalog(), p => + { + Assert.Equal((first, 2, "Профиль"), (p.Guid, p.Index, p.Name)); + Assert.Equal(["Wall", "Beam", "Column", "Railing", "Object"], p.UseWith); + Assert.Equal(2, p.Width); + Assert.Equal(2, p.Height); + Assert.True(p.HasCoreSkin); + var component = Assert.Single(p.Components!); + Assert.Equal(0, component.BuildingMaterialIndex); + Assert.Equal(2 + Math.PI / 2, component.CrossSectionArea, 12); + Assert.Equal(new PlaProfileArc(0, 0, Math.PI), Assert.Single(component.Arcs!)); + }, p => + { + Assert.Equal((second, 9), (p.Guid, p.Index)); + Assert.Null(p.UseWith); + Assert.False(p.HasCoreSkin); + Assert.Null(Assert.Single(p.Components!).Function); + }, p => + { + Assert.Equal((unsupported, 12), (p.Guid, p.Index)); + Assert.Equal(["Beam"], p.UseWith); + Assert.Null(p.Components); + Assert.Null(p.Width); + Assert.Null(p.Height); + Assert.Null(p.HasCoreSkin); + }); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsConflictingProfileAttributeIndicesAndGuids(bool sameGuid) + { + Guid id = Guid.NewGuid(); + using var doc = Open(ClassTable((7, ProfileAttributeClass)), + CatalogProfileBlock(id, 2, flags: 1, material: 0, core: true), + CatalogProfileBlock(sameGuid ? id : Guid.NewGuid(), sameGuid ? 4 : 2, flags: 1, material: 0, core: true)); + Assert.Throws(doc.ReadProfileCatalog); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsProfileStretchAndOnlyReciprocallyLinkedModifierNames(bool wrongOwner) + { + Guid modifierClass = new("09f84a8c-dcf6-45b4-96aa-e23380acf496"); + Guid definitionClass = new("7fd67a75-4b36-4be8-bf9a-6ce013ab9247"); + Guid ownerRelation = new("d98b1d57-b28c-44bf-92a3-a67c8881ed56"); + Guid definitionRelation = new("43f52d63-b8d0-4659-b981-4401a14823b1"); + Guid profile = Guid.NewGuid(), modifier = Guid.NewGuid(), definition = Guid.NewGuid(); + byte[] extension = new byte[6 + 8 + 128 + 68]; + BinaryPrimitives.WriteUInt16LittleEndian(extension, 1); + BinaryPrimitives.WriteInt32LittleEndian(extension.AsSpan(2), 1); + new byte[] { 2, 0, 9, 1 }.CopyTo(extension, 6); + BinaryPrimitives.WriteInt32LittleEndian(extension.AsSpan(10), 128); + BinaryPrimitives.WriteInt32LittleEndian(extension.AsSpan(14), 128); + var stretch = extension.AsSpan(142); + for (int i = 0; i <= 24; i += 6) stretch[i] = 1; + stretch[26] = 1; + BinaryPrimitives.WriteDoubleLittleEndian(stretch[27..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(stretch[35..], 1.75); + stretch[60] = 2; + stretch[63] = 4; + stretch[67] = 1; + extension = WithGeometryRelations(extension, GeometryRelation(0x11, ownerRelation, modifier)); + + byte[] name = System.Text.Encoding.Unicode.GetBytes("Глубина"); + byte[] definitionRecord = new byte[53 + name.Length]; + definitionClass.TryWriteBytes(definitionRecord); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(definitionRecord, 41); + BinaryPrimitives.WriteInt32LittleEndian(definitionRecord.AsSpan(49), name.Length / 2); + name.CopyTo(definitionRecord, 53); + using var doc = Open(ClassTable((7, ProfileAttributeClass), (8, modifierClass), (9, definitionClass)), + CatalogProfileBlock(profile, 2, flags: 5, material: 8, core: true, extension: extension), + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(modifierClass.ToByteArray(), + HostRelation(ownerRelation, wrongOwner ? Guid.NewGuid() : profile), HostRelation(definitionRelation, definition)), + ver: 1, kind: 8, guid: modifier, extra: 1), + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(definitionRecord, GeometryRelation(0x11, definitionRelation, modifier)), + ver: 1, kind: 9, guid: definition, extra: 1)); + var p = Assert.Single(doc.ReadProfileCatalog()); + Assert.Equal(new PlaProfileStretch(true, 0.25, 1.75, 0.5), p.WidthStretch); + Assert.Equal(new PlaProfileStretch(false, null, null, 2), p.HeightStretch); + if (wrongOwner) + Assert.Null(p.Modifiers); + else + Assert.Equal(new PlaProfileModifier(modifier, definition, "Глубина"), Assert.Single(p.Modifiers!)); + } + + internal static byte[] ProfileCatalogFile(Guid id) => Synthetic.Fdb(ClassTable((7, ProfileAttributeClass)), + CatalogProfileBlock(id, 3, flags: 5, material: 8, core: true)); + + [Theory] + [InlineData("valid", 1.0)] + [InlineData("negative", -1.0)] + [InlineData("unknown vertex", null)] + [InlineData("conflicting dimensions", null)] + public void MeasuresProfileModifierDefaultFromItsAnchors(string variation, double? expected) + { + Guid modifierClass = new("09f84a8c-dcf6-45b4-96aa-e23380acf496"); + Guid definitionClass = new("7fd67a75-4b36-4be8-bf9a-6ce013ab9247"); + Guid ownerRelation = new("d98b1d57-b28c-44bf-92a3-a67c8881ed56"); + Guid definitionRelation = new("43f52d63-b8d0-4659-b981-4401a14823b1"); + Guid profile = Guid.NewGuid(), modifier = Guid.NewGuid(), definition = Guid.NewGuid(), hatch = Guid.NewGuid(); + Guid key = Guid.NewGuid(), group1 = Guid.NewGuid(), group2 = Guid.NewGuid(); + Guid dimension1 = Guid.NewGuid(), dimension2 = Guid.NewGuid(); + Guid edge = Guid.NewGuid(), vertex = Guid.NewGuid(), point = Guid.NewGuid(); + byte[] modifierRecord = new byte[63]; + modifierClass.TryWriteBytes(modifierRecord); + new byte[] { 1, 0, 0x83, 0, 3, 0, 0, 0 }.CopyTo(modifierRecord, 39); + key.TryWriteBytes(modifierRecord.AsSpan(47)); + byte[] definitionRecord = new byte[55]; + definitionClass.TryWriteBytes(definitionRecord); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(definitionRecord, 41); + BinaryPrimitives.WriteInt32LittleEndian(definitionRecord.AsSpan(49), 1); + definitionRecord[53] = (byte)'A'; + + using var data = new MemoryStream(); + using var writer = new BinaryWriter(data); + Count(1); + writer.Write(key.ToByteArray()); + Count(2); + writer.Write(group1.ToByteArray()); + writer.Write(group2.ToByteArray()); + Count(2); + Group(group1, dimension1); + Group(group2, dimension2); + Count(3); + Anchor(edge, 1, 1); + Anchor(vertex, 2, variation == "unknown vertex" ? 99 : 5); + Anchor(point, 3, 0, variation == "conflicting dimensions" ? 2 : 1); + Count(2); + Dimension(dimension1, vertex); + Dimension(dimension2, point); + + PlaProfilePoint[] outside = [new(0, 0), new(5, 0), new(5, 5), new(0, 5), new(0, 0)]; + PlaProfilePoint[] hole = [new(1, 1), new(1, 3), new(3, 3), new(3, 1), new(1, 1)]; + using var doc = Open(ClassTable((7, ProfileAttributeClass), (8, modifierClass), (9, definitionClass)), + CatalogProfileBlock(profile, 2, flags: 1, material: 8, core: true, + extension: WithGeometryRelations(data.ToArray(), GeometryRelation(0x11, ownerRelation, modifier)), + geometry: (hatch, [outside, hole])), + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(modifierRecord, + HostRelation(ownerRelation, profile), HostRelation(definitionRelation, definition)), ver: 1, kind: 8, guid: modifier), + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(definitionRecord, + GeometryRelation(0x11, definitionRelation, modifier)), ver: 1, kind: 9, guid: definition)); + var decoded = Assert.Single(Assert.Single(doc.ReadProfileCatalog()).Modifiers!); + Assert.Equal("A", decoded.Name); + if (expected is { } value) + Assert.Equal(value, decoded.DefaultValue!.Value, 12); + else + Assert.Null(decoded.DefaultValue); + + void Count(int count) + { + writer.Write((ushort)1); + writer.Write(count); + } + + void Group(Guid group, Guid dimension) + { + writer.Write(group.ToByteArray()); + Count(2); + writer.Write((ushort)1); + Count(1); + writer.Write(new byte[] { 1, 0, 1, 0 }); + writer.Write(hatch.ToByteArray()); + writer.Write(1); + writer.Write(1); + writer.Write(dimension.ToByteArray()); + } + + void Anchor(Guid id, int kind, int index, double z = 0) + { + var anchor = new byte[67]; + anchor[0] = anchor[6] = anchor[28] = anchor[50] = 1; + BinaryPrimitives.WriteInt32LittleEndian(anchor.AsSpan(2), kind); + if (kind is 1 or 2) + { + int offset = kind == 1 ? 8 : 30; + hatch.TryWriteBytes(anchor.AsSpan(offset)); + BinaryPrimitives.WriteInt32LittleEndian(anchor.AsSpan(offset + 16), index); + } + else + BinaryPrimitives.WriteDoubleLittleEndian(anchor.AsSpan(59), z); + writer.Write(id.ToByteArray()); + writer.Write(anchor); + } + + void Dimension(Guid id, Guid target) + { + writer.Write(id.ToByteArray()); + writer.Write(new byte[] { 1, 1, 92, 0, 0, 0 }); + writer.Write(edge.ToByteArray()); + writer.Write(target.ToByteArray()); + writer.Write(edge.ToByteArray()); + writer.Write(key.ToByteArray()); + writer.Write(key.ToByteArray()); + writer.Write(2); + writer.Write(variation == "negative" ? -Math.PI / 2 : Math.PI / 2); + } + } + + private static byte[] CatalogProfileBlock(Guid id, int index, ushort flags, int material, bool core, + bool withSection = true, byte[]? extension = null, (Guid Id, PlaProfilePoint[][] Rings)? geometry = null) + { + byte[] name = System.Text.Encoding.Unicode.GetBytes("Профиль"); + const int frame = 37; + int settings = 63 + name.Length; + PlaProfilePoint[] ring = [new(0, 0), new(2, 0), new(2, 1), new(0, 1), new(0, 0)]; + byte[] hatch = SavedProfileHatch(material, core ? (byte)1 : (byte)2, geometry.HasValue ? 0 : 2, + geometry?.Rings ?? [ring]); + int hatchStart = 128 + (geometry.HasValue ? 16 : 0); + int sectionLength = withSection ? 8 + hatchStart + hatch.Length : 0; + var data = new byte[settings + frame + sectionLength + (extension?.Length ?? 0)]; + ProfileAttributeClass.TryWriteBytes(data); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(data, 51); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(59), name.Length / 2); + name.CopyTo(data, 63); + var body = data.AsSpan(settings); + BinaryPrimitives.WriteUInt16LittleEndian(body, 1); + BinaryPrimitives.WriteInt32LittleEndian(body[2..], index); + BinaryPrimitives.WriteUInt16LittleEndian(body[35..], flags); + if (withSection) + { + new byte[] { 2, 0, 9, 1 }.CopyTo(body[frame..]); + BinaryPrimitives.WriteInt32LittleEndian(body[(frame + 4)..], hatchStart + hatch.Length); + BinaryPrimitives.WriteInt32LittleEndian(body[(frame + 8)..], 128); + BinaryPrimitives.WriteInt32LittleEndian(body[(frame + 8 + 69)..], 1); + if (geometry is { } keyed) + keyed.Id.TryWriteBytes(body[(frame + 8 + hatchStart - 16)..]); + hatch.CopyTo(body[(frame + 8 + hatchStart)..]); + } + extension?.CopyTo(data, settings + frame + sectionLength); + return Synthetic.Block(PlaBlockMode.Raw, data, ver: 1, kind: 7, guid: id, extra: 1); + } + + [Theory] + [InlineData(3, false)] + [InlineData(23, true)] + public void ReadsTheClassGuidAndWallParametersThroughTheFileLocalNumber(ushort number, bool prefixed) + { + Guid wallId = Guid.NewGuid(), unknownClass = Guid.NewGuid(); + using var doc = Open( + ClassTable((number, WallClass), (1, ObjectClass), (2, unknownClass)), + ElementDirectory(prefixed, new(number, 0, 8, wallId), new(1, 8, 8, Guid.NewGuid()), + new(2, 16, 8, Guid.NewGuid()), new(number, ulong.MaxValue, 8, Guid.NewGuid())), + Pool(Subgroup(number, wallId, Wall("Стена-01")))); + + Assert.Collection(doc.ReadObjectClasses(), + c => Assert.Equal(new PlaObjectClass(1, ObjectClass, "Object"), c), + c => Assert.Equal(new PlaObjectClass(2, unknownClass, null), c), + c => Assert.Equal(new PlaObjectClass(number, WallClass, "Wall"), c)); + Assert.Equal(new PlaElement(wallId, "Wall", "Стена-01", 0.25, 5), Assert.Single(doc.ReadElements())); + } + + [Fact] + public void IncompleteAndConflictingSubgroupsDoNotSupplyParameters() + { + Guid conflict = Guid.NewGuid(), truncated = Guid.NewGuid(), wrongClass = Guid.NewGuid(); + using var doc = Open( + ClassTable((1, WallClass), (2, BeamClass)), + ElementDirectory(false, new(1, 0, 8, conflict), new(2, 8, 8, truncated), new(1, 16, 8, wrongClass)), + Pool(Subgroup(1, conflict, Wall("A")), Subgroup(1, conflict, Wall("B")), + Subgroup(2, truncated, ElementId("B")[..^1]), Subgroup(2, wrongClass, ElementId("Wrong class")))); + + var elements = doc.ReadElements(); + Assert.Equal(3, elements.Count); + Assert.All(elements, element => Assert.Null(element.ElementId)); + Assert.All(elements, element => Assert.Null(element.WallThickness)); + } + + [Fact] + public void MissingClassTableIsReported() + { + using var doc = Open(ElementDirectory(false)); + Assert.Throws(doc.ReadElements); + } + + [Fact] + public void ReadsSavedStoryCatalogWithoutElementRecords() + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + byte[] table = StoryTable(storyClass); + BinaryPrimitives.WriteDoubleLittleEndian(table.AsSpan(table.Length - 23), 3); + using var doc = Open(ClassTable((7, storyClass)), Synthetic.Block(PlaBlockMode.Raw, table, ver: 1, kind: 7)); + + Assert.Equal([new PlaStory(-1, "Подвал", -4), new PlaStory(0, "", 0)], doc.ReadStories()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void StoryCatalogRejectsInvalidRangesAndLeavesConflictingElevationsUnset(bool invalidRange) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + byte[] first = StoryTable(storyClass), second = StoryTable(storyClass); + BinaryPrimitives.WriteDoubleLittleEndian(second.AsSpan(52), -6); + if (invalidRange) BinaryPrimitives.WriteInt32LittleEndian(second.AsSpan(second.Length - 4), 1); + using var doc = Open(ClassTable((1, storyClass)), Synthetic.Block(PlaBlockMode.Raw, first, ver: 1, kind: 1), + Synthetic.Block(PlaBlockMode.Raw, second, ver: 1, kind: 1)); + + if (invalidRange) + Assert.Throws(doc.ReadStories); + else + Assert.Equal([new PlaStory(-1, "Подвал", null), new PlaStory(0, "", 0)], doc.ReadStories()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsLayerCatalogAndReportsConflictingIdentities(bool conflictingGuid) + { + var layerClass = new Guid("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + var builtIn = new Guid("4d22523e-c844-4209-a123-3608c8964de4"); + Guid userLayer = Guid.NewGuid(); + byte[] token = [1, 0, 0, 0, 0x14, 0]; + using var doc = Open(ClassTable((7, layerClass)), + Layer(8, ElementId("Стены")[14..], 0, userLayer), Layer(1, token, 1, builtIn), + conflictingGuid ? Layer(9, ElementId("Двери")[14..], 1, userLayer) : Layer(10, token, 1, Guid.NewGuid())); + + if (conflictingGuid) + Assert.Throws(doc.ReadLayers); + else + Assert.Equal([new PlaLayer(builtIn, 1, null, 1), new PlaLayer(userLayer, 8, "Стены", 0)], doc.ReadLayers()); + + byte[] Layer(int index, byte[] name, uint group, Guid id) + { + byte[] prefix = new byte[55]; + layerClass.TryWriteBytes(prefix); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(prefix, 47); + byte[] tail = new byte[39]; + tail[0] = 1; + BinaryPrimitives.WriteInt32LittleEndian(tail.AsSpan(2), index); + BinaryPrimitives.WriteUInt32LittleEndian(tail.AsSpan(35), group); + return Synthetic.Block(PlaBlockMode.Raw, Synthetic.Concat(prefix, name, tail), ver: 1, guid: id, kind: 7); + } + } + + [Fact] + public void SlabElementIdUsesItsOwnClassFrame() + { + Guid id = Guid.NewGuid(), wrongFrame = Guid.NewGuid(); + byte[] slab = FramedElementId(SlabClass, 185, "SL-1"); + byte[] other = FramedElementId(WallClass, 185, "SL-1"); + using var doc = Open(ClassTable((1, SlabClass)), + ElementDirectory(false, new(1, 0, 8, id), new(1, 8, 8, wrongFrame)), + Pool(Subgroup(1, id, slab), Subgroup(1, wrongFrame, other))); + + Assert.Collection(doc.ReadElements(), + element => Assert.Equal(new PlaElement(id, "Slab", "SL-1", null, null), element), + element => Assert.Equal(new PlaElement(wrongFrame, "Slab", null, null, null), element)); + } + + [Theory] + [InlineData("Opening", "6746aa79-7498-4bea-bad8-191cdad31d05", 185, "", PlaBlockMode.Raw)] + [InlineData("Lamp", "342a8b55-7348-486a-850b-1eb1bed031fc", 289, "Свет-01", PlaBlockMode.ZeroMask)] + [InlineData("Stair", "fa0f7f15-29b4-4905-80fa-c6769109847b", 185, "ST-01", PlaBlockMode.Lz)] + public void ReadsElementIdsFromIndexedRawZeroMaskAndQuickLzRecords(string type, string classId, int offset, + string elementId, PlaBlockMode mode) + { + Guid id = Guid.NewGuid(), classGuid = new(classId); + byte[] plain = FramedElementId(classGuid, offset, elementId); + byte[] packed = mode switch + { + PlaBlockMode.ZeroMask => Synthetic.ZeroMask(plain), + PlaBlockMode.Lz => Synthetic.QuickLzFrame(plain.Chunk(31) + .SelectMany(chunk => Synthetic.Concat([0, 0, 0, 0x80], chunk)).ToArray(), plain.Length, 0x47), + _ => plain, + }; + byte[] decodedPool = new byte[512]; + Synthetic.Block(mode, packed, ver: 1, unpacked: (uint)plain.Length, guid: id, extra: 0xFFFFFFFF, kind: 1) + .CopyTo(decodedPool, 0); + using var doc = Open(ClassTable((1, classGuid)), ElementDirectory(false, new ObjectDirectoryRecord(1, 0, 32, id)), Pool(decodedPool)); + + Assert.Equal(new PlaElement(id, type, elementId, null, null), Assert.Single(doc.ReadElements())); + } + + [Theory] + [InlineData(true, true)] + [InlineData(false, true)] + [InlineData(true, false)] + public void ZoneIdComesFromTheLinkedStamp(bool matchingGuid, bool validLength) + { + Guid zoneClass = new("3ad0332e-efe2-491a-92a6-5b14bfdd7229"); + Guid zoneId = Guid.NewGuid(), stampId = Guid.NewGuid(); + byte[] zone = FramedElementId(zoneClass, 185, "Room-304"); + byte[] relationship = new byte[4 + 19 + 16]; + BinaryPrimitives.WriteUInt32LittleEndian(relationship, validLength ? 35u : 36u); + relationship[4] = 1; + relationship[6] = 0x11; + Assert.True(new Guid("5bbc9f04-754d-408b-8e1b-4f20c33cd868").TryWriteBytes(relationship.AsSpan(7))); + Assert.True((matchingGuid ? stampId : Guid.NewGuid()).TryWriteBytes(relationship.AsSpan(23))); + zone = Synthetic.Concat(zone, relationship); + + byte[] decodedPool = new byte[1024]; + Synthetic.Block(PlaBlockMode.Raw, FramedElementId(ObjectClass, 289, "ZN-01"), ver: 1, guid: stampId, extra: 1, kind: 2) + .CopyTo(decodedPool, 0); + Synthetic.Block(PlaBlockMode.Raw, zone, ver: 1, guid: zoneId, extra: 1, kind: 1).CopyTo(decodedPool, 512); + using var doc = Open(ClassTable((1, zoneClass), (2, ObjectClass)), + OwnedDirectory(false, Guid.Empty, 64, new(2, 0, 32, stampId), new(1, 32, 32, zoneId)), Pool(decodedPool)); + + Assert.Equal(new PlaElement(zoneId, "Zone", matchingGuid && validLength ? "ZN-01" : null, null, null), + Assert.Single(doc.ReadElements())); + } + + [Theory] + [InlineData(true, 1, 0)] + [InlineData(true, 2, 0)] + [InlineData(false, 1, 0)] + [InlineData(true, 0, 1)] + [InlineData(true, 3, 2)] + [InlineData(true, 1, 3)] + [InlineData(true, 1, 0, 1)] + [InlineData(true, 1, 0, 2)] + [InlineData(true, 1, 0, 3)] + [InlineData(true, 1, 0, 4)] + public void ReadsHostedLocationsAndVerifiesDoorHostAndDimensions(bool matchingHost, int reciprocal, int invalidDimensions, + int placementCase = 0) + { + var fixture = HostedElementsFixture(matchingHost, reciprocal, invalidDimensions, placementCase); + var (wallId, doorId, openingId) = (fixture.Wall, fixture.Door, fixture.Opening); + using var doc = PlaDocument.Open(new MemoryStream(fixture.File)); + var elements = doc.ReadElements().ToDictionary(e => e.Guid); + Assert.Equal((17, "Несущие стены", -1, "Подвал"), Location(elements[wallId])); + Assert.Equal((matchingHost ? 17 : (int?)null, matchingHost ? "Несущие стены" : null, 0, ""), Location(elements[doorId])); + Assert.Equal(matchingHost && reciprocal is 1 or 2 ? wallId : (Guid?)null, elements[doorId].HostGuid); + PlaDoorDimensions? dimensions = invalidDimensions is 1 or 2 ? null : + new PlaDoorDimensions(0.9, 2.1) { SillHeightFromAnchor = invalidDimensions == 3 ? null : 0.1 }; + Assert.Equal(dimensions, elements[doorId].DoorDimensions); + var point = placementCase == 1 ? new PlaPlanPoint(3.25, 5) : new PlaPlanPoint(1.75, 3); + PlaDoorPlacement? placement = matchingHost && reciprocal is 1 or 2 && invalidDimensions == 0 && placementCase is 0 or 1 + ? new PlaDoorPlacement(point, 1.25, -3.65, 0.35) : null; + Assert.Equal(placement, elements[doorId].DoorPlacement); + Assert.Equal(matchingHost ? Location(elements[wallId]) : (null, null, null, null), Location(elements[openingId])); + } + + internal static (byte[] File, Guid Wall, Guid Door, Guid Opening) HostedElementsFixture(bool matchingHost, + int reciprocal, int invalidDimensions, int placementCase) + { + Guid doorClass = new("d8f07689-9cfa-4fbe-aeb4-0a60b8e667ee"); + Guid openingClass = new("6746aa79-7498-4bea-bad8-191cdad31d05"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid doorHost = new("1f6bfe02-d60c-40ae-9ac8-c3953ce12814"); + Guid wallId = Guid.NewGuid(), doorId = Guid.NewGuid(), openingId = Guid.NewGuid(); + Guid host = matchingHost ? wallId : Guid.NewGuid(); + + byte[] wall = WallWithPlanes(1, -3.75); + var wallSettings = wall.AsSpan(209); + bool reverse = placementCase == 1; + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings, reverse ? 4 : 1); + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[8..], reverse ? 6 : 2); + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[16..], reverse ? 1 : 4); + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[24..], reverse ? 2 : 6); + if (placementCase == 2) wallSettings[184] = 1; + WriteLocation(wall.AsSpan(163), 17, -1); + if (reciprocal != 0) + { + wall = WithGeometryRelations(wall, reciprocal == 1 ? GeometryRelation(0x11, doorHost, doorId) : + GeometryRelationList(1, doorHost, reciprocal == 2 ? Guid.NewGuid() : doorId, doorId)); + } + byte[] door = FramedElementId(doorClass, 286, "DR-01"); + WriteLocation(door.AsSpan(175), 34, 0); + BinaryPrimitives.WriteUInt16LittleEndian(door.AsSpan(185), 1); + BinaryPrimitives.WriteDoubleLittleEndian(door.AsSpan(202), invalidDimensions == 1 ? double.NaN : 0.9); + BinaryPrimitives.WriteDoubleLittleEndian(door.AsSpan(210), 2.1); + BinaryPrimitives.WriteUInt32LittleEndian(door.AsSpan(268), 1); + BinaryPrimitives.WriteUInt16LittleEndian(door.AsSpan(272), invalidDimensions == 2 ? (ushort)0 : (ushort)83); + BinaryPrimitives.WriteUInt16LittleEndian(door.AsSpan(274), 2); + var tail = new byte[72]; + new byte[] { 0, 1, 0, 14, 0, 0, 0, 63, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 255, 0, 0 }.CopyTo(tail, 0); + if (invalidDimensions == 3) tail[15] = 0; + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(24), placementCase == 3 ? 5.1 : 1.25); + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(48), 1); + if (placementCase == 4) BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(56), 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(64), 0.1); + door = WithGeometryRelations(Synthetic.Concat(door, tail), GeometryRelation(0x12, doorHost, host)); + byte[] opening = Synthetic.Concat(FramedElementId(openingClass, 185, "OP-01"), + HostRelation(new Guid("49f5b35f-3e0e-4644-a659-d024c2c93228"), host)); + byte[] pool = new byte[3 * 1024]; + Synthetic.Block(PlaBlockMode.Raw, wall, ver: 1, guid: wallId, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, door, ver: 1, guid: doorId, extra: 1, kind: 2).CopyTo(pool, 1024); + Synthetic.Block(PlaBlockMode.Raw, opening, ver: 1, guid: openingId, extra: 1, kind: 3).CopyTo(pool, 2048); + + byte[] layer = new byte[55]; + Assert.True(layerClass.TryWriteBytes(layer)); + byte[] layerNameFrame = [0x83, 0, 3, 0, 0, 0, 1, 0]; + layerNameFrame.CopyTo(layer, 47); + layer = Synthetic.Concat(layer, ElementId("Несущие стены")[14..], [1, 0, 17, 0, 0, 0]); + var file = Synthetic.Fdb(ClassTable((1, WallClass), (2, doorClass), (3, openingClass), (4, layerClass), (5, storyClass)), + OwnedDirectory(false, Guid.Empty, 192, new(1, 0, 64, wallId), new(2, 64, 64, doorId), new(3, 128, 64, openingId)), + Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(layer), ver: 1, unpacked: (uint)layer.Length, kind: 0xFFDC), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 5), Pool(pool)); + return (file, wallId, doorId, openingId); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + [InlineData(5)] + [InlineData(6)] + [InlineData(7)] + public void ReadsOpeningProfileAndReciprocalCutTargets(int variation) + { + Guid openingClass = new("6746aa79-7498-4bea-bad8-191cdad31d05"); + Guid cutClass = new("9a756127-8689-486d-8873-5c1d7b0f8785"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid hostRole = new("49f5b35f-3e0e-4644-a659-d024c2c93228"); + Guid openingRole = new("219fcd20-e2ef-4e61-bb1b-a771897ff878"); + Guid targetRole = new("fc9598c9-7004-45ef-93e0-8fdcbc306acf"); + Guid openingId = Guid.NewGuid(), wallId = Guid.NewGuid(), slabId = Guid.NewGuid(); + Guid wallCut = Guid.NewGuid(), slabCut = Guid.NewGuid(); + + var wall = WallWithPlanes(1, -3.75); + WriteLocation(wall.AsSpan(163), 2, -1); + wall = WithGeometryRelations(wall, + GeometryRelationList(1, hostRole, variation == 3 ? Guid.NewGuid() : openingId), + GeometryRelation(0x11, targetRole, variation == 4 ? Guid.NewGuid() : wallCut)); + var slab = WithGeometryRelations(RectangularSlab(true), GeometryRelation(0x11, targetRole, slabCut)); + + var settings = OpeningSettings(variation == 1 ? 1u : 2u, 0.5, 0.75, linked: variation != 1); + double center = variation == 7 ? 0.375 : 2; + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(270), center); + if (variation == 5) settings[307] = 2; + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(variation == 6 ? 190 : 198), 1); + var opening = WithGeometryRelations(Synthetic.Concat(FramedElementId(openingClass, 185, "OP"), settings), + HostRelation(hostRole, wallId), + variation == 2 ? GeometryRelationList(1, openingRole, slabCut, wallCut) : GeometryRelation(0x11, openingRole, wallCut)); + + byte[] pool = new byte[5 * 1024]; + var records = new List(); + void Add(ushort kind, Guid id, byte[] body) + { + int block = records.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, block * 1024); + records.Add(new ObjectDirectoryRecord(kind, (ulong)block * 64, 64, id)); + } + Add(1, openingId, opening); + Add(2, wallId, wall); + Add(3, slabId, slab); + Add(4, wallCut, WithGeometryRelations(cutClass.ToByteArray(), HostRelation(openingRole, openingId), HostRelation(targetRole, wallId))); + Add(4, slabCut, WithGeometryRelations(cutClass.ToByteArray(), HostRelation(openingRole, openingId), HostRelation(targetRole, slabId))); + using var doc = Open(ClassTable((1, openingClass), (2, WallClass), (3, SlabClass), (4, cutClass), (5, storyClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, records.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 5), Pool(pool)); + var elements = doc.ReadElements(); + var element = Assert.Single(elements, item => item.Guid == openingId); + Assert.Equal(variation == 3 ? null : (Guid?)wallId, element.HostGuid); + if (variation is 3 or 4) + Assert.Null(element.OpeningCutElementGuids); + else + Assert.Equal(variation == 2 ? new[] { wallId, slabId }.Order().ToArray() : [wallId], element.OpeningCutElementGuids); + Assert.Equal(variation == 5 ? null : variation == 1 ? new PlaOpeningProfile("Rectangle", 0.5, 0.75) : + new PlaOpeningProfile("Circle", 0.5, 0.5), element.OpeningProfile); + + double? halfHeight = variation is 0 or 7 ? 0.25 : variation == 1 ? 0.375 : null; + Assert.Equal(center - halfHeight, element.BottomElevationToHomeStory); + Assert.Equal(center + halfHeight, element.TopElevationToHomeStory); + Assert.Equal(center - 4 - halfHeight, element.BottomElevationToProjectZero); + Assert.Equal(center - 4 + halfHeight, element.TopElevationToProjectZero); + + var host = Assert.Single(elements, item => item.Guid == wallId); + double? wallBottom = variation is 0 or 1 ? 0.25 : null; + double? wallTop = wallBottom + 3; + Assert.Equal(wallBottom, host.BottomElevationToHomeStory); + Assert.Equal(wallTop, host.TopElevationToHomeStory); + Assert.Equal(wallBottom - 4, host.BottomElevationToProjectZero); + Assert.Equal(wallTop - 4, host.TopElevationToProjectZero); + } + + [Theory] + [InlineData(0, -0.5, 0.5)] + [InlineData(1, 0.125, 0.5)] + [InlineData(2, null, null)] + [InlineData(3, null, null)] + [InlineData(4, -0.5, 1.0)] + [InlineData(5, -0.25, 0.5)] + [InlineData(6, null, null)] + [InlineData(7, -0.5, 0.5)] + [InlineData(8, -0.5, 0.5)] + [InlineData(9, -0.5, 0.5)] + public void ResolvesSlabOpeningElevationsFromCutLimitsAndOverlaps(int variation, double? bottom, double? top) + { + var (file, opening, slab, other, secondSlab) = SlabOpeningFixture(variation); + using var doc = PlaDocument.Open(new MemoryStream(file)); + var elements = doc.ReadElements(); + var element = Assert.Single(elements, e => e.Guid == opening); + Assert.Equal(slab, element.HostGuid); + Assert.Equal(bottom, element.BottomElevationToHomeStory); + Assert.Equal(top, element.TopElevationToHomeStory); + Assert.Equal(bottom - 4, element.BottomElevationToProjectZero); + Assert.Equal(top - 4, element.TopElevationToProjectZero); + var solid = Assert.IsType(Assert.Single(elements, e => e.Guid == slab).SlabGeometry); + const double circleArea = 0.19684949293332902; + Assert.Null(solid.VerticalPrisms); + if (bottom is null || variation == 8) + { + Assert.Null(solid.TopAreaWithOpenings); + Assert.Null(solid.BottomAreaWithOpenings); + Assert.Null(solid.Volume); + } + else + { + Assert.Equal(4 - circleArea, solid.TopAreaWithOpenings!.Value, 12); + double removedBelow = variation switch { 1 => 2.25, 5 => 0, _ => circleArea }; + Assert.Equal(4 - removedBelow, solid.BottomAreaWithOpenings!.Value, 12); + double expectedVolume = 4 - circleArea * (0.5 - bottom.Value) - (variation == 1 ? 1.40625 : 0); + if (variation == 9) + Assert.Null(solid.Volume); + else + Assert.Equal(expectedVolume, solid.Volume!.Value, 12); + } + if (variation is 4 or 7) + { + var secondary = Assert.IsType(Assert.Single(elements, e => e.Guid == secondSlab).SlabGeometry); + double area = variation == 7 ? 4 : 4 - circleArea; + Assert.Equal(area, secondary.TopAreaWithOpenings!.Value, 12); + Assert.Equal(area, secondary.BottomAreaWithOpenings!.Value, 12); + Assert.Equal(area * 0.25, secondary.Volume!.Value, 12); + } + if (variation == 3) + { + Assert.Null(element.OpeningGeometry); + return; + } + var geometry = Assert.IsType(element.OpeningGeometry); + Assert.Equal(new PlaPlanPoint(variation == 2 ? 0.875 : 0.25, -0.125), geometry.Origin); + Assert.Null(geometry.Rings); + if (bottom is null || variation == 8) + { + Assert.Null(geometry.Cuts); + Assert.Null(geometry.CutVolume); + } + else + { + Assert.NotNull(geometry.Cuts); + Assert.Equal(variation == 4 ? 2 : 1, geometry.Cuts.Count); + Assert.Equal(new PlaOpeningCut(slab, bottom.Value - 4, (variation == 4 ? 0.5 : top!.Value) - 4), geometry.Cuts[0]); + if (variation == 4) Assert.Equal(new PlaOpeningCut(secondSlab, -3.25, -3), geometry.Cuts[1]); + Assert.Equal(circleArea * (variation == 4 ? 1.25 : top!.Value - bottom.Value), geometry.CutVolume!.Value, 12); + } + if (variation == 1) + { + var recess = Assert.IsType(Assert.Single(elements, e => e.Guid == other).OpeningGeometry); + Assert.NotNull(recess.Rings); + Assert.Equal(new PlaPlanPoint(-0.5, -0.875), Assert.Single(recess.Rings)[0]); + Assert.Equal(new PlaOpeningCut(slab, -4.5, -3.875), Assert.Single(recess.Cuts!)); + Assert.Equal(1.40625, recess.CutVolume); + } + } + + internal static (byte[] File, Guid Opening, Guid Slab, Guid Other, Guid SecondSlab) SlabOpeningFixture( + int variation, bool rectangular = false, bool slabAlignedFrame = false) + { + Guid openingClass = new("6746aa79-7498-4bea-bad8-191cdad31d05"); + Guid cutClass = new("9a756127-8689-486d-8873-5c1d7b0f8785"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid hostRole = new("49f5b35f-3e0e-4644-a659-d024c2c93228"); + Guid openingRole = new("219fcd20-e2ef-4e61-bb1b-a771897ff878"); + Guid targetRole = new("fc9598c9-7004-45ef-93e0-8fdcbc306acf"); + Guid opening = Guid.NewGuid(), slab = Guid.NewGuid(), cut = Guid.NewGuid(); + Guid other = Guid.NewGuid(), secondSlab = Guid.NewGuid(), secondCut = Guid.NewGuid(); + + const int slotSize = 2048; + byte[] pool = new byte[5 * slotSize]; + var records = new List(); + void Add(ushort kind, Guid id, byte[] body) + { + int block = records.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, block * slotSize); + records.Add(new ObjectDirectoryRecord(kind, (ulong)block * (slotSize / 16), slotSize / 16, id)); + } + void AddCut(Guid id, Guid source, Guid target) => Add(3, id, + WithGeometryRelations(cutClass.ToByteArray(), HostRelation(openingRole, source), HostRelation(targetRole, target))); + + var settings = OpeningSettings(rectangular ? 1u : 2u, 0.5, 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(134), variation switch { 2 => 0.625, 10 => 0.5, _ => 0 }); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(158), 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(190), 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(222), slabAlignedFrame ? -1 : 1); + if (slabAlignedFrame) BinaryPrimitives.WriteUInt32LittleEndian(settings.AsSpan(266), 2); + if (variation == 5) + { + BinaryPrimitives.WriteUInt32LittleEndian(settings.AsSpan(278), 2); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(282), -0.75); + } + + bool multipleSlabs = variation is 4 or 7; + Add(1, opening, WithGeometryRelations(Synthetic.Concat(FramedElementId(openingClass, 185, "OP"), settings), + HostRelation(hostRole, slab), + multipleSlabs ? GeometryRelationList(1, openingRole, cut, secondCut) : GeometryRelation(0x11, openingRole, cut))); + AddCut(cut, opening, slab); + bool overlapping = variation is 1 or 2 or 6 or 8; + byte[] slabBody = OpeningSlab(-1, 0.5, 1, variation == 3); + if (slabAlignedFrame) + { + slabBody[191 + 8] = 1; + BinaryPrimitives.WriteDoubleLittleEndian(slabBody.AsSpan(191), 0.375); + BinaryPrimitives.WriteDoubleLittleEndian(slabBody.AsSpan(191 + 9), 0.125); + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 83), 2); + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 87), 1); + } + Add(2, slab, WithGeometryRelations(slabBody, + overlapping ? GeometryRelationList(1, hostRole, opening, other) : GeometryRelation(0x11, hostRole, opening), + overlapping ? GeometryRelationList(1, targetRole, cut, secondCut) : GeometryRelation(0x11, targetRole, cut), + variation == 9 ? GeometryRelation(0x11, Guid.NewGuid(), Guid.NewGuid()) : [])); + + if (overlapping) + { + var recess = OpeningSettings(3, 1.5, 1.5); + Array.Resize(ref recess, 304 + 247); + WriteRectangularPlan(recess.AsSpan(304), -0.75, -0.75, 0.75, 0.75, slab: false); + recess[312] = 1; + BinaryPrimitives.WriteDoubleLittleEndian(recess.AsSpan(158), 1); + BinaryPrimitives.WriteDoubleLittleEndian(recess.AsSpan(190), 1); + BinaryPrimitives.WriteDoubleLittleEndian(recess.AsSpan(222), -1); + BinaryPrimitives.WriteUInt32LittleEndian(recess.AsSpan(278), variation == 8 ? 0u : 2u); + BinaryPrimitives.WriteDoubleLittleEndian(recess.AsSpan(282), 0.375); + Add(1, other, WithGeometryRelations(Synthetic.Concat(FramedElementId(openingClass, 185, "R"), recess), + HostRelation(hostRole, slab), GeometryRelation(0x11, openingRole, secondCut))); + AddCut(secondCut, variation == 6 ? Guid.NewGuid() : other, slab); + } + if (multipleSlabs) + { + var second = OpeningSlab(0, -3, 0.25); + if (variation == 7) WriteRectangularPlan(second.AsSpan(191 + 270), 2, 2, 4, 4, slab: true); + Add(2, secondSlab, WithGeometryRelations(second, GeometryRelation(0x11, targetRole, secondCut))); + AddCut(secondCut, opening, secondSlab); + } + + var file = Synthetic.Fdb(ClassTable((1, openingClass), (2, SlabClass), (3, cutClass), (4, storyClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, records.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), Pool(pool)); + return (file, opening, slab, other, secondSlab); + } + + [Fact] + public void ReadsTheTopCenteredCircularOpeningWithoutInferringItsCutVolume() + { + var (file, opening, slab, _, _) = SlabOpeningFixture(0, slabAlignedFrame: true); + using var doc = PlaDocument.Open(new MemoryStream(file)); + var elements = doc.ReadElements(); + var geometry = Assert.IsType(Assert.Single(elements, e => e.Guid == opening).OpeningGeometry); + Assert.Equal(new PlaPlanPoint(0.25, -0.375), geometry.Origin); + Assert.Equal(new PlaOpeningCut(slab, -4.5, -3.5), Assert.Single(geometry.Cuts!)); + Assert.Null(geometry.CutVolume); + var solid = Assert.IsType(Assert.Single(elements, e => e.Guid == slab).SlabGeometry); + Assert.Null(solid.Volume); + Assert.Null(solid.VerticalPrisms); + } + + private static byte[] OpeningSettings(uint shape, double width, double height, bool linked = false) + { + var settings = new byte[363]; + new byte[] { 1, 3, 70, 0, 0, 0 }.CopyTo(settings, 230); + BinaryPrimitives.WriteUInt32LittleEndian(settings.AsSpan(236), shape); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(240), width); + BinaryPrimitives.WriteDoubleLittleEndian(settings.AsSpan(248), height); + new byte[] { 2, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0 }.CopyTo(settings, 256); + BinaryPrimitives.WriteUInt32LittleEndian(settings.AsSpan(298), linked ? 0u : 1u); + new byte[] { 0, 0, 2, 1, 59, 0, 0, 0, 1, 31, 0 }.CopyTo(settings, 304); + return settings; + } + + private static byte[] OpeningSlab(short story, double reference, double thickness, bool beveled = false) + { + byte[] slab = RectangularSlab(true); + const int edgesOffset = 191 + 270 + 247; + const int tailOffset = edgesOffset + 16 + 4 * 27; + Array.Resize(ref slab, tailOffset + 87); + WriteLocation(slab.AsSpan(163), 1, story); + slab[191 + 165] = 20; + BinaryPrimitives.WriteDoubleLittleEndian(slab.AsSpan(191), reference); + BinaryPrimitives.WriteDoubleLittleEndian(slab.AsSpan(191 + 17), thickness); + WriteSlabEdges(slab.AsSpan(edgesOffset), 4, beveled ? 1 : -1); + var tail = slab.AsSpan(tailOffset); + BinaryPrimitives.WriteUInt32LittleEndian(tail, 2); + BinaryPrimitives.WriteDoubleLittleEndian(tail[4..], Math.PI / 2); + new byte[] { 1, 0, 1, 0, 1, 0, 0, 0 }.CopyTo(tail[23..]); + BinaryPrimitives.WriteDoubleLittleEndian(tail[63..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(tail[71..], -0.125); + return slab; + } + + [Theory] + [InlineData(false, PlaBlockMode.Raw, true, true, true)] + [InlineData(true, PlaBlockMode.ZeroMask, true, true, true)] + [InlineData(false, PlaBlockMode.Lz, true, true, true)] + [InlineData(true, PlaBlockMode.Lz, false, true, true)] + [InlineData(false, PlaBlockMode.Raw, true, false, true)] + [InlineData(true, PlaBlockMode.Raw, true, true, false)] + public void ResolvesTheTopStoryThroughTheTypedPartitionDescriptor(bool column, PlaBlockMode mode, + bool matchingPartition, bool validDescriptor, bool validElementSection) + { + Guid elementClass = column ? new Guid("13e8eb85-5a33-47a3-a4d4-1e05296aec7e") : WallClass; + Guid topStoryRelation = column ? new Guid("5ebebc2d-cf0b-4751-8f55-7c2353c3fd14") : new Guid("7b48cc47-7267-4cfd-9133-9214ea18fb99"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid descriptorClass = new("bc046b25-27d6-461a-a6e5-6fa0e8594a95"); + Guid elementId = Guid.NewGuid(), partitionId = Guid.NewGuid(); + byte[] body = column ? FramedElementId(elementClass, 735, "WC") : WallWithPlanes(1, 0.25); + if (!column) + { + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(209 + 145), 5); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(209 + 153), 0); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(209 + 555), 1); + } + WriteLocation(body.AsSpan(column ? 701 : 163), 1, 0); + body = Synthetic.Concat(body, [(byte)(validElementSection ? 36 : 35), 0, 0, 0, 1, 0], + HostRelation(topStoryRelation, matchingPartition ? partitionId : Guid.NewGuid()), [0]); + + byte[] descriptor = new byte[49]; + Assert.True(descriptorClass.TryWriteBytes(descriptor)); + byte[] frame = [5, 0, 0x83, 0, 3, 0, 0, 0, 1, 0]; + frame.CopyTo(descriptor, 39); + byte[] tail = [0xFF, 0xFF, 1, 0, 0, (byte)(validDescriptor ? 36 : 35), 0, 0, 0, 1, 0]; + var relation = HostRelation(new Guid("baf95b80-f256-4932-b891-03ff66848591"), partitionId); + relation[0] = 0x11; + descriptor = Synthetic.Concat(descriptor, ElementId("Подвал")[14..], tail, relation, [0]); + var packed = mode switch + { + PlaBlockMode.Lz => Synthetic.QuickLzFrame(descriptor, descriptor.Length, 0x46), + PlaBlockMode.ZeroMask => Synthetic.ZeroMask(descriptor), + _ => descriptor, + }; + + byte[] pool = new byte[1024]; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: elementId, extra: 1, kind: 1).CopyTo(pool, 0); + using var doc = Open(ClassTable((1, elementClass), (2, storyClass), (3, descriptorClass)), + OwnedDirectory(false, Guid.Empty, 64, new ObjectDirectoryRecord(1, 0, 64, elementId)), Pool(pool), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 2), + Synthetic.Block(mode, packed, ver: 1, unpacked: (uint)descriptor.Length, kind: 3)); + var element = Assert.Single(doc.ReadElements()); + Assert.Equal(0, element.HomeStoryIndex); + Assert.Equal(matchingPartition && validDescriptor && validElementSection ? -1 : (int?)null, element.TopLinkedStoryIndex); + double? top = !column && matchingPartition && validDescriptor && validElementSection ? 1 : null; + Assert.Equal(top, element.TopElevationToHomeStory); + Assert.Equal(top, element.TopElevationToProjectZero); + } + + [Theory] + [InlineData(0, -1, 1.25, 0.0, 0.5, true)] + [InlineData(3, -1, 0.75, 0.5, 0.5, true)] + [InlineData(3, 2, 0.75, 0.5, 0.5, true)] + [InlineData(7, -1, 0.75, 0.5, 0.5, false)] + [InlineData(0, -1, 1.25, 0.0, -double.Epsilon, false)] + public void ReadsSlabPlanesInMetresInBothOrigins(byte plane, short story, double reference, double offset, + double thickness, bool supported) + { + byte[] slab = FramedElementId(SlabClass, 185, "SL-1"); + WriteLocation(slab.AsSpan(163), 1, story); + byte[] planes = new byte[25]; + BinaryPrimitives.WriteDoubleLittleEndian(planes, reference); + planes[8] = plane; + BinaryPrimitives.WriteDoubleLittleEndian(planes.AsSpan(9), offset); + BinaryPrimitives.WriteDoubleLittleEndian(planes.AsSpan(17), thickness); + + var element = ReadElementWithStory(SlabClass, Synthetic.Concat(slab, planes)); + + Assert.Equal("SL-1", element.ElementId); + Assert.Equal(supported ? 0.75 : null, element.BottomElevationToHomeStory); + Assert.Equal(supported ? 1.25 : null, element.TopElevationToHomeStory); + Assert.Equal(supported && story == -1 ? -3.25 : null, element.BottomElevationToProjectZero); + Assert.Equal(supported && story == -1 ? -2.75 : null, element.TopElevationToProjectZero); + } + + [Theory] + [InlineData(1, 2.5, 24, true)] + [InlineData(2, 2.5, 24, false)] + [InlineData(1, 2.5, 23, false)] + [InlineData(1, -2.5, 24, false)] + [InlineData(1, double.PositiveInfinity, 24, false)] + public void ReadsZoneBoundsAfterTheTwoCountedRoomStrings(byte roomNumberTag, double height, int length, bool supported) + { + Guid zoneClass = new("3ad0332e-efe2-491a-92a6-5b14bfdd7229"); + byte[] zone = FramedElementId(zoneClass, 253, "Холл"); + WriteLocation(zone.AsSpan(163), 1, -1); + byte[] levels = new byte[52 + 247]; + BinaryPrimitives.WriteDoubleLittleEndian(levels, -0.25); + BinaryPrimitives.WriteDoubleLittleEndian(levels.AsSpan(8), height); + BinaryPrimitives.WriteDoubleLittleEndian(levels.AsSpan(16), 0.125); + + WriteRectangularPlan(levels.AsSpan(52), 1, 2, 4, 6, slab: true); + levels[52] = 0; + levels[53] = 1; + var element = ReadElementWithStory(zoneClass, Synthetic.Concat(zone, [roomNumberTag, 0], ElementId("Б-01")[14..], + length == 24 ? levels : levels[..length])); + + Assert.Equal("Подвал", element.HomeStoryName); + Assert.Equal(supported ? -0.125 : null, element.BottomElevationToHomeStory); + Assert.Equal(supported ? 2.375 : null, element.TopElevationToHomeStory); + Assert.Equal(supported ? -4.125 : null, element.BottomElevationToProjectZero); + Assert.Equal(supported ? -1.625 : null, element.TopElevationToProjectZero); + Assert.Equal(supported ? new PlaBoundingBox(1, 2, -4.125, 4, 6, -1.625) : null, element.BoundingBox); + } + + [Theory] + [InlineData(false, false, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, true)] + [InlineData(false, true, true)] + public void ReadsSlabBoxesFromFramedOutlines(bool compact, bool curved, bool damaged) + { + byte[] slab = RectangularSlab(true); + var settings = slab.AsSpan(191); + settings[165] = 20; + if (compact) settings[270..].CopyTo(settings[166..]); + var polygon = settings[(compact ? 166 : 270)..]; + if (curved) + { + BinaryPrimitives.WriteUInt32LittleEndian(polygon[47..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[155..], 0); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[167..], damaged ? uint.MaxValue : 1); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[171..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[175..], Math.PI / 2); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[187..], 5); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[19..], -Math.Sqrt(2)); + } + else if (damaged) + BinaryPrimitives.WriteUInt32LittleEndian(polygon[155..], 6); + + var slabElement = ReadElementWithStory(SlabClass, slab); + Assert.Equal(damaged ? null : new PlaBoundingBox(-1, curved ? -Math.Sqrt(2) : -1, -4.5, 1, 1, -3.5), + slabElement.BoundingBox); + if (curved && !damaged) + { + var geometry = Assert.IsType(slabElement.SlabGeometry); + Assert.Equal(new PlaSlabArc(0, 0, Math.PI / 2), Assert.Single(geometry.Arcs!)); + Assert.Equal(3 + Math.PI / 2, geometry.OutlineArea, 12); + } + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void ReadsClosingSlabArcAndRejectsIntersectingEdges(bool clockwise, bool crossing) + { + var slab = RectangularSlab(true); + slab[191 + 165] = 20; + var polygon = slab.AsSpan(191 + 270); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[47..], 1); + polygon[151..191].Clear(); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[167..], 4); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[171..], 5); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[175..], crossing ? -1.5 * Math.PI : clockwise ? -Math.PI : Math.PI); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[187..], 5); + double span = Math.Sqrt(2); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[11..], crossing ? -1 : -2); + if (clockwise) + { + Span start = stackalloc byte[16]; + polygon.Slice(71, 16).CopyTo(start); + polygon.Slice(119, 16).CopyTo(polygon[71..]); + start.CopyTo(polygon[119..]); + polygon.Slice(103, 16).CopyTo(start); + polygon.Slice(87, 16).CopyTo(polygon[103..]); + start.CopyTo(polygon[87..]); + polygon.Slice(71, 16).CopyTo(polygon[135..]); + } + if (crossing) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[19..], -span); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[27..], span); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[35..], span); + } + var element = ReadElementWithStory(SlabClass, slab); + Assert.NotNull(element.BoundingBox); + if (crossing) + { + Assert.Null(element.SlabGeometry); + return; + } + var geometry = Assert.IsType(element.SlabGeometry); + Assert.Equal(new PlaSlabArc(0, 3, Math.PI), Assert.Single(geometry.Arcs!)); + Assert.Equal(4 + Math.PI / 2, geometry.OutlineArea, 12); + Assert.Equal(6 + Math.PI, geometry.FloorPlanPerimeter!.Value, 12); + Assert.Equal(0, geometry.FloorPlanHolesPerimeter); + Assert.Null(geometry.TopAreaWithOpenings); + Assert.Null(geometry.BottomAreaWithOpenings); + Assert.Null(geometry.Volume); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TestsSlabHoleContainmentAgainstTheArcRatherThanItsChord(bool inward) + { + var slab = RectangularSlab(true); + slab[191 + 165] = 20; + var polygon = slab.AsSpan(191 + 270); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[4..], 275); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[43..], 10); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[47..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[51..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[11..], inward ? -1 : -2); + double x = inward ? -0.5 : -1.5; + var hole = new PlaPlanPoint[] { new(-1, -0.25), new(-1, 0.25), new(x, 0.25), new(x, -0.25), new(-1, -0.25) }; + for (int i = 0; i < hole.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(151 + i * 16)..], hole[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(159 + i * 16)..], hole[i].Y); + } + BinaryPrimitives.WriteUInt32LittleEndian(polygon[247..], 4); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[251..], 5); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[255..], inward ? -Math.PI : Math.PI); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[267..], 5); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[271..], 10); + var element = ReadElementWithStory(SlabClass, slab); + Assert.NotNull(element.BoundingBox); + if (inward) + Assert.Null(element.SlabGeometry); + else + { + var geometry = Assert.IsType(element.SlabGeometry); + Assert.Equal(3.75 + Math.PI / 2, geometry.OutlineArea, 12); + Assert.Equal(8 + Math.PI, geometry.FloorPlanPerimeter!.Value, 12); + Assert.Equal(2, geometry.FloorPlanHolesPerimeter); + } + } + + [Theory] + [InlineData(0, true, true)] + [InlineData(1, true, false)] + [InlineData(2, true, false)] + [InlineData(3, false, false)] + [InlineData(4, false, false)] + public void ReadsConcaveSlabOutlinesAndVerifiesExtrusionsWithHoles(int variation, bool readsOutline, bool readsVolume) + { + (double X, double Y)[] outer = [(0, 0), (0, 4), (2, 4), (2, 2), (4, 2), (4, 0), (0, 0)]; + if (variation == 4) (outer[1], outer[2]) = (outer[2], outer[1]); + double h = variation == 3 ? 3 : 0.5; + (double X, double Y)[] hole = [(h, h), (h + 1, h), (h + 1, h + 1), (h, h + 1), (h, h)]; + var slab = SlabWithStraightRings(variation == 2 ? 1 : -1, outer, hole); + var element = ReadElementWithStory(SlabClass, WithGeometryRelations(slab, + variation == 1 ? GeometryRelation(0x11, Guid.NewGuid(), Guid.NewGuid()) : [])); + var geometry = element.SlabGeometry; + if (!readsOutline) + { + Assert.Null(geometry); + return; + } + + Assert.NotNull(geometry); + Assert.Equal([6, 4], geometry.Rings.Select(ring => ring.Count)); + Assert.Equal(new PlaPlanPoint(4, 0), geometry.Rings[0][0]); + Assert.Equal(new PlaPlanPoint(0.5, 1.5), geometry.Rings[1][0]); + Assert.Equal(-4.5, geometry.Bottom); + Assert.Equal(-3.5, geometry.Top); + Assert.Equal(11, geometry.OutlineArea); + Assert.Equal(20, geometry.FloorPlanPerimeter); + Assert.Equal(4, geometry.FloorPlanHolesPerimeter); + Assert.Equal(variation == 2 ? null : 11.0, geometry.TopAreaWithOpenings); + Assert.Equal(variation == 2 ? null : 11.0, geometry.BottomAreaWithOpenings); + Assert.Equal(readsVolume ? 11.0 : null, geometry.Volume); + Assert.Equal(readsVolume, geometry.VerticalPrisms is { Count: 1 }); + } + + private static void WriteSlabEdges(Span edges, int edgeCount, int beveledEdge) + { + new byte[] { 1, 0, 1, 0 }.CopyTo(edges[8..]); + BinaryPrimitives.WriteInt32LittleEndian(edges[12..], edgeCount); + for (int i = 0; i < edgeCount; i++) + { + var edge = edges[(16 + i * 27)..]; + BinaryPrimitives.WriteUInt32LittleEndian(edge[4..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(edge[8..], i == beveledEdge ? Math.PI / 4 : Math.PI / 2); + BinaryPrimitives.WriteUInt16LittleEndian(edge[16..], 3); + } + } + + [Theory] + [InlineData(900, false, false, 3.953125)] + [InlineData(1000, false, false, 3.953125)] + [InlineData(1100, false, false, 4.0)] + [InlineData(900, true, false, null)] + [InlineData(900, false, true, 3.96875)] + public void ComputesSlabVolumeFromTheIntersectionWithARotatedColumn(int slabPriority, bool wrongTarget, bool composite, + double? volume) + { + var (file, slab) = SlabColumnSceneFixture(slabPriority, wrongTarget, composite); + using var doc = PlaDocument.Open(new MemoryStream(file)); + var geometry = Assert.IsType(Assert.Single(doc.ReadElements(), e => e.Guid == slab).SlabGeometry); + Assert.Equal(volume, geometry.Volume); + Assert.Equal(4, geometry.TopAreaWithOpenings); + Assert.Equal(4, geometry.BottomAreaWithOpenings); + Assert.Equal(volume == 4, geometry.VerticalPrisms is { Count: 1 }); + } + + internal enum SlabColumnContact { PartialEdge, PartialInterior, Interior, Edge, Split, TrimOuterEdge } + + [Theory] + [InlineData(5, 5, true)] + [InlineData(5, 6, true)] + [InlineData(1, 1, true)] + [InlineData(5, 1, false)] + [InlineData(5, 0, false)] + public void ResolvesColumnSolidWhenCompositeWallCannotWrap(byte outer, byte middle, bool hasSolid) + { + var (file, _) = SlabColumnSceneFixture(wallSkinFunctions: [outer, middle, outer]); + using var doc = PlaDocument.Open(new MemoryStream(file)); + var column = Assert.Single(doc.ReadElements(), e => e.Type == "Column"); + Assert.Equal(-0.25, column.BottomElevationToHomeStory); + Assert.Equal(1, column.TopElevationToHomeStory); + Assert.Equal(-4.25, column.BottomElevationToProjectZero); + Assert.Equal(-3, column.TopElevationToProjectZero); + if (hasSolid) + { + var solid = Assert.IsType(column.ColumnExtrusion); + Assert.Equal(0.15625, solid.Volume, 12); + Assert.Equal(-4.25, solid.BoundingBox.ZMin); + Assert.Equal(-3, solid.BoundingBox.ZMax); + } + else + { + Assert.Null(column.ColumnExtrusion); + } + } + + [Theory] + [InlineData(true, true, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(true, false, true)] + [InlineData(true, true, true)] + [InlineData(false, false, true)] + public void PreservesColumnGeometryWithReciprocalAnnotation(bool reciprocal, bool circular, bool angularDimension) + { + var (file, _) = SlabColumnSceneFixture(validCircularSection: circular ? true : null, validColumnAnnotation: reciprocal, + angularDimension: angularDimension); + using var doc = PlaDocument.Open(new MemoryStream(file)); + var element = Assert.Single(doc.ReadElements(), e => e.Type == "Column"); + if (!reciprocal) + { + Assert.Null(element.ColumnExtrusion); + Assert.Null(element.BottomElevationToProjectZero); + Assert.Null(element.TopElevationToHomeStory); + return; + } + var solid = Assert.IsType(element.ColumnExtrusion); + Assert.Equal(circular ? Math.PI * 0.25 * 0.25 * 1.25 : 0.15625, solid.Volume, 12); + Assert.Equal((-4.25, -3.0, -0.25, 1.0), (element.BottomElevationToProjectZero, + element.TopElevationToProjectZero, element.BottomElevationToHomeStory, element.TopElevationToHomeStory)); + } + + internal static (byte[] File, Guid Element) SlabColumnSceneFixture(int slabPriority = 900, bool wrongTarget = false, + bool composite = false, SlabColumnContact contact = SlabColumnContact.PartialEdge, bool slopeUpperCap = false, + bool? validCircularSection = null, double circularRadius = 0.25, byte[]? wallSkinFunctions = null, + bool? validColumnAnnotation = null, bool angularDimension = false) + { + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"); + Guid memoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid sectionClass = new(validCircularSection.HasValue ? "d6c12939-d905-40e0-aa57-f7c8d687dc7b" : "c4191955-87c6-4fb6-b074-5f094fe9f6a6"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid jointClass = new("d5381783-6a19-4de8-9e52-2e04a3978db0"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid compositeClass = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid memoRelation = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"); + Guid sectionRelation = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid slabRelation = new("f6ee0d9c-27ad-44d0-824f-682969bb171e"); + Guid columnRelation = new("87811dc4-1686-45f4-b1a6-dfaa81da44e4"); + Guid wallJointClass = new("a9e0daf5-0932-4054-b976-d8f207bb865a"); + Guid wallRelation = new("199f13d8-5fa0-4894-8adf-761a1442a7f7"); + Guid columnWallRelation = new("27c70d06-a928-499c-a005-5307c9f10da0"); + Guid annotationClass = new(angularDimension ? "2120198c-d317-4cea-ab4e-c7b6ceb5156e" : "1601b50c-a61f-447c-8b74-0f578c003d88"); + Guid annotationRelation = new(angularDimension ? "1ff9df7b-3f2d-4f16-855a-b863af9ca26d" : "f73ad2dc-973b-4e70-9787-a3c6fee4a2bf"); + Guid slab = Guid.NewGuid(), column = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), joint = Guid.NewGuid(); + Guid wall = Guid.NewGuid(), wallJoint = Guid.NewGuid(); + Guid annotation = Guid.NewGuid(); + + var columnBody = Synthetic.Concat(FramedElementId(columnClass, 735, "C"), new byte[95]); + var data = columnBody.AsSpan(); + ElementId("C").CopyTo(data[721..]); + WriteLocation(data[701..], 1, -1); + new byte[] { 1, 0, 2, 0, 0, 0, 1, 0 }.CopyTo(data[304..]); + BinaryPrimitives.WriteUInt16LittleEndian(data[368..], 1); + double x = contact is SlabColumnContact.PartialEdge or SlabColumnContact.Edge or SlabColumnContact.TrimOuterEdge ? 1 : 0; + bool through = contact is not (SlabColumnContact.PartialEdge or SlabColumnContact.PartialInterior); + (double halfWidth, double halfHeight, double angle) = contact switch + { + SlabColumnContact.Split => (1, 0.125, 0), + SlabColumnContact.TrimOuterEdge => (0.125, 1.25, 0), + _ => (0.25, 0.125, Math.PI / 4), + }; + BinaryPrimitives.WriteDoubleLittleEndian(data[312..], x); + BinaryPrimitives.WriteDoubleLittleEndian(data[328..], through ? -1 : -0.25); + BinaryPrimitives.WriteDoubleLittleEndian(data[352..], -1); + BinaryPrimitives.WriteDoubleLittleEndian(data[370..], x); + BinaryPrimitives.WriteDoubleLittleEndian(data[386..], 1); + if (slopeUpperCap) BinaryPrimitives.WriteDoubleLittleEndian(data[402..], 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(data[410..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(data[(741 + 87)..], angle); + + int slots = wallSkinFunctions is null ? 5 : 7; + byte[] pool = new byte[(slots + (angularDimension && validColumnAnnotation.HasValue ? 1 : 0)) * 1024]; + var entries = new List(); + void Add(ushort kind, Guid id, byte[] bytes) + { + int offset = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, bytes, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, offset * 1024); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)offset * 64, 64, id)); + } + var slabBody = OpeningSlab(-1, 0.5, 1); + if (composite) + { + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 83), 2); + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 87), 1); + } + Add(1, slab, WithGeometryRelations(slabBody, GeometryRelation(0x11, slabRelation, joint))); + byte[] annotationLink = !validColumnAnnotation.HasValue ? [] : angularDimension + ? GeometryRelationList(1, annotationRelation, annotation) : GeometryRelation(0x11, annotationRelation, annotation); + Add(2, column, WithGeometryRelations(columnBody, GeometryRelation(0x11, memoRelation, memo), annotationLink)); + var memoRelations = new List { HostRelation(memoRelation, column), GeometryRelation(0x11, sectionRelation, section), + GeometryRelation(0x11, columnRelation, joint) }; + if (wallSkinFunctions is not null) memoRelations.Add(GeometryRelation(0x11, columnWallRelation, wallJoint)); + Add(3, memo, WithGeometryRelations(memoClass.ToByteArray(), memoRelations.ToArray())); + var sectionBody = validCircularSection is { } valid + ? CircularColumnSection(sectionClass, circularRadius, valid) + : RectangularSection(sectionClass, 1, halfWidth, -halfHeight, halfHeight); + Add(4, section, WithGeometryRelations(sectionBody, HostRelation(sectionRelation, memo))); + Add(5, joint, WithGeometryRelations(jointClass.ToByteArray(), HostRelation(columnRelation, memo), + HostRelation(slabRelation, wrongTarget ? Guid.NewGuid() : slab))); + if (wallSkinFunctions is not null) + { + var wallBody = WallWithPlanes(2, -4.25); + BinaryPrimitives.WriteUInt16LittleEndian(wallBody.AsSpan(209 + 225), 2); + BinaryPrimitives.WriteUInt16LittleEndian(wallBody.AsSpan(209 + 229), 1); + Add(10, wall, WithGeometryRelations(wallBody, GeometryRelation(0x11, wallRelation, wallJoint))); + Add(11, wallJoint, WithGeometryRelations(wallJointClass.ToByteArray(), + HostRelation(columnWallRelation, memo), HostRelation(wallRelation, wall))); + } + + byte[] labelDirectory = [], labelPool = []; + if (validColumnAnnotation is { } reciprocal) + { + var body = WithGeometryRelations(annotationClass.ToByteArray(), HostRelation(annotationRelation, reciprocal ? column : Guid.NewGuid())); + if (angularDimension) Add(12, annotation, body); + else + { + byte[] labelData = new byte[1024]; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: annotation, extra: 1, kind: 12).CopyTo(labelData, 0); + labelDirectory = OwnedDirectory(false, Guid.Empty, 64, new ObjectDirectoryRecord(12, 0, 64, annotation)); + labelPool = Pool(labelData); + } + } + + var file = Synthetic.Fdb(ClassTable((1, SlabClass), (2, columnClass), (3, memoClass), (4, sectionClass), + (5, jointClass), (6, storyClass), (7, materialClass), (8, layerClass), (9, compositeClass), + (10, WallClass), (11, wallJointClass), (12, annotationClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), labelDirectory, + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 6), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, (uint)slabPriority), + JunctionAttribute(materialClass, 7, 3, wallSkinFunctions is null ? 1100U : 950U), + JunctionAttribute(layerClass, 8, 1, 1), + CompositeForWallTest(compositeClass, splitCuts: false, kind: 9, skinFunctions: wallSkinFunctions), Pool(pool), labelPool); + + return (file, slab); + } + + private static byte[] CircularColumnSection(Guid sectionClass, double radius, bool valid) + { + const int frame = 141, vector = 149, hatchOffset = 482, hatchLength = 175; + var section = new byte[vector + hatchOffset + hatchLength]; + sectionClass.TryWriteBytes(section); + BinaryPrimitives.WriteDoubleLittleEndian(section.AsSpan(91), 2 * radius); + BinaryPrimitives.WriteDoubleLittleEndian(section.AsSpan(99), 2 * radius); + new byte[] { 2, 0, 9, 1 }.CopyTo(section, frame); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(frame + 4), hatchOffset + hatchLength); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(vector), 128); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(vector + 69), 1); + var hatch = section.AsSpan(vector + hatchOffset); + hatch[0] = 3; + hatch[1] = 1; + BinaryPrimitives.WriteUInt32LittleEndian(hatch[2..], hatchLength - 6); + BinaryPrimitives.WriteUInt16LittleEndian(hatch[8..], 2); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[18..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[55..], 4); + BinaryPrimitives.WriteDoubleLittleEndian(hatch[75..], -radius); + BinaryPrimitives.WriteDoubleLittleEndian(hatch[91..], radius); + BinaryPrimitives.WriteDoubleLittleEndian(hatch[107..], -radius); + var arcs = hatch[123..]; + BinaryPrimitives.WriteUInt16LittleEndian(arcs, 1); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[2..], 2); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[6..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[10..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(arcs[14..], Math.PI); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[22..], 2); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[26..], 3); + BinaryPrimitives.WriteDoubleLittleEndian(arcs[30..], valid ? Math.PI : -Math.PI); + BinaryPrimitives.WriteUInt16LittleEndian(arcs[38..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[40..], 2); + BinaryPrimitives.WriteUInt32LittleEndian(arcs[48..], 3); + return section; + } + + [Theory] + [InlineData(1100, false, 4.0)] + [InlineData(900, false, null)] + [InlineData(1100, true, null)] + public void ChecksPriorityAndOwnershipForTheAlternateSlabWallRelation(int slabPriority, bool wrongTarget, double? volume) + { + Guid contactClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid slabRole = new("29bce22c-b910-400a-b84a-0b85fb92610e"); + Guid wallRole = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slab = Guid.NewGuid(), wall = Guid.NewGuid(), contact = Guid.NewGuid(); + byte[] pool = new byte[3 * 1024]; + var slabBody = WithGeometryRelations(OpeningSlab(-1, 0.5, 1), GeometryRelation(0x11, slabRole, contact)); + var wallBody = WithGeometryRelations(WallWithPlanes(1, -3.75), GeometryRelation(0x11, wallRole, contact)); + var jointBody = WithGeometryRelations(contactClass.ToByteArray(), + HostRelation(slabRole, wrongTarget ? Guid.NewGuid() : slab), HostRelation(wallRole, wall)); + Synthetic.Block(PlaBlockMode.Raw, slabBody, ver: 1, guid: slab, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, wallBody, ver: 1, guid: wall, extra: 1, kind: 2).CopyTo(pool, 1024); + Synthetic.Block(PlaBlockMode.Raw, jointBody, ver: 1, guid: contact, extra: 1, kind: 3).CopyTo(pool, 2048); + using var doc = Open(ClassTable((1, SlabClass), (2, WallClass), (3, contactClass), (4, storyClass), (7, materialClass)), + OwnedDirectory(false, Guid.Empty, 192, new(1, 0, 64, slab), new(2, 64, 64, wall), new(3, 128, 64, contact)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, (uint)slabPriority), Pool(pool)); + var geometry = Assert.IsType(Assert.Single(doc.ReadElements(), e => e.Guid == slab).SlabGeometry); + Assert.Equal(volume, geometry.Volume); + } + + [Theory] + [InlineData("valid")] + [InlineData("unknown role")] + [InlineData("wrong owner")] + [InlineData("arc crosses rings")] + [InlineData("open ring")] + [InlineData("hole outside")] + public void ReadsSavedWallProfileComponents(string variation) + { + Guid profileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"); + Guid relation = new("e63e7632-0efd-412d-8077-d3f3906b638a"); + Guid wall = Guid.NewGuid(), profile = Guid.NewGuid(); + var wallBody = WallWithPlanes(1, -4.5); + BinaryPrimitives.WriteUInt16LittleEndian(wallBody.AsSpan(209 + 225), 3); + + double holeX = variation == "hole outside" ? 5 : 1; + PlaProfilePoint[] exterior = [new(0, 0), new(4, 0), new(4, 4), new(0, 4), new(0, 0)]; + PlaProfilePoint[] hole = [new(holeX, 1), new(holeX + 1, 1), new(holeX + 1, 2), new(holeX, 2), new(holeX, 1)]; + if (variation == "open ring") exterior[^1] = new(0, 1); + var core = SavedProfileHatch(14, variation == "unknown role" ? (byte)7 : (byte)1, + variation == "arc crosses rings" ? 6 : 5, exterior, hole); + PlaProfilePoint[] otherRing = [new(5, 0), new(6, 0), new(6, 1), new(5, 1), new(5, 0)]; + var other = SavedProfileHatch(6, 0, 0, otherRing); + byte[] profileBody = SavedWallProfileRecord(profileClass, core, other); + + const int extent = 2048; + var pool = new byte[2 * extent]; + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(wallBody, GeometryRelation(0x11, relation, profile)), + ver: 1, guid: wall, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, + WithGeometryRelations(profileBody, HostRelation(relation, variation == "wrong owner" ? Guid.NewGuid() : wall)), + ver: 1, guid: profile, extra: 1, kind: 2).CopyTo(pool, extent); + using var doc = Open(ClassTable((1, WallClass), (2, profileClass)), + OwnedDirectory(false, Guid.Empty, 256, new ObjectDirectoryRecord(1, 0, 128, wall), + new ObjectDirectoryRecord(2, 128, 128, profile)), Pool(pool)); + var profileResult = Assert.Single(doc.ReadElements()).WallProfile; + if (variation is not ("valid" or "unknown role")) + { + Assert.Null(profileResult); + return; + } + + var decoded = Assert.IsType(profileResult); + Assert.Equal(9, decoded.ProfileIndex); + Assert.Collection(decoded.Components, part => + { + Assert.Equal(14, part.BuildingMaterialIndex); + Assert.Equal(variation == "valid" ? "Core" : null, part.Function); + Assert.Equal(15 + 2 * Math.PI, part.CrossSectionArea, 12); + Assert.Collection(part.Rings, + ring => Assert.Equal(exterior[..^1], ring), + ring => Assert.Equal(hole[..^1], ring)); + Assert.Equal(new PlaProfileArc(0, 3, Math.PI), Assert.Single(part.Arcs!)); + }, part => + { + Assert.Equal(6, part.BuildingMaterialIndex); + Assert.Equal("Other", part.Function); + Assert.Equal(1, part.CrossSectionArea); + Assert.Single(part.Rings); + Assert.Null(part.Arcs); + }); + + } + + private static byte[] SavedWallProfileRecord(Guid profileClass, params byte[][] hatches) + { + int size = 128 + hatches.Sum(h => h.Length) + (hatches.Length - 1) * 16; + var profile = new byte[402 + size]; + profileClass.TryWriteBytes(profile); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(49), 1); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(51), 9); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(55), 2); + new byte[] { 2, 0, 9, 1 }.CopyTo(profile, 394); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(398), size); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(402), 128); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(402 + 69), hatches.Length); + int offset = 402 + 128; + foreach (var hatch in hatches) + { + hatch.CopyTo(profile, offset); + offset += hatch.Length + 16; + } + return profile; + } + + [Theory] + [InlineData(false, true)] + [InlineData(true, true)] + [InlineData(false, false)] + public void ReadsProfiledWallBoxFromAnInlineSlice(bool reflected, bool verifiedSlice) + { + var (file, _) = ProfiledWallSceneFixture(overlapping: false, reflected, verifiedSlice); + using var document = PlaDocument.Open(new MemoryStream(file)); + var wall = Assert.Single(document.ReadElements()); + Assert.Equal(verifiedSlice ? new PlaBoundingBox(-1, reflected ? 0 : -5, -6.75, + 1, reflected ? 5 : 0, -3.75) : null, wall.BoundingBox); + Assert.Null(wall.BottomElevationToProjectZero); + } + + internal static (byte[] File, Guid Wall) ProfiledWallSceneFixture(bool overlapping, bool reflected = false, bool? verifiedSlice = null) + { + Guid profileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"); + Guid relation = new("e63e7632-0efd-412d-8077-d3f3906b638a"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid wall = Guid.NewGuid(), profile = Guid.NewGuid(); + var body = WallWithPlanes(1, -3.75); + var settings = body.AsSpan(209); + BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 3); + BinaryPrimitives.WriteDoubleLittleEndian(settings, -1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], 1); + new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(settings[489..]); + double[] box = [-1, -5, 1, 0, -3.75, -0.75]; + if (verifiedSlice is { } verified) + { + settings[515..563].Clear(); + BinaryPrimitives.WriteDoubleLittleEndian(settings[77..], 5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[85..], 5); + double edgeMin = reflected ? 4 : -5; + double edgeMax = reflected ? 5 : -4; + WriteRectangularPlan(settings[256..], -1, edgeMin, verified ? 1 : 0.5, edgeMax, slab: false); + } + else + for (int i = 0; i < box.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(settings[(515 + i * 8)..], box[i]); + double z = verifiedSlice.HasValue ? -3 : 0; + var core = SavedProfileHatch(14, 1, 0, + [new(0, z), new(4, z), new(4, z + 3), new(0, z + 3), new(0, z)], + [new(1, z + 1), new(2, z + 1), new(2, z + 2), new(1, z + 2), new(1, z + 1)]); + double edge = overlapping ? 3.5 : 4; + PlaProfilePoint[] jacketRing = [new(edge, z + 1), new(5, z + 1), new(5, z + 2), new(edge, z + 2), new(edge, z + 1)]; + var jacket = SavedProfileHatch(6, 0, 0, jacketRing); + const int extent = 2048; + var pool = new byte[2 * extent]; + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(body, GeometryRelation(0x11, relation, profile)), + ver: 1, guid: wall, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(SavedWallProfileRecord(profileClass, core, jacket), HostRelation(relation, wall)), + ver: 1, guid: profile, extra: 1, kind: 2).CopyTo(pool, extent); + return (Synthetic.Fdb(ClassTable((1, WallClass), (2, profileClass), (3, storyClass)), + OwnedDirectory(false, Guid.Empty, 256, new ObjectDirectoryRecord(1, 0, 128, wall), + new ObjectDirectoryRecord(2, 128, 128, profile)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 3), Pool(pool)), wall); + } + + private static byte[] SavedProfileHatch(int material, byte role, int arcEnd, params PlaProfilePoint[][] rings) + { + int points = 1 + rings.Sum(ring => ring.Length); + int arcs = 59 + points * 16; + int ends = arcs + 6 + (arcEnd == 0 ? 0 : 16); + int footer = ends + 6 + (rings.Length + 1) * 4; + var buffer = new byte[footer + 109]; + buffer[0] = 3; + buffer[1] = 1; + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(2), buffer.Length - 6); + BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(8), 2); + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(18), material); + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(55), points); + BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(arcs), 1); + if (arcEnd != 0) + { + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(arcs + 2), 1); + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(arcs + 6), arcEnd - 1); + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(arcs + 10), arcEnd); + BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(arcs + 14), Math.PI); + } + BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(ends), 1); + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(ends + 2), rings.Length + 1); + int vertex = 1; + for (int i = 0; i < rings.Length; i++) + { + foreach (var point in rings[i]) + { + int offset = 59 + vertex * 16; + BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(offset), point.U); + BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(offset + 8), point.Z); + vertex++; + } + BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(ends + 10 + i * 4), vertex - 1); + } + buffer[footer + 108] = role; + return buffer; + } + + [Theory] + [InlineData(0.65, true, true, null)] + [InlineData(0.59, true, false, null)] + [InlineData(0.65, false, false, null)] + [InlineData(0.65, true, true, -0.5)] + [InlineData(0.65, true, false, 0.4)] + [InlineData(0.65, false, false, -0.5)] + public void ChecksJoinedBeamCapAgainstTheRotatedColumnOutline(double centerX, bool reciprocal, bool hasSolid, double? collisionX) + { + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"), memoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"), storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid jointClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"), columnJointClass = new("f7f60005-35d0-4346-87ab-29e087ac0bbf"); + Guid memoKey = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid beamKey = new("6346a816-1d7c-4e46-9609-67624e99d0fb"), endKey = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid peerKey = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"); + if (collisionX.HasValue) + { + endKey = new("89d11bdb-3a78-48ad-96e7-5b69836c591d"); + peerKey = new("1d381463-2edc-4aad-91b0-027291e8da94"); + } + Guid column = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), contact = Guid.NewGuid(), join = Guid.NewGuid(); + byte[] pool = new byte[14 * 1024]; + var records = new List(); + void Add(ushort kind, Guid id, byte[] bytes, int slot) + { + Synthetic.Block(PlaBlockMode.Raw, bytes, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * 1024); + records.Add(new ObjectDirectoryRecord(kind, (ulong)slot * 64, 64, id)); + } + + var body = Synthetic.Concat(FramedElementId(columnClass, 735, "C"), new byte[95]); + ElementId("C").CopyTo(body.AsSpan(721)); + new byte[] { 1, 0, 2, 0, 0, 0, 1, 0 }.CopyTo(body, 304); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(368), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(312), centerX); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(320), 0.34); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(370), centerX); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(378), 0.34); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(386), 4); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(410), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(741 + 87), Math.PI / 4); + WriteLocation(body.AsSpan(701), 1, -1); + Add(1, column, WithGeometryRelations(body, GeometryRelation(0x11, memoKey, memo)), 0); + Add(2, memo, WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, column), + GeometryRelation(0x11, sectionKey, section), GeometryRelation(0x11, beamKey, contact)), 1); + Add(3, section, WithGeometryRelations(RectangularSection(sectionClass, 1, 0.25, -0.25, 0.25), + HostRelation(sectionKey, memo)), 2); + + Guid branch = AddBeamCutFixture(pool, records, memo, contact, 3 * 1024, 0, 2.5, 0.1, 0, + GeometryRelation(0x11, endKey, join), endX: 0.4); + Guid peer = AddBeamCutFixture(pool, records, Guid.Empty, Guid.Empty, 8 * 1024, collisionX ?? 0.4, 2.5, 0.1, 0, + reciprocal ? GeometryRelation(0x11, peerKey, join) : [], transverse: true, startY: collisionX.HasValue ? -2 : 0); + var joint = new byte[67]; + jointClass.TryWriteBytes(joint); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(joint, 35); + if (!collisionX.HasValue) + { + BinaryPrimitives.WriteDoubleLittleEndian(joint.AsSpan(50), 0.4); + joint[66] = 1; + } + Add(12, join, WithGeometryRelations(joint, HostRelation(endKey, branch), HostRelation(peerKey, peer)), 13); + + using var doc = Open(ClassTable((1, columnClass), (2, memoClass), (3, sectionClass), (6, storyClass), (7, materialClass), + (8, layerClass), (9, new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")), (10, new("cbab7bc6-e03a-4133-9161-c28ed3368672")), + (11, columnJointClass), (12, jointClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, records.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 6), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, 1200), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var element = Assert.Single(doc.ReadElements(), e => e.Guid == column); + Assert.Equal(0, element.BottomElevationToHomeStory); + Assert.Equal(4, element.TopElevationToHomeStory); + Assert.Equal(-4, element.BottomElevationToProjectZero); + Assert.Equal(0, element.TopElevationToProjectZero); + Assert.Equal(hasSolid ? 1.0 : (double?)null, element.ColumnExtrusion?.Volume); + } + + [Theory] + [InlineData(0.75, 0.125, true, 0.375)] + [InlineData(0, 0.125, true, 0.4375)] + [InlineData(0, 0.25, true, null)] + [InlineData(0, 0.125, false, null)] + public void ReadsRectangularColumnCutByCoextensiveBeams(double end, double profileHalfWidth, bool reciprocal, double? volume) + { + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"), columnMemoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid beamClass = new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca"), beamMemoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"), complexClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"); + Guid shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"), columnContactClass = new("f7f60005-35d0-4346-87ab-29e087ac0bbf"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"), jointClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid columnMemoKey = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"), beamMemoKey = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"), shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"); + Guid columnContactKey = new("6346a816-1d7c-4e46-9609-67624e99d0fb"), beamContactKey = new("cd0b0837-0b34-4e96-8d66-9fe7d926478c"); + Guid endKey = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"), peerKey = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"); + Guid column = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), shape = Guid.NewGuid(); + Guid startJoint = Guid.NewGuid(), endJoint = Guid.NewGuid(), mainContact = Guid.NewGuid(), profileContact = Guid.NewGuid(); + byte[] pool = new byte[14 * 2048]; + var entries = new List(); + void Add(ushort kind, Guid id, byte[] body) + { + int slot = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * 2048); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)slot * 128, 128, id)); + } + + var body = Synthetic.Concat(FramedElementId(columnClass, 735, "C"), new byte[95]); + ElementId("C").CopyTo(body.AsSpan(721)); + new byte[] { 1, 0, 2, 0, 0, 0, 1, 0 }.CopyTo(body, 304); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(368), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(320), 0.125); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(378), 0.125); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(386), 2); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(410), 1); + WriteLocation(body.AsSpan(701), 1, -1); + Add(1, column, WithGeometryRelations(body, GeometryRelation(0x11, columnMemoKey, memo))); + Add(2, memo, WithGeometryRelations(columnMemoClass.ToByteArray(), HostRelation(columnMemoKey, column), + GeometryRelation(0x11, sectionKey, section), GeometryRelationList(1, columnContactKey, mainContact, profileContact))); + Add(3, section, WithGeometryRelations(RectangularSection(sectionClass, 1, 0.25, -0.25, 0.25), HostRelation(sectionKey, memo))); + + Guid main = AddBeam(false, mainContact, endKey), weaker = AddBeam(true, profileContact, peerKey); + AddJoin(startJoint, -1, weaker); + AddJoin(endJoint, end, reciprocal ? weaker : Guid.NewGuid()); + + using var doc = Open(ClassTable((1, columnClass), (2, columnMemoClass), (3, sectionClass), (4, complexClass), (5, shapeClass), + (6, storyClass), (7, materialClass), (8, layerClass), (9, beamClass), (10, beamMemoClass), (11, columnContactClass), (12, jointClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 6), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, 1200), + JunctionAttribute(materialClass, 7, 3, 1100), JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var element = Assert.Single(doc.ReadElements(), e => e.Guid == column); + if (volume is null) + { + Assert.Null(element.ColumnCutMesh); + return; + } + var mesh = Assert.IsType(element.ColumnCutMesh); + Assert.Equal(volume.Value, mesh.Volume, 12); + Assert.Equal(new PlaBoundingBox(-0.25, -0.125, -4, 0.25, 0.375, -2), element.BoundingBox); + Assert.Equal(0, element.BottomElevationToHomeStory); + Assert.Equal(2, element.TopElevationToHomeStory); + Assert.Equal(-4, element.BottomElevationToProjectZero); + Assert.Equal(-2, element.TopElevationToProjectZero); + + Guid AddBeam(bool profiled, Guid contact, Guid jointRole) + { + Guid owner = Guid.NewGuid(), beamMemo = Guid.NewGuid(), beamSection = Guid.NewGuid(); + Add(9, owner, WithGeometryRelations(HorizontalBeam(beamClass, -1, 0, end, 0, 1, 0, 1), + GeometryRelation(0x11, beamMemoKey, beamMemo))); + Add(10, beamMemo, WithGeometryRelations(beamMemoClass.ToByteArray(), HostRelation(beamMemoKey, owner), + GeometryRelation(0x11, sectionKey, beamSection), GeometryRelation(0x11, beamContactKey, contact), + GeometryRelationList(1, jointRole, startJoint, endJoint))); + Add(11, contact, WithGeometryRelations(columnContactClass.ToByteArray(), HostRelation(beamContactKey, beamMemo), + HostRelation(columnContactKey, memo))); + if (profiled) + { + Add(4, beamSection, WithGeometryRelations(complexClass.ToByteArray(), HostRelation(sectionKey, beamMemo), + GeometryRelation(0x11, shapeKey, shape))); + double w = profileHalfWidth; + PlaProfilePoint[] ring = [new(-w, -1), new(w, -1), new(w, -0.5), new(0, -0.5), new(0, 0), new(-w, 0), new(-w, -1)]; + Add(5, shape, WithGeometryRelations(SavedMemberProfileShape(shapeClass, 1, SavedProfileHatch(3, 1, 0, ring)), + HostRelation(shapeKey, beamSection))); + } + else + Add(3, beamSection, WithGeometryRelations(RectangularSection(sectionClass, 2, 0.125, -1, 0), HostRelation(sectionKey, beamMemo))); + return beamMemo; + } + + void AddJoin(Guid id, double x, Guid other) + { + var join = new byte[67]; + jointClass.TryWriteBytes(join); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(join, 35); + BinaryPrimitives.WriteDoubleLittleEndian(join.AsSpan(50), x); + join[66] = 1; + Add(12, id, WithGeometryRelations(join, HostRelation(endKey, main), HostRelation(peerKey, other))); + } + } + + internal enum ColumnBeamEnd + { + Butt, EqualTee, WeakerTee, RepeatedWeakerTee, DifferentHeightTee, TrimmedThroughTee, AngledTee, + AngledTeeNearCap, AngledWeakerTee, + MiterAway, MiterAtFace, WeakerOverlap, EqualOverlap, SeparateEqualOverlap, + EqualMiter, EqualMiterWithWeakPeer, EqualMiterWithDifferentWeakPeer, + } + + internal static byte[] ColumnBeamBandsFixture(bool partialCut, bool otherColumn, bool wrongOtherOwner, bool oblique = false, + bool? validWallLabel = null, bool concaveProfile = false, bool skewedBeam = false, bool clearBeams = false, + ColumnBeamEnd beamEnd = ColumnBeamEnd.Butt) + { + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"), columnMemoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid sectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"), shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"), materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"), beamJoinClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid memoKey = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"), beamKey = new("6346a816-1d7c-4e46-9609-67624e99d0fb"); + Guid firstEnd = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"), secondEnd = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid throughRole = new("89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid secondCollision = new("1d381463-2edc-4aad-91b0-027291e8da94"); + Guid column = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), shape = Guid.NewGuid(); + Guid lowerContact = Guid.NewGuid(), middleContact = Guid.NewGuid(), beamJoin = Guid.NewGuid(); + Guid throughContact = Guid.NewGuid(), repeatedJoin = Guid.NewGuid(), throughTrim = Guid.NewGuid(); + bool trimmed = beamEnd == ColumnBeamEnd.TrimmedThroughTee; + bool nearCap = beamEnd == ColumnBeamEnd.AngledTeeNearCap; + bool angledTee = beamEnd is ColumnBeamEnd.AngledTee or ColumnBeamEnd.AngledWeakerTee || nearCap; + bool weakMiterPeer = beamEnd is ColumnBeamEnd.EqualMiterWithWeakPeer or ColumnBeamEnd.EqualMiterWithDifferentWeakPeer; + bool activeMiter = beamEnd == ColumnBeamEnd.EqualMiter || weakMiterPeer; + bool miter = beamEnd is ColumnBeamEnd.MiterAway or ColumnBeamEnd.MiterAtFace || activeMiter; + bool overlap = beamEnd is ColumnBeamEnd.WeakerOverlap or ColumnBeamEnd.EqualOverlap or ColumnBeamEnd.SeparateEqualOverlap; + bool tee = beamEnd != ColumnBeamEnd.Butt && !miter && !overlap; + bool equal = beamEnd is ColumnBeamEnd.EqualTee or ColumnBeamEnd.AngledTee || trimmed || nearCap || activeMiter; + bool repeated = beamEnd == ColumnBeamEnd.RepeatedWeakerTee; + Guid wallColumn = new("199f13d8-5fa0-4894-8adf-761a1442a7f7"), columnWall = new("27c70d06-a928-499c-a005-5307c9f10da0"); + Guid wallProfileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"), wallColumnClass = new("a9e0daf5-0932-4054-b976-d8f207bb865a"); + Guid labelClass = new("1601b50c-a61f-447c-8b74-0f578c003d88"), wallContact = Guid.NewGuid(); + var body = Synthetic.Concat(FramedElementId(columnClass, 735, "C"), new byte[95]); + ElementId("C").CopyTo(body.AsSpan(721)); + body[741] = 1; + new byte[] { 1, 0, 2, 0, 0, 0, 1, 0 }.CopyTo(body, 304); + if (nearCap) BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(328), 1.5 - 1e-12); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -1); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(368), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(386), 4); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(410), 1); + WriteLocation(body.AsSpan(701), 1, -1); + if (oblique) + { + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(336), 1 / Math.Sqrt(5)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -2 / Math.Sqrt(5)); + } + + var pool = new byte[(validWallLabel.HasValue || trimmed || weakMiterPeer ? 31 : otherColumn ? 28 : 24) * 1024]; + var records = new List(); + void Add(ushort kind, Guid id, byte[] bytes, int? position = null) + { + int offset = position ?? records.Count * 1024; + Synthetic.Block(PlaBlockMode.Raw, bytes, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, offset); + records.Add(new ObjectDirectoryRecord(kind, (ulong)offset / 16, 64, id)); + } + + PlaProfilePoint[] ring = concaveProfile + ? [new(-0.25, -0.25), new(0.25, -0.25), new(0.25, 0), new(0, 0), new(0, 0.25), new(-0.25, 0.25), new(-0.25, -0.25)] + : [new(-0.25, -0.25), new(0.25, -0.25), new(0.25, 0.25), new(-0.25, 0.25), new(-0.25, -0.25)]; + Add(1, column, WithGeometryRelations(body, GeometryRelation(0x11, memoKey, memo))); + Add(2, memo, WithGeometryRelations(columnMemoClass.ToByteArray(), HostRelation(memoKey, column), + GeometryRelation(0x11, sectionKey, section), equal + ? GeometryRelationList(1, beamKey, lowerContact, middleContact, throughContact) + : GeometryRelationList(1, beamKey, lowerContact, middleContact), + validWallLabel.HasValue ? GeometryRelation(0x11, columnWall, wallContact) : [])); + Add(4, section, WithGeometryRelations(sectionClass.ToByteArray(), HostRelation(sectionKey, memo), GeometryRelation(0x11, shapeKey, shape))); + Add(5, shape, WithGeometryRelations(SavedMemberProfileShape(shapeClass, 1, SavedProfileHatch(1, 1, 0, ring)), HostRelation(shapeKey, section))); + + var contact = new byte[67]; + beamJoinClass.TryWriteBytes(contact); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(contact, 35); + double jointX = activeMiter ? 0 : tee || beamEnd == ColumnBeamEnd.MiterAtFace ? 0.25 : miter ? 0.5 : 2; + double beamY = clearBeams ? 1 : 0; + double skew = skewedBeam ? 0.5 : 0; + if (!overlap) + { + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(50), jointX); + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(58), beamY + skew); + contact[66] = 1; + } + Guid extraContact = Guid.NewGuid(); + Guid beamColumn = new("cd0b0837-0b34-4e96-8d66-9fe7d926478c"); + Guid branchRole = overlap ? secondCollision : firstEnd; + Guid nextRole = tee || overlap ? throughRole : secondEnd; + byte[] JointLinks(Guid role) => repeated || (weakMiterPeer && role == branchRole) + ? GeometryRelationList(1, role, beamJoin, repeatedJoin) : GeometryRelation(0x11, role, beamJoin); + Guid middle = AddBeamCutFixture(pool, records, memo, middleContact, 6144, beamY - skew, 2.5, partialCut ? 0.125 : 0.25, 0, + oblique ? [] : JointLinks(branchRole), endElevation: oblique ? 3.5 : null, + additionalColumnContact: otherColumn ? extraContact : null, endY: beamY + skew, endX: jointX); + AddBeamCutFixture(pool, records, memo, lowerContact, 16384, beamY, 0.75, 0.25, 0, []); + if (!oblique) + { + const double throughStart = -0.375; + var throughLinks = trimmed + ? Synthetic.Concat(JointLinks(throughRole), GeometryRelation(0x11, firstEnd, throughTrim)) + : JointLinks(nextRole); + Guid next = activeMiter + ? AddBeamCutFixture(pool, records, memo, throughContact, 11264, jointX, 2.5, 0.25, 0, throughLinks, + transverse: true, startY: beamY) + : tee + ? AddBeamCutFixture(pool, records, equal ? memo : Guid.Empty, throughContact, 11264, angledTee ? jointX - 0.5 : jointX, + beamEnd == ColumnBeamEnd.DifferentHeightTee ? 2.625 : 2.5, 0.125, 0, throughLinks, + transverse: true, material: equal ? 2u : 3u, startY: trimmed ? throughStart : -2, + concaveSection: !equal, endX: angledTee ? jointX + 0.5 : null) + : AddBeamCutFixture(pool, records, Guid.Empty, Guid.Empty, 11264, + beamEnd == ColumnBeamEnd.SeparateEqualOverlap ? 1 : beamY + skew, 2.5, 0.25, 0, + JointLinks(nextRole), startX: overlap ? -2 : jointX, endX: overlap ? 2 : 4, + endY: overlap ? null : miter ? 1 : beamY + 2 * skew, + material: beamEnd == ColumnBeamEnd.WeakerOverlap ? 3u : 2u); + var connection = WithGeometryRelations(contact, HostRelation(branchRole, middle), HostRelation(nextRole, next)); + Add(12, beamJoin, connection, 22528); + if (repeated) Add(12, repeatedJoin, connection, 23552); + if (weakMiterPeer) + { + double weakEndX = beamEnd == ColumnBeamEnd.EqualMiterWithDifferentWeakPeer ? jointX + 0.25 : jointX; + Guid weak = AddBeamCutFixture(pool, records, Guid.Empty, Guid.Empty, 24576, jointX, 2.5, 0.25, 0, + GeometryRelation(0x11, nextRole, repeatedJoin), transverse: true, startY: beamY, + endX: weakEndX, material: 3, concaveSection: true); + Add(12, repeatedJoin, WithGeometryRelations(contact, HostRelation(branchRole, middle), HostRelation(nextRole, weak)), 29696); + } + if (trimmed) + { + Guid weak = AddBeamCutFixture(pool, records, Guid.Empty, Guid.Empty, 24576, throughStart, 2.5, 0.25, 0, + GeometryRelation(0x11, throughRole, throughTrim), material: 3, concaveSection: true); + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(58), throughStart); + Add(12, throughTrim, WithGeometryRelations(contact, HostRelation(firstEnd, next), HostRelation(throughRole, weak)), 29696); + } + } + Guid beamColumnClass = new("f7f60005-35d0-4346-87ab-29e087ac0bbf"); + if (otherColumn) + { + Guid placed = Guid.NewGuid(), otherMemo = Guid.NewGuid(), otherSection = Guid.NewGuid(); + Add(1, placed, WithGeometryRelations(body, GeometryRelation(0x11, memoKey, otherMemo)), 24576); + Add(2, otherMemo, WithGeometryRelations(columnMemoClass.ToByteArray(), HostRelation(memoKey, placed), + GeometryRelation(0x11, sectionKey, otherSection), GeometryRelation(0x11, beamKey, extraContact)), 25600); + Add(3, otherSection, WithGeometryRelations(RectangularSection(new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"), 2, 0.25, -0.25, 0.25), + HostRelation(sectionKey, otherMemo)), 26624); + Add(11, extraContact, WithGeometryRelations(beamColumnClass.ToByteArray(), + HostRelation(beamColumn, middle), HostRelation(beamKey, wrongOtherOwner ? Guid.NewGuid() : otherMemo)), 27648); + } + + byte[] labelDirectory = [], labelPool = []; + if (validWallLabel is { } valid) + { + Guid wall = Guid.NewGuid(), wallProfile = Guid.NewGuid(), label = Guid.NewGuid(); + Guid profileKey = new("e63e7632-0efd-412d-8077-d3f3906b638a"), labelKey = new("5dd68b40-d2b2-4e13-9238-8343cdb6c423"); + Guid columnLabelKey = new("f73ad2dc-973b-4e70-9787-a3c6fee4a2bf"); + var wallBody = WallWithPlanes(2, 0); + var settings = wallBody.AsSpan(209); + BinaryPrimitives.WriteDoubleLittleEndian(settings[8..], -2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[24..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 3); + WriteRectangularPlan(settings[256..], 0.5, -2, 1, 2, slab: false); + Add(13, wall, WithGeometryRelations(wallBody, GeometryRelation(0x11, profileKey, wallProfile), + GeometryRelation(0x11, wallColumn, wallContact), GeometryRelation(0x11, labelKey, label)), 28672); + PlaProfilePoint[] wallRing = [new(0, 5), new(1, 5), new(1, 6), new(0, 6), new(0, 5)]; + var placedProfile = SavedProfileHatch(2, 1, 0, wallRing); + Add(14, wallProfile, WithGeometryRelations(SavedWallProfileRecord(wallProfileClass, placedProfile), HostRelation(profileKey, wall)), 29696); + Add(15, wallContact, WithGeometryRelations(wallColumnClass.ToByteArray(), HostRelation(wallColumn, wall), + HostRelation(columnWall, memo)), 30720); + labelDirectory = OwnedDirectory(false, Guid.Empty, 64, new ObjectDirectoryRecord(16, 0, 64, label)); + var labelData = new byte[1024]; + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(labelClass.ToByteArray(), + HostRelation(labelKey, valid ? wall : Guid.NewGuid()), HostRelation(columnLabelKey, column)), + ver: 1, guid: label, extra: 1, kind: 16).CopyTo(labelData, 0); + labelPool = Pool(labelData); + } + + return Synthetic.Fdb(ClassTable((1, columnClass), (2, columnMemoClass), (3, new("c4191955-87c6-4fb6-b074-5f094fe9f6a6")), + (4, sectionClass), (5, shapeClass), (6, storyClass), (7, materialClass), (8, layerClass), + (9, new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")), (10, new("cbab7bc6-e03a-4133-9161-c28ed3368672")), + (11, beamColumnClass), (12, beamJoinClass), (13, WallClass), (14, wallProfileClass), (15, wallColumnClass), (16, labelClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, records.ToArray()), labelDirectory, + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 6), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, 1200), + JunctionAttribute(materialClass, 7, 3, 900), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool), labelPool); + } + + private static byte[] SavedMemberProfileShape(Guid shapeClass, int index, byte[] hatch) + { + var profile = new byte[400 + 128 + hatch.Length]; + shapeClass.TryWriteBytes(profile); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(47), 1); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(49), index); + byte[] frame = [2, 0, 9, 1]; + frame.CopyTo(profile, 53); + frame.CopyTo(profile, 392); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(396), 128 + hatch.Length); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(400), 128); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(400 + 69), 1); + hatch.CopyTo(profile, 400 + 128); + return profile; + } + + [Theory] + [InlineData(true, "valid")] + [InlineData(false, "valid")] + [InlineData(false, "hole")] + [InlineData(false, "curved")] + [InlineData(false, "crosshair")] + [InlineData(false, "invalid crosshair")] + [InlineData(false, "single annotation")] + [InlineData(false, "annotation list")] + [InlineData(false, "annotation owner")] + [InlineData(true, "memo owner")] + [InlineData(false, "section owner")] + [InlineData(true, "shape owner")] + [InlineData(false, "invalid index")] + public void ReadsSavedBeamAndColumnProfiles(bool beam, string variation) + { + Guid elementClass = new(beam ? "a5c2d285-5a7c-4a68-9554-9eda9d4556ca" : "13e8eb85-5a33-47a3-a4d4-1e05296aec7e"); + Guid memoClass = new(beam ? "cbab7bc6-e03a-4133-9161-c28ed3368672" : "7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid memoKey = new(beam ? "d5762ca7-d920-455d-a373-28ba6d47152a" : "27448621-9adc-43e6-b5aa-fc76e4cd62ce"); + Guid sectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"), shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"); + Guid element = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), shape = Guid.NewGuid(); + + bool crosshair = variation is "crosshair" or "invalid crosshair"; + PlaProfilePoint[] ring = crosshair + ? [new(-1, -1.5), new(1, -1.5), new(1, 1.5), new(-1, 1.5), new(-1, -1.5)] + : [new(-1, 0), new(1, 0), new(1, 3), new(-1, 3), new(-1, 0)]; + PlaProfilePoint[] hole = [new(-0.5, 1), new(-0.5, 2), new(0.5, 2), new(0.5, 1), new(-0.5, 1)]; + var hatch = SavedProfileHatch(17, 1, variation == "curved" ? 2 : 0, variation == "hole" ? [ring, hole] : [ring]); + var profile = SavedMemberProfileShape(shapeClass, variation == "invalid index" ? -1 : 12, hatch); + + Guid annotationClass = new("5793eecb-32e2-4fdd-b216-739ff6c806c4"), annotationKey = new("386bc4fb-ea34-4287-8067-4f16b966b7af"); + Guid annotation = Guid.NewGuid(), secondAnnotation = Guid.NewGuid(); + byte[] annotationLink = variation switch + { + "single annotation" => GeometryRelation(0x11, annotationKey, annotation), + "annotation list" or "annotation owner" => GeometryRelationList(1, annotationKey, annotation, secondAnnotation), + _ => [], + }; + const int extent = 2048, units = extent / 16; + var pool = new byte[(annotationLink.Length == 0 ? 4 : 6) * extent]; + var entries = new List(); + void Add(ushort kind, Guid id, byte[] bytes) + { + Synthetic.Block(PlaBlockMode.Raw, bytes, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, entries.Count * extent); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)entries.Count * units, units, id)); + } + byte[] body = Synthetic.Concat(FramedElementId(elementClass, 735, "P"), new byte[95]); + if (!beam) + { + ElementId("P").CopyTo(body.AsSpan(721)); + WriteLocation(body.AsSpan(701), 1, -1); + new byte[] { 1, 0, 2, 0, 0, 0, 1, 0 }.CopyTo(body, 304); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(368), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(312), 10); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(320), 20); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(370), 10); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(378), 20); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(386), 2); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(410), 1); + body[741] = crosshair ? (byte)4 : (byte)1; + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(741 + 69), variation == "invalid crosshair" ? double.NaN : 1.25); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(741 + 87), crosshair ? Math.PI / 6 : Math.PI / 2); + } + Add(1, element, WithGeometryRelations(body, GeometryRelation(0x11, memoKey, memo), annotationLink)); + Add(2, memo, WithGeometryRelations(memoClass.ToByteArray(), + HostRelation(memoKey, variation == "memo owner" ? Guid.NewGuid() : element), GeometryRelation(0x11, sectionKey, section))); + Add(3, section, WithGeometryRelations(sectionClass.ToByteArray(), + HostRelation(sectionKey, variation == "section owner" ? Guid.NewGuid() : memo), GeometryRelation(0x11, shapeKey, shape))); + Add(4, shape, WithGeometryRelations(profile, HostRelation(shapeKey, variation == "shape owner" ? Guid.NewGuid() : section))); + if (annotationLink.Length != 0) + { + Add(6, annotation, WithGeometryRelations(annotationClass.ToByteArray(), HostRelation(annotationKey, element))); + Add(6, secondAnnotation, WithGeometryRelations(annotationClass.ToByteArray(), + HostRelation(annotationKey, variation == "annotation owner" ? Guid.NewGuid() : element))); + } + + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + using var doc = Open(ClassTable((1, elementClass), (2, memoClass), (3, sectionClass), (4, shapeClass), (5, storyClass), + (6, annotationClass)), OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 5), Pool(pool)); + var item = Assert.Single(doc.ReadElements()); + var result = item.MemberProfile; + if (variation is "memo owner" or "section owner" or "shape owner" or "invalid index") + { + Assert.Null(result); + Assert.Null(item.ColumnExtrusion); + return; + } + var decoded = Assert.IsType(result); + Assert.Equal(12, decoded.ProfileIndex); + var component = Assert.Single(decoded.Components); + Assert.Equal(17, component.BuildingMaterialIndex); + Assert.Equal("Core", component.Function); + Assert.Equal(ring[..^1], component.Rings[0]); + if (variation == "curved") + { + Assert.Single(component.Arcs!); + Assert.Null(item.ColumnExtrusion); + return; + } + double area = variation == "hole" ? 5 : 6; + Assert.Equal(area, component.CrossSectionArea); + if (beam) return; + if (variation == "annotation owner") + { + Assert.Null(item.BottomElevationToProjectZero); + Assert.Null(item.ColumnExtrusion); + return; + } + var solid = Assert.IsType(item.ColumnExtrusion); + Assert.Equal(new PlaPlanPoint(10, 20), solid.Origin); + if (crosshair) + { + double cos = Math.Sqrt(3) / 2; + Assert.Equal(10 + cos + 0.75, solid.BoundingBox.XMax, 12); + Assert.Equal(20 + 0.5 + 1.5 * cos, solid.BoundingBox.YMax, 12); + if (variation == "invalid crosshair") + Assert.Null(item.BoundingBox); + else + { + var box = Assert.IsType(item.BoundingBox); + Assert.Equal(10 - 2.25 * cos, box.XMin, 12); + Assert.Equal(10 + 2.25 * cos, box.XMax, 12); + Assert.Equal(20 - 2.75 * cos, box.YMin, 12); + Assert.Equal(20 + 2.75 * cos, box.YMax, 12); + Assert.Equal((-4d, -2d), (box.ZMin, box.ZMax)); + } + } + else + { + Assert.Equal(new PlaBoundingBox(7, 19, -4, 10, 21, -2), solid.BoundingBox); + Assert.Equal(solid.BoundingBox, item.BoundingBox); + } + Assert.Equal(2 * area, solid.Volume); + Assert.Equal(variation == "hole" ? 2 : 1, Assert.Single(solid.Sections).Rings.Count); + } + + [Theory] + [InlineData(900, false, false, false, 3.7)] + [InlineData(1000, false, false, false, 4.0)] + [InlineData(900, true, false, false, null)] + [InlineData(900, false, true, false, null)] + [InlineData(900, false, false, true, 3.825)] + public void ComputesSlabVolumeFromTheIntersectionWithAPrismaticWallProfile(int slabPriority, bool staleEnvelope, + bool otherContact, bool composite, double? volume) + { + Guid profileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"); + Guid contactClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid compositeClass = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid profileRole = new("e63e7632-0efd-412d-8077-d3f3906b638a"); + Guid slabRole = new("29bce22c-b910-400a-b84a-0b85fb92610e"); + Guid wallRole = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slab = Guid.NewGuid(), wall = Guid.NewGuid(), profile = Guid.NewGuid(), contact = Guid.NewGuid(); + + var slabBody = OpeningSlab(-1, 0.5, 1); + if (composite) + { + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 83), 2); + BinaryPrimitives.WriteUInt16LittleEndian(slabBody.AsSpan(191 + 87), 1); + } + var wallBody = WallWithPlanes(1, -4.5); + var wallSettings = wallBody.AsSpan(209); + BinaryPrimitives.WriteUInt16LittleEndian(wallSettings[225..], 3); + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[153..], 1.5); + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[161..], -0.5); + double[] line = [0.8, -2, 0.8, 2]; + for (int i = 0; i < line.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[(8 * i)..], line[i]); + new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(wallSettings[489..]); + double[] envelope = [staleEnvelope ? 0.7 : 0.8, -2, 1.2, 2, -4.5, -3]; + for (int i = 0; i < envelope.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(wallSettings[(515 + 8 * i)..], envelope[i]); + + const int hatchSize = 59 + 6 * 16 + 6; + byte[] profileBody = new byte[402 + 128 + hatchSize]; + profileClass.TryWriteBytes(profileBody); + new byte[] { 2, 0, 9, 1 }.CopyTo(profileBody, 394); + BinaryPrimitives.WriteUInt32LittleEndian(profileBody.AsSpan(398), 128 + hatchSize); + BinaryPrimitives.WriteUInt32LittleEndian(profileBody.AsSpan(402), 128); + BinaryPrimitives.WriteUInt32LittleEndian(profileBody.AsSpan(402 + 69), 1); + var hatch = profileBody.AsSpan(402 + 128); + hatch[0] = 3; + hatch[1] = 1; + BinaryPrimitives.WriteUInt32LittleEndian(hatch[2..], hatchSize - 6); + BinaryPrimitives.WriteUInt16LittleEndian(hatch[8..], 2); + BinaryPrimitives.WriteInt32LittleEndian(hatch[18..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[55..], 6); + (double U, double Z)[] points = [(0, 0), (0.4, 0), (0.4, 1.5), (0, 0.5), (0, 0)]; + for (int i = 0; i < points.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(hatch[(75 + 16 * i)..], points[i].U); + BinaryPrimitives.WriteDoubleLittleEndian(hatch[(83 + 16 * i)..], points[i].Z); + } + BinaryPrimitives.WriteUInt16LittleEndian(hatch[(59 + 6 * 16)..], 1); + + byte[] pool = new byte[4 * 1024]; + var entries = new List(); + void Add(ushort kind, Guid id, byte[] bytes) + { + int offset = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, bytes, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, offset * 1024); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)offset * 64, 64, id)); + } + Add(1, slab, WithGeometryRelations(slabBody, GeometryRelation(0x11, slabRole, contact))); + Add(2, wall, WithGeometryRelations(wallBody, GeometryRelation(0x11, wallRole, contact), + GeometryRelation(0x11, profileRole, profile), + otherContact ? GeometryRelation(0x11, Guid.NewGuid(), Guid.NewGuid()) : [])); + Add(3, profile, WithGeometryRelations(profileBody, HostRelation(profileRole, wall))); + Add(4, contact, WithGeometryRelations(contactClass.ToByteArray(), HostRelation(slabRole, slab), HostRelation(wallRole, wall))); + + using var doc = Open(ClassTable((1, SlabClass), (2, WallClass), (3, profileClass), (4, contactClass), + (5, storyClass), (7, materialClass), (8, layerClass), (9, compositeClass)), + OwnedDirectory(false, Guid.Empty, 256, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 5), + JunctionAttribute(materialClass, 7, 1, 1000), JunctionAttribute(materialClass, 7, 2, (uint)slabPriority), + JunctionAttribute(materialClass, 7, 3, 1100), JunctionAttribute(layerClass, 8, 1, 1), + CompositeForWallTest(compositeClass, splitCuts: false, kind: 9), Pool(pool)); + var geometry = Assert.IsType(Assert.Single(doc.ReadElements(), e => e.Guid == slab).SlabGeometry); + if (volume.HasValue) + Assert.Equal(volume.Value, geometry.Volume!.Value, 12); + else + Assert.Null(geometry.Volume); + Assert.Equal(4, geometry.TopAreaWithOpenings); + Assert.Equal(4, geometry.BottomAreaWithOpenings); + } + + private static PlaElement ReadElementWithStory(Guid elementClass, byte[] body) + { + var (file, _) = ElementWithStoryFile(elementClass, body); + using var doc = PlaDocument.Open(new MemoryStream(file)); + return Assert.Single(doc.ReadElements()); + } + + private static (byte[] File, Guid Element) ElementWithStoryFile(Guid elementClass, byte[] body) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid id = Guid.NewGuid(); + var block = Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: 1); + byte[] pool = new byte[Math.Max(1024, (block.Length + 15) / 16 * 16)]; + uint paragraphs = (uint)pool.Length / 16; + block.CopyTo(pool, 0); + byte[] file = Synthetic.Fdb(ClassTable((1, elementClass), (2, storyClass)), + OwnedDirectory(false, Guid.Empty, paragraphs, new ObjectDirectoryRecord(1, 0, paragraphs, id)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 2), Pool(pool)); + return (file, id); + } + + internal static (byte[] File, Guid Element) SlabSceneFixture(bool concave, bool beveled) + { + const int outlineOffset = 191 + 166; + const int alternateOffset = 191 + 270; + byte[] slab = RectangularSlab(true, concave ? 7 : 0); + int polygonSize = BinaryPrimitives.ReadInt32LittleEndian(slab.AsSpan(alternateOffset + 4)); + slab.AsSpan(alternateOffset, polygonSize).CopyTo(slab.AsSpan(outlineOffset)); + int edgeCount = concave ? 6 : 4; + int edgesOffset = outlineOffset + polygonSize; + Array.Resize(ref slab, edgesOffset + 16 + edgeCount * 27); + WriteSlabEdges(slab.AsSpan(edgesOffset), edgeCount, beveled ? 0 : -1); + return ElementWithStoryFile(SlabClass, WithGeometryRelations(slab)); + } + + internal static (byte[] File, Guid Element) SlabWithHolesSceneFixture() + { + var slab = SlabWithStraightRings(-1, + [(0, 0), (0, 4), (2, 4), (2, 2), (4, 2), (4, 0), (0, 0)], + [(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5), (0.5, 0.5)], + [(2.5, 0.5), (3.5, 0.5), (3.5, 1.5), (2.5, 1.5), (2.5, 0.5)]); + return ElementWithStoryFile(SlabClass, WithGeometryRelations(slab)); + } + + private static byte[] SlabWithStraightRings(int beveledEdge, params (double X, double Y)[][] rings) + { + var points = rings.SelectMany(r => r).ToArray(); + int polygonSize = 71 + points.Length * 16 + (rings.Length + 1) * 4; + int edgeCount = points.Length - rings.Length; + const int outlineOffset = 191 + 166; + var slab = RectangularSlab(true); + Array.Resize(ref slab, outlineOffset + polygonSize + 16 + edgeCount * 27); + var polygon = slab.AsSpan(outlineOffset); + polygon.Clear(); + new byte[] { 2, 0, 2, 1 }.CopyTo(polygon); + BinaryPrimitives.WriteInt32LittleEndian(polygon[4..], polygonSize); + new byte[] { 1, 31, 0 }.CopyTo(polygon[8..]); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[27..], points.Max(p => p.X)); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[35..], points.Max(p => p.Y)); + BinaryPrimitives.WriteInt32LittleEndian(polygon[43..], points.Length); + BinaryPrimitives.WriteInt32LittleEndian(polygon[51..], rings.Length); + for (int i = 0; i < points.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(71 + i * 16)..], points[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(79 + i * 16)..], points[i].Y); + } + int table = 71 + points.Length * 16; + int end = 0; + for (int i = 0; i < rings.Length; i++) + { + end += rings[i].Length; + BinaryPrimitives.WriteInt32LittleEndian(polygon[(table + (i + 1) * 4)..], end); + } + WriteSlabEdges(polygon[polygonSize..], edgeCount, beveledEdge); + return slab; + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void ReadsUnjoinedWallPlanesWhenTheStoredEnvelopeAgrees(bool joined, bool staleEnvelope) + { + byte[] wall = WallWithPlanes(1, staleEnvelope ? -2.75 : -3.75); + byte[] relation = GeometryRelation(0x11, joined + ? new Guid("0e7a0206-f853-4c86-9f9e-43266b0ab58a") + : new Guid("3b42cf2e-0d77-4d3d-bf03-0b922103f576"), Guid.NewGuid()); + var element = ReadElementWithStory(WallClass, WithGeometryRelations(wall, relation)); + bool supported = !joined && !staleEnvelope; + Assert.Equal(supported ? 0.25 : null, element.BottomElevationToHomeStory); + Assert.Equal(supported ? 3.25 : null, element.TopElevationToHomeStory); + Assert.Equal(supported ? -3.75 : null, element.BottomElevationToProjectZero); + Assert.Equal(supported ? -0.75 : null, element.TopElevationToProjectZero); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void ReadsTheFramedWallBoxIndependentlyOfItsSchedulePlanes(bool wrongFrame, bool invalidCoordinate) + { + byte[] wall = WallWithPlanes(1, -3.75); + var settings = wall.AsSpan(209); + new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(settings[489..]); + if (wrongFrame) settings[490] = 1; + WriteWallStrip(settings, alongX: true, 0.125); + BinaryPrimitives.WriteDoubleLittleEndian(settings[547..], invalidCoordinate ? double.NaN : -3.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[555..], -0.75); + var element = ReadElementWithStory(WallClass, wall); + + Assert.Equal(wrongFrame || invalidCoordinate ? null : new PlaBoundingBox(-0.5, -0.125, -3.5, 0.5, 0.125, -0.75), + element.BoundingBox); + Assert.Null(element.BottomElevationToProjectZero); + } + + [Theory] + [InlineData(0, false, 0, false, false)] + [InlineData(1, false, 0.25, false, false)] + [InlineData(3, true, 0.0625, false, false)] + [InlineData(4, true, 0.1875, true, false)] + [InlineData(0, true, 0, false, true)] + public void ReadsStraightWallReferencePlacementFromItsInlineContour(uint mode, bool flipped, double offset, + bool joined, bool inconsistentContour) + { + var (file, _) = WallReferenceSceneFixture(mode, flipped, offset, joined, inconsistentContour); + using var document = PlaDocument.Open(new MemoryStream(file)); + var element = Assert.Single(document.ReadElements()); + var start = new PlaPlanPoint(4, -3); + var end = new PlaPlanPoint(1, 1); + double outside = flipped ? offset : -offset; + double inside = flipped ? offset - 0.25 : 0.25 - offset; + Assert.Equal(inconsistentContour ? null : new PlaWallReferencePlan(start, end, outside, inside), element.WallReferencePlan); + if (joined || inconsistentContour) + { + Assert.Null(element.BoundingBox); + Assert.Null(element.BottomElevationToProjectZero); + Assert.Null(element.TopElevationToHomeStory); + return; + } + double u0 = Math.Min(outside, inside), u1 = Math.Max(outside, inside); + Assert.Equal(new PlaBoundingBox(end.X + 0.8 * u0, start.Y + 0.6 * u0, -3.75, + start.X + 0.8 * u1, end.Y + 0.6 * u1, -0.75), element.BoundingBox); + Assert.Equal(-3.75, element.BottomElevationToProjectZero); + Assert.Equal(-0.75, element.TopElevationToProjectZero); + Assert.Equal(0.25, element.BottomElevationToHomeStory); + Assert.Equal(3.25, element.TopElevationToHomeStory); + } + + [Theory] + [InlineData(null, true)] + [InlineData(-3.75, true)] + [InlineData(-3.5, false)] + public void ReadsStraightWallBoxWithAnEmptyPlanCache(double? storedBottom, bool supported) + { + var (file, _) = WallReferenceSceneFixture(0, flipped: false, offset: 0, joined: true, inconsistentContour: false, + hasEmptyPlanFrame: true, storedBottom: storedBottom); + using var document = PlaDocument.Open(new MemoryStream(file)); + var wall = Assert.Single(document.ReadElements()); + Assert.Equal(supported ? new PlaBoundingBox(1, -3, -3.75, 4.2, 1.15, -0.75) : null, wall.BoundingBox); + Assert.Null(wall.BottomElevationToProjectZero); + Assert.Null(wall.TopElevationToHomeStory); + } + + internal static (byte[] File, Guid Element) WallReferenceSceneFixture(uint mode, bool flipped, double offset, + bool joined, bool inconsistentContour, bool? validZoneCalculation = null, bool hasEmptyPlanFrame = false, + double? storedBottom = null) + { + byte[] wall = WallWithPlanes(1, -3.75); + var settings = wall.AsSpan(209); + settings[547..563].Clear(); + if (hasEmptyPlanFrame) new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(settings[489..]); + if (storedBottom is { } bottom) + { + BinaryPrimitives.WriteDoubleLittleEndian(settings[547..], bottom); + BinaryPrimitives.WriteDoubleLittleEndian(settings[555..], bottom + 3); + } + var start = new PlaPlanPoint(4, -3); + var end = new PlaPlanPoint(1, 1); + const double thickness = 0.25; + BinaryPrimitives.WriteDoubleLittleEndian(settings, start.X); + BinaryPrimitives.WriteDoubleLittleEndian(settings[8..], start.Y); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], end.X); + BinaryPrimitives.WriteDoubleLittleEndian(settings[24..], end.Y); + BinaryPrimitives.WriteDoubleLittleEndian(settings[77..], thickness); + BinaryPrimitives.WriteDoubleLittleEndian(settings[85..], thickness); + if (mode >= 3) BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 2); + settings[238] = flipped ? (byte)1 : (byte)0; + BinaryPrimitives.WriteUInt32LittleEndian(settings[239..], mode); + BinaryPrimitives.WriteDoubleLittleEndian(settings[243..], offset); + double outside = flipped ? offset : -offset; + double inside = flipped ? offset - thickness : thickness - offset; + double u0 = Math.Min(outside, inside), u1 = Math.Max(outside, inside); + PlaPlanPoint Shift(PlaPlanPoint point, double u) => new(point.X + 0.8 * u, point.Y + 0.6 * u); + PlaPlanPoint[] corners = [Shift(start, u1), Shift(end, u1), Shift(end, u0), Shift(start, u0)]; + double minX = corners.Min(p => p.X), minY = corners.Min(p => p.Y); + double maxX = corners.Max(p => p.X), maxY = corners.Max(p => p.Y); + var polygon = settings[256..]; + new byte[] { 0, 0, 2, 1, 247, 0, 0, 0, 0, 31, 0 }.CopyTo(polygon); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[11..], minX); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[19..], minY); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[27..], maxX); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[35..], maxY); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[43..], 5); + BinaryPrimitives.WriteUInt32LittleEndian(polygon[51..], 1); + for (int i = 0; i < 5; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(71 + 16 * i)..], corners[i % 4].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(79 + 16 * i)..], corners[i % 4].Y); + } + BinaryPrimitives.WriteUInt32LittleEndian(polygon[155..], 5); + if (inconsistentContour) BinaryPrimitives.WriteDoubleLittleEndian(polygon[87..], 2); + + var wallRecord = WithGeometryRelations(wall, GeometryRelation(0x11, + new Guid(joined ? "0e7a0206-f853-4c86-9f9e-43266b0ab58a" : "3b42cf2e-0d77-4d3d-bf03-0b922103f576"), Guid.NewGuid())); + return validZoneCalculation is { } valid ? WallFixtureWithZoneCalculation(wall, valid) : ElementWithStoryFile(WallClass, wallRecord); + } + + private static (byte[] File, Guid Element) WallFixtureWithZoneCalculation(byte[] wall, bool valid) + { + Guid zoneClass = new("3ad0332e-efe2-491a-92a6-5b14bfdd7229"); + Guid calculationClass = new("ea57dcc5-7231-45df-83dc-792083fc4699"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid relation = new("cc4c5518-9f96-4272-8130-5d61c5a351e6"); + Guid owner = Guid.NewGuid(), zone = Guid.NewGuid(), record = Guid.NewGuid(); + const int extent = 1024; + var pool = new byte[extent * 3]; + var wallBody = WithGeometryRelations(wall, GeometryRelationList(2, relation, zone, record)); + var calculation = WithGeometryRelations(calculationClass.ToByteArray(), + GeometryRelationList(4, relation, zone, valid ? owner : Guid.NewGuid())); + Synthetic.Block(PlaBlockMode.Raw, wallBody, ver: 1, extra: 1, kind: 1, guid: owner).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, zoneClass.ToByteArray(), ver: 1, extra: 1, kind: 2, guid: zone).CopyTo(pool, extent); + Synthetic.Block(PlaBlockMode.Raw, calculation, ver: 1, extra: 1, kind: 3, guid: record).CopyTo(pool, extent * 2); + return (Synthetic.Fdb(ClassTable((1, WallClass), (2, zoneClass), (3, calculationClass), (4, storyClass)), + OwnedDirectory(false, Guid.Empty, 192, new ObjectDirectoryRecord(1, 0, 64, owner), + new ObjectDirectoryRecord(2, 64, 64, zone), new ObjectDirectoryRecord(3, 128, 64, record)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), Pool(pool)), owner); + } + + [Theory] + [InlineData(0, 2.0, 2.0)] + [InlineData(1, 0.25, 1.0)] + [InlineData(2, -0.25, 0.875)] + [InlineData(3, null, null)] + [InlineData(4, null, null)] + [InlineData(5, 2.0, null)] + [InlineData(6, 2.0, 2.0)] + public void ReadsBeamQuantitiesThroughSupportedJunctions(int shape, double? xMax, double? volume) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid junctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid firstEnd = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"); + Guid secondEnd = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid through = new("89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid secondThrough = new("1d381463-2edc-4aad-91b0-027291e8da94"); + Guid junction = Guid.NewGuid(); + bool joined = shape != 0; + Guid ownRole = shape >= 5 ? through : firstEnd; + byte[] pool = new byte[11 * 1024]; + var entries = new List(); + Guid own = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 0, 0, 2, 0.25, 0, + joined ? GeometryRelation(0x11, ownRole, junction) : [], endX: joined && shape < 5 ? 0 : null); + if (joined) + { + Guid otherRole = shape switch { 1 => secondEnd, 5 => secondThrough, 6 => firstEnd, _ => through }; + Guid peer = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 5120, 0, shape == 3 ? 2.25 : 2, 0.25, 0, + GeometryRelation(0x11, otherRole, shape == 4 ? Guid.NewGuid() : junction), transverse: true, + startY: shape is 1 or 6 ? 0 : -2); + var joint = new byte[67]; + junctionClass.TryWriteBytes(joint); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(joint, 35); + joint[66] = 1; + byte[] contact = WithGeometryRelations(joint, HostRelation(ownRole, own), HostRelation(otherRole, peer)); + Synthetic.Block(PlaBlockMode.Raw, contact, ver: 1, guid: junction, extra: 1, kind: 12).CopyTo(pool, 10240); + entries.Add(new(12, 640, 64, junction)); + } + using var doc = Open(ClassTable((3, new Guid("c4191955-87c6-4fb6-b074-5f094fe9f6a6")), (4, storyClass), + (7, materialClass), (8, layerClass), (9, BeamClass), (10, new Guid("cbab7bc6-e03a-4133-9161-c28ed3368672")), + (12, junctionClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 2, 1000), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + + var beam = Assert.Single(doc.ReadElements(), e => e.Guid == entries[0].ObjectId); + Assert.Equal(xMax is { } end ? new PlaBoundingBox(-2, -0.25, -3, end, 0.25, -2) : null, beam.BoundingBox); + Assert.Equal(volume, beam.BeamNetVolume); + bool hasElevations = xMax.HasValue || shape == 3; + Assert.Equal(hasElevations ? -3.0 : null, beam.BottomElevationToProjectZero); + Assert.Equal(hasElevations ? -2.0 : null, beam.TopElevationToProjectZero); + Assert.Equal(hasElevations ? 1.0 : null, beam.BottomElevationToHomeStory); + Assert.Equal(hasElevations ? 2.0 : null, beam.TopElevationToHomeStory); + } + + [Theory] + [InlineData("unjoined", true, true)] + [InlineData("rolled", true, true)] + [InlineData("transverse", true, false)] + [InlineData("covers axis", false, false)] + [InlineData("combined cuts", false, false)] + [InlineData("missing reciprocal", false, false)] + [InlineData("opposite ends", true, true)] + [InlineData("overlapping ends", false, false)] + public void ReadsBeamElevationsWhenAProfileSectionSurvives(string junctionCase, bool hasElevations, bool hasBox) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"), memoKey = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid sectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"), shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"); + Guid junctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid own = Guid.NewGuid(), ownMemo = Guid.NewGuid(), segment = Guid.NewGuid(), profileId = Guid.NewGuid(), junction = Guid.NewGuid(); + Guid secondJunction = Guid.NewGuid(); + Guid peer = Guid.NewGuid(), peerMemo = Guid.NewGuid(), peerSegment = Guid.NewGuid(), peerShape = Guid.NewGuid(); + bool collinear = junctionCase is "opposite ends" or "overlapping ends"; + bool joined = junctionCase is not ("unjoined" or "rolled"); + bool twoCuts = junctionCase == "combined cuts"; + double roll = junctionCase == "rolled" ? Math.PI / 6 : 0; + Guid ownRole = new(collinear ? "59655252-b20b-47a7-9d4a-27a2f2bf2c73" : "89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid peerRole = new(collinear ? "1dae4518-b353-42bc-bcb1-d037bcc603d6" : "1d381463-2edc-4aad-91b0-027291e8da94"); + + PlaProfilePoint[] lowerRing = [new(-1, -2), new(1, -2), new(1, -1), new(-1, -1), new(-1, -2)]; + PlaProfilePoint[] upperRing = [new(-0.5, -1), new(0.5, -1), new(0.5, 0.5), new(-0.5, 0.5), new(-0.5, -1)]; + var lower = SavedProfileHatch(2, 1, 2, lowerRing); + var upper = SavedProfileHatch(3, 0, 0, upperRing); + var profile = new byte[528 + lower.Length + 16 + upper.Length]; + shapeClass.TryWriteBytes(profile); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(47), 1); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(49), 12); + byte[] frame = [2, 0, 9, 1]; + frame.CopyTo(profile, 53); + frame.CopyTo(profile, 392); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(396), profile.Length - 400); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(400), 128); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(469), 2); + lower.CopyTo(profile, 528); + upper.CopyTo(profile, 528 + lower.Length + 16); + + const int extent = 2048, units = extent / 16; + var pool = new byte[12 * extent]; + var entries = new List(); + Add(9, own, WithGeometryRelations(HorizontalBeam(BeamClass, -2, 0, collinear ? 0 : 2, 0, 2, roll, 1), + GeometryRelation(0x11, memoKey, ownMemo))); + Add(10, ownMemo, WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, own), + GeometryRelation(0x11, sectionKey, segment), twoCuts ? GeometryRelationList(1, ownRole, junction, secondJunction) : + joined ? GeometryRelation(0x11, ownRole, junction) : [])); + Add(13, segment, WithGeometryRelations(sectionClass.ToByteArray(), HostRelation(sectionKey, ownMemo), GeometryRelation(0x11, shapeKey, profileId))); + Add(14, profileId, WithGeometryRelations(profile, HostRelation(shapeKey, segment))); + if (joined) + { + if (collinear) + { + Add(9, peer, WithGeometryRelations(HorizontalBeam(BeamClass, 0, 0, junctionCase == "opposite ends" ? 2 : -2, 0, 2, 0, 1), + GeometryRelation(0x11, memoKey, peerMemo))); + Add(10, peerMemo, WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, peer), + GeometryRelation(0x11, sectionKey, peerSegment), GeometryRelation(0x11, peerRole, junction))); + Add(13, peerSegment, WithGeometryRelations(sectionClass.ToByteArray(), HostRelation(sectionKey, peerMemo), + GeometryRelation(0x11, shapeKey, peerShape))); + Add(14, peerShape, WithGeometryRelations(profile, HostRelation(shapeKey, peerSegment))); + } + else + { + double halfWidth = junctionCase == "covers axis" ? 2.25 : twoCuts ? 1.1 : 0.25; + peerMemo = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 4 * extent, twoCuts ? -1 : 0, 2, halfWidth, 0, + GeometryRelation(0x11, peerRole, junctionCase == "missing reciprocal" ? Guid.NewGuid() : junction), transverse: true); + } + AddJunction(junction, peerMemo, twoCuts ? -1 : 0, 11); + if (twoCuts) + { + Guid second = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 7 * extent, 1, 2, 1.1, 0, + GeometryRelation(0x11, peerRole, secondJunction), transverse: true); + AddJunction(secondJunction, second, 1, 10); + } + } + using var document = Open(ClassTable((3, new Guid("c4191955-87c6-4fb6-b074-5f094fe9f6a6")), (4, storyClass), + (7, materialClass), (8, layerClass), (9, BeamClass), (10, memoClass), (12, junctionClass), (13, sectionClass), (14, shapeClass)), + OwnedDirectory(false, Guid.Empty, 12 * units, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 2, 1000), JunctionAttribute(materialClass, 7, 3, 800), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var beam = Assert.Single(document.ReadElements(), e => e.Guid == own); + Assert.Equal(2, Assert.IsType(beam.MemberProfile).Components.Count); + if (roll == 0) + { + Assert.Equal(hasBox ? new PlaBoundingBox(-2, -1, -5, collinear ? 0 : 2, 1, -1.5) : null, beam.BoundingBox); + Assert.Equal(hasElevations ? -5.0 : null, beam.BottomElevationToProjectZero); + Assert.Equal(hasElevations ? -1.5 : null, beam.TopElevationToProjectZero); + Assert.Equal(hasElevations ? -1.0 : null, beam.BottomElevationToHomeStory); + Assert.Equal(hasElevations ? 2.5 : null, beam.TopElevationToHomeStory); + } + else + { + var box = Assert.IsType(beam.BoundingBox); + double low = -3 - Math.Sqrt(3), high = -2 + (1 + Math.Sqrt(3)) / 4; + Assert.Equal(-2, box.YMin, 12); + Assert.Equal(high + 2, box.YMax, 12); + Assert.Equal(low, box.ZMin, 12); + Assert.Equal(high, box.ZMax, 12); + Assert.Equal(low + 4, Assert.IsType(beam.BottomElevationToHomeStory), 12); + Assert.Equal(high + 4, Assert.IsType(beam.TopElevationToHomeStory), 12); + } + Assert.Null(beam.BeamNetVolume); + + void AddJunction(Guid id, Guid neighbor, double x, int slot) + { + var contact = new byte[67]; + junctionClass.TryWriteBytes(contact); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(contact, 35); + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(50), x); + contact[66] = 1; + Add(12, id, WithGeometryRelations(contact, HostRelation(ownRole, ownMemo), HostRelation(peerRole, neighbor)), slot); + } + + void Add(ushort kind, Guid id, byte[] payload, int? slot = null) + { + int position = slot ?? entries.Count; + Synthetic.Block(PlaBlockMode.Raw, payload, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, position * extent); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)position * units, units, id)); + } + } + + [Theory] + [InlineData(5, 1, 0, false, -3.25, 1.0, 2.0, 2.5)] + [InlineData(-1, 1, 0, false, -6.25, -2.0, 2.0, 2.5)] + [InlineData(5, 0.8, 0.6, false, -3.25, 1.0, 2.6, null)] + [InlineData(2, 0.8, 0.6, false, -3.0, -2.0, 2.75, null)] + [InlineData(5, -1, 0, false, null, null, null, null)] + [InlineData(5, 1, 0, true, null, null, null, null)] + public void ReadsBeamBoundsFromInclinationAndStoredCutPlanes(double endElevation, double normalX, double normalZ, + bool unresolvedContact, double? bottom, double? top, double? xMax, double? volume) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid rectangularSection = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"); + Guid beamMemoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + var pool = new byte[5 * 1024]; + var entries = new List(); + AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 0, 0, 2, 0.25, 0, + unresolvedContact ? GeometryRelation(0x11, Guid.NewGuid(), Guid.NewGuid()) : [], + endElevation: endElevation, endNormal: (normalX, normalZ)); + using var document = Open(ClassTable((3, rectangularSection), (4, storyClass), (7, materialClass), + (9, BeamClass), (10, beamMemoClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 2, 1000), Pool(pool)); + var beam = Assert.Single(document.ReadElements()); + var reference = Assert.IsType(beam.BeamReferenceAxis); + Assert.Equal(new PlaPlanPoint(-2, 0), reference.Start); + Assert.Equal(new PlaPlanPoint(2, 0), reference.End); + Assert.Equal(-2, reference.StartElevationToProjectZero); + Assert.Equal(endElevation - 4, reference.EndElevationToProjectZero); + Assert.Equal(0, reference.PlanSweepRadians); + Assert.Equal(Math.Atan2(endElevation - 2, 4), reference.InclinationRadians, 12); + Assert.Equal(double.Hypot(4, endElevation - 2), reference.Length, 12); + Assert.Equal(volume, beam.BeamNetVolume); + if (bottom is { } low && top is { } high && xMax is { } end) + { + var box = Assert.IsType(beam.BoundingBox); + Assert.Equal(-2.0, box.XMin, 12); + Assert.Equal(end, box.XMax, 12); + Assert.Equal(-0.25, box.YMin, 12); + Assert.Equal(0.25, box.YMax, 12); + Assert.Equal(low, box.ZMin, 12); + Assert.Equal(high, box.ZMax, 12); + Assert.Equal(low, Assert.IsType(beam.BottomElevationToProjectZero), 12); + Assert.Equal(high, Assert.IsType(beam.TopElevationToProjectZero), 12); + Assert.Equal(low + 4, Assert.IsType(beam.BottomElevationToHomeStory), 12); + Assert.Equal(high + 4, Assert.IsType(beam.TopElevationToHomeStory), 12); + } + else + { + Assert.Null(beam.BoundingBox); + Assert.Null(beam.BottomElevationToProjectZero); + Assert.Null(beam.TopElevationToProjectZero); + Assert.Null(beam.BottomElevationToHomeStory); + Assert.Null(beam.TopElevationToHomeStory); + } + } + + [Theory] + [InlineData(1000, 0.25, 1.75, true, 0, null, null, true)] + [InlineData(700, 0.25, 1.75, true, 0, null, null, false)] + [InlineData(1000, 0.10, 1.75, true, 0, null, null, false)] + [InlineData(1000, 0.25, 2.125, true, 0, null, null, false)] + [InlineData(1000, 0.25, 1.75, false, 0, null, null, false)] + [InlineData(1000, 0.25, 1.75, true, 800, null, null, true)] + [InlineData(1000, 0.25, 1.75, true, 1100, null, null, false)] + [InlineData(1000, 0.25, 1.75, true, 0, 0.0, null, true)] + [InlineData(1000, 0.25, 1.75, true, 0, 0.01, null, false)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "end under cover", true)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "end outside cover", false)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "slab above profile", true)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "slab within profile", false)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "angular dimension", true)] + [InlineData(1000, 0.25, 1.75, true, 0, null, "wrong angular dimension owner", false)] + public void ReadsZeroNetVolumeWhenRectangularBeamsCoverTheWholeProfile( + uint coveringPriority, double halfWidth, double elevation, bool reciprocal, uint competingPriority, + double? secondCoverStart, string? extraContact, bool hasZeroVolume) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"), memoKey = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid sectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"), shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"); + Guid junctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid mine = new("89d11bdb-3a78-48ad-96e7-5b69836c591d"), other = new("1d381463-2edc-4aad-91b0-027291e8da94"); + Guid endRole = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"); + Guid beamSlab = new("4df5ee09-8368-4f3b-ad64-056115b4c0ab"), slabBeam = new("d50bcd56-a71c-40f8-a3f1-551d14a4762b"); + Guid slabJunctionClass = new("7259c45f-97e3-434a-bc9e-fe3bcf980947"); + Guid owner = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(), shape = Guid.NewGuid(), joint = Guid.NewGuid(); + Guid competingJoint = Guid.NewGuid(); + Guid secondCoverJoint = Guid.NewGuid(); + Guid additionalJoint = Guid.NewGuid(); + Guid dimension = Guid.NewGuid(); + Guid dimensionClass = new("2120198c-d317-4cea-ab4e-c7b6ceb5156e"); + Guid dimensionRole = new("b3ffaf20-1c37-4090-b8f3-9e65bd5fa244"); + bool dimensionAttached = extraContact is "angular dimension" or "wrong angular dimension owner"; + bool endJoint = extraContact is "end under cover" or "end outside cover"; + bool slabCut = extraContact is "slab above profile" or "slab within profile"; + const int extent = 2048, units = extent / 16; + var pool = new byte[12 * extent]; + var entries = new List(); + Add(0, 9, owner, WithGeometryRelations(HorizontalBeam(BeamClass, 1, 0, -1, 0, elevation, 0, 1), + GeometryRelation(0x11, memoKey, memo), dimensionAttached ? GeometryRelation(0x11, dimensionRole, dimension) : [])); + Add(1, 10, memo, WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, owner), + GeometryRelation(0x11, sectionKey, section), secondCoverStart.HasValue + ? GeometryRelationList(1, mine, joint, secondCoverJoint) : GeometryRelation(0x11, mine, joint), + endJoint ? GeometryRelation(0x11, endRole, additionalJoint) : [])); + Add(2, 13, section, WithGeometryRelations(sectionClass.ToByteArray(), HostRelation(sectionKey, memo), + GeometryRelation(0x11, shapeKey, shape))); + + PlaProfilePoint[] ring = [new(-0.125, -0.5), new(0.15, -0.5), new(0.15, 0), new(-0.125, 0), new(-0.125, -0.5)]; + var hatch = SavedProfileHatch(1, 1, 0, ring); + var profile = new byte[528 + hatch.Length]; + shapeClass.TryWriteBytes(profile); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(47), 1); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(49), 1); + byte[] frame = [2, 0, 9, 1]; + frame.CopyTo(profile, 53); + frame.CopyTo(profile, 392); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(396), profile.Length - 400); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(400), 128); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(469), 1); + hatch.CopyTo(profile, 528); + Add(3, 14, shape, WithGeometryRelations(profile, HostRelation(shapeKey, section))); + + Guid savedJoint = reciprocal ? joint : Guid.NewGuid(); + byte[] relations = competingPriority == 0 ? GeometryRelation(0x11, other, savedJoint) + : GeometryRelationList(1, other, savedJoint, competingJoint); + if (slabCut) relations = Synthetic.Concat(relations, GeometryRelation(0x11, beamSlab, additionalJoint)); + Guid peerMemo = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 4 * extent, 0, 2, halfWidth, 0, relations, + endX: secondCoverStart.HasValue ? 0 : extraContact == "end outside cover" ? 1.1 : null); + var contact = new byte[67]; + junctionClass.TryWriteBytes(contact); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(contact, 35); + Add(7, 11, joint, WithGeometryRelations(contact, HostRelation(mine, memo), HostRelation(other, peerMemo))); + if (competingPriority > 0) + { + Guid competitor = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 8 * extent, 0, 2, 0.5, 0, + GeometryRelation(0x11, mine, competingJoint), material: 3); + Add(11, 11, competingJoint, WithGeometryRelations(contact, HostRelation(mine, competitor), HostRelation(other, peerMemo))); + } + if (secondCoverStart is { } start) + { + Guid second = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 8 * extent, 0, 2, halfWidth, 0, + GeometryRelation(0x11, other, secondCoverJoint), startX: start); + Add(11, 11, secondCoverJoint, WithGeometryRelations(contact, HostRelation(mine, memo), HostRelation(other, second))); + } + if (endJoint) + { + Guid branch = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 8 * extent, 1, 2, 0.25, 0, + GeometryRelation(0x11, mine, additionalJoint), transverse: true); + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(50), 1); + contact[66] = 1; + Add(11, 11, additionalJoint, WithGeometryRelations(contact, HostRelation(endRole, memo), HostRelation(mine, branch))); + } + if (slabCut) + { + Guid slab = Guid.NewGuid(); + var body = OpeningSlab(-1, extraContact == "slab above profile" ? 1.95 : 1.7, 0.1); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(191 + 73), 3); + WriteRectangularPlan(body.AsSpan(191 + 270), -0.125, -0.5, 0.125, 0.5, slab: true); + Add(8, 6, slab, WithGeometryRelations(body, GeometryRelation(0x11, slabBeam, additionalJoint))); + Add(9, 15, additionalJoint, WithGeometryRelations(slabJunctionClass.ToByteArray(), + HostRelation(beamSlab, peerMemo), HostRelation(slabBeam, slab))); + } + if (dimensionAttached) + Add(11, 16, dimension, WithGeometryRelations(dimensionClass.ToByteArray(), + HostRelation(dimensionRole, extraContact == "angular dimension" ? owner : Guid.NewGuid()))); + + using var document = Open(ClassTable((3, new Guid("c4191955-87c6-4fb6-b074-5f094fe9f6a6")), (4, storyClass), + (6, SlabClass), (7, materialClass), (8, layerClass), (9, BeamClass), (10, memoClass), (11, junctionClass), + (13, sectionClass), (14, shapeClass), (15, slabJunctionClass), (16, dimensionClass)), + OwnedDirectory(false, Guid.Empty, 12 * units, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(layerClass, 8, 1, 1), JunctionAttribute(materialClass, 7, 1, 700), + JunctionAttribute(materialClass, 7, 2, coveringPriority), JunctionAttribute(materialClass, 7, 3, slabCut ? 1100 : competingPriority), + Pool(pool)); + var beam = Assert.Single(document.ReadElements(), e => e.Guid == owner); + Assert.NotNull(beam.MemberProfile); + Assert.NotNull(beam.BeamReferenceAxis); + Assert.Null(beam.BoundingBox); + Assert.Null(beam.BottomElevationToHomeStory); + Assert.Equal(hasZeroVolume ? 0 : (double?)null, beam.BeamNetVolume); + + void Add(int index, ushort kind, Guid id, byte[] data) + { + Synthetic.Block(PlaBlockMode.Raw, data, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, index * extent); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)index * units, units, id)); + } + } + + [Theory] + [InlineData(Math.PI / 2, true, true)] + [InlineData(-Math.PI / 2, true, true)] + [InlineData(Math.PI / 2, false, true)] + [InlineData(Math.PI / 2, true, false)] + public void ReadsDirectedCircularBeamAxis(double sweep, bool matchingCaps, bool reciprocal) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"), memoKey = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid id = Guid.NewGuid(), memo = Guid.NewGuid(); + var placement = HorizontalBeam(BeamClass, -2, 0, 2, 0, 2, 0, 1); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(790), sweep); + double c = Math.Cos(sweep / 2), s = Math.Sin(sweep / 2); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(336), -c); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(344), matchingCaps ? s : -s); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(352), 1e-32); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(394), c); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(402), s); + var pool = new byte[3 * 1024]; + var body = WithGeometryRelations(placement, GeometryRelation(0x11, memoKey, memo)); + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: 9).CopyTo(pool, 0); + var linked = WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, reciprocal ? id : Guid.NewGuid())); + Synthetic.Block(PlaBlockMode.Raw, linked, ver: 1, guid: memo, extra: 1, kind: 10).CopyTo(pool, 2048); + using var document = Open(ClassTable((4, storyClass), (9, BeamClass), (10, memoClass)), + OwnedDirectory(false, Guid.Empty, 192, new ObjectDirectoryRecord(9, 0, 128, id), + new ObjectDirectoryRecord(10, 128, 64, memo)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), Pool(pool)); + var beam = Assert.Single(document.ReadElements()); + Assert.Null(beam.BoundingBox); + if (!matchingCaps || !reciprocal) + { + Assert.Null(beam.BeamReferenceAxis); + return; + } + var reference = Assert.IsType(beam.BeamReferenceAxis); + Assert.Equal(new PlaPlanPoint(-2, 0), reference.Start); + Assert.Equal(new PlaPlanPoint(2, 0), reference.End); + Assert.Equal(-2, reference.StartElevationToProjectZero); + Assert.Equal(-2, reference.EndElevationToProjectZero); + Assert.Equal(sweep, reference.PlanSweepRadians); + Assert.Equal(Math.PI * Math.Sqrt(2), reference.Length, 12); + Assert.Equal(0, reference.InclinationRadians); + } + + [Theory] + [InlineData("free")] + [InlineData("clockwise")] + [InlineData("major arc")] + [InlineData("straight joint")] + [InlineData("curved joint")] + [InlineData("near tangency")] + [InlineData("stale node")] + [InlineData("missing reciprocal")] + [InlineData("interior slab")] + [InlineData("slab at bottom")] + [InlineData("assembly")] + [InlineData("transformed member")] + public void ReadsEvaluatedCircularBeamBounds(string scenario) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"), memoKey = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid sectionClass = new("8825ae40-f827-4a57-a1c5-49d04c687c46"), sectionKey = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid shapeClass = new("f4cd2bd7-d4b1-4abf-b13c-59001907bbbd"), shapeKey = new("ca073b44-0655-407d-9715-1a019e628139"); + Guid junctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"), slabJunctionClass = new("7259c45f-97e3-434a-bc9e-fe3bcf980947"); + Guid ownRole = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"), peerRole = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid beamSlab = new("4df5ee09-8368-4f3b-ad64-056115b4c0ab"), slabBeam = new("d50bcd56-a71c-40f8-a3f1-551d14a4762b"); + Guid groupClass = new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d"), memberClass = new("47a28b23-f655-49fa-b219-1511ca52c49a"); + Guid groupKey = new("68236820-e176-4e8c-be39-d5d56a7a71c0"); + Guid own = Guid.NewGuid(), memo = Guid.NewGuid(), peer = Guid.NewGuid(), peerMemo = Guid.NewGuid(); + Guid joint = Guid.NewGuid(), duplicate = Guid.NewGuid(), group = Guid.NewGuid(), member = Guid.NewGuid(); + bool clockwise = scenario == "clockwise"; + bool major = scenario == "major arc"; + bool tangency = scenario is "near tangency" or "stale node"; + bool joined = tangency || scenario is "straight joint" or "curved joint" or "missing reciprocal"; + bool slabCut = scenario is "interior slab" or "slab at bottom"; + bool grouped = scenario is "assembly" or "transformed member"; + double sweep = clockwise ? -Math.PI / 2 : Math.PI / 2; + const int extent = 2048, units = extent / 16; + var pool = new byte[14 * extent]; + var entries = new List(); + double corner = 3 / Math.Sqrt(2); + var placement = major ? ArcBeam(new(-corner, -corner), new(-corner, corner), 3 * Math.PI / 2) + : ArcBeam(new(3, 0), new(0, clockwise ? -3 : 3), sweep); + AddProfiledBeam(own, memo, placement, + joined ? GeometryRelationList(1, ownRole, joint, duplicate) : slabCut ? GeometryRelation(0x11, beamSlab, joint) : [], + grouped ? GeometryRelationList(2, groupKey, group, member) : []); + if (grouped) + { + Add(17, group, WithGeometryRelations(groupClass.ToByteArray(), GeometryRelationList(1, groupKey, own))); + var body = new byte[84]; + memberClass.TryWriteBytes(body); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(60), scenario == "assembly" ? 0 : 0.2); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(76), 1); + Add(18, member, WithGeometryRelations(body, GeometryRelationList(4, groupKey, group, own))); + } + if (joined) + { + double c = Math.Sqrt(3) / 2; + bool curve = scenario == "curved joint"; + var end = curve ? new PlaPlanPoint(1.5 - 3 * c, 4.5 + 3 * c) + : tangency ? new(-4 * Math.Cos(1e-6), 3 - 4 * Math.Sin(1e-6)) : new(-4 * c, 5); + AddProfiledBeam(peer, peerMemo, ArcBeam(new(0, 3), end, curve ? -Math.PI / 2 : 0), + GeometryRelationList(1, peerRole, joint, scenario == "missing reciprocal" ? Guid.NewGuid() : duplicate), []); + AddJoint(joint); + AddJoint(duplicate); + } + if (slabCut) + { + Guid slab = Guid.NewGuid(); + var body = OpeningSlab(-1, scenario == "interior slab" ? 1.5 : 1.1, 0.2); + var settings = body.AsSpan(191); + WriteRectangularPlan(settings[270..], -1, -1, 4, 4, slab: true); + Add(6, slab, WithGeometryRelations(body, GeometryRelation(0x11, slabBeam, joint))); + Add(16, joint, WithGeometryRelations(slabJunctionClass.ToByteArray(), HostRelation(beamSlab, memo), HostRelation(slabBeam, slab))); + } + + using var document = Open(ClassTable((4, storyClass), (6, SlabClass), (7, materialClass), (8, layerClass), + (9, BeamClass), (10, memoClass), (12, junctionClass), (13, sectionClass), (14, shapeClass), + (16, slabJunctionClass), (17, groupClass), (18, memberClass)), + OwnedDirectory(false, Guid.Empty, 14 * units, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 100), JunctionAttribute(materialClass, 7, 2, 200), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var beam = Assert.Single(document.ReadElements(), e => e.Guid == own); + Assert.NotNull(beam.BeamReferenceAxis); + Assert.NotNull(beam.MemberProfile); + Assert.Null(beam.BeamNetVolume); + if (scenario is "missing reciprocal" or "slab at bottom" or "transformed member" or "stale node") + { + Assert.Null(beam.BoundingBox); + Assert.Null(beam.BottomElevationToProjectZero); + Assert.Null(beam.TopElevationToHomeStory); + return; + } + + double minX = major ? -corner : 0; + if (joined && !tangency) + { + // At the inner radius the end is an intersection of the two offset curves. + double c = Math.Sqrt(3) / 2; + if (scenario == "curved joint") + { + double dx = 1.5, dy = 3 + 3 * c, centerDistance = double.Hypot(dx, dy); + double along = (centerDistance * centerDistance - 12) / (2 * centerDistance); + minX = (dx * along - dy * Math.Sqrt(4 - along * along)) / centerDistance; + } + else + { + double along = 1 - 3 * c; + minX = -along / 2 - c * Math.Sqrt(4 - along * along); + } + } + var box = Assert.IsType(beam.BoundingBox); + Assert.Equal(minX, box.XMin, 10); + Assert.Equal(clockwise ? -4 : major ? -3 : 0, box.YMin, 10); + Assert.Equal(clockwise ? 4 : 3, box.XMax, 10); + Assert.Equal(clockwise ? 0 : 3, box.YMax, 10); + Assert.Equal(-3, box.ZMin, 10); + Assert.Equal(-1.5, box.ZMax, 10); + Assert.Equal(-3, beam.BottomElevationToProjectZero); + Assert.Equal(-1.5, beam.TopElevationToProjectZero); + Assert.Equal(1, beam.BottomElevationToHomeStory); + Assert.Equal(2.5, beam.TopElevationToHomeStory); + + static byte[] ArcBeam(PlaPlanPoint a, PlaPlanPoint b, double sweep) + { + var body = HorizontalBeam(BeamClass, a.X, a.Y, b.X, b.Y, 2, 0, 1); + double heading = Math.Atan2(b.Y - a.Y, b.X - a.X), half = sweep / 2; + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(336), -Math.Cos(heading - half)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(344), -Math.Sin(heading - half)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(394), Math.Cos(heading + half)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(402), Math.Sin(heading + half)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(790), sweep); + return body; + } + + void AddProfiledBeam(Guid owner, Guid id, byte[] body, byte[] contact, byte[] membership) + { + Guid section = Guid.NewGuid(), shape = Guid.NewGuid(); + Add(9, owner, WithGeometryRelations(body, GeometryRelation(0x11, memoKey, id), membership)); + Add(10, id, WithGeometryRelations(memoClass.ToByteArray(), HostRelation(memoKey, owner), + GeometryRelation(0x11, sectionKey, section), contact)); + Add(13, section, WithGeometryRelations(sectionClass.ToByteArray(), HostRelation(sectionKey, id), + GeometryRelation(0x11, shapeKey, shape))); + PlaProfilePoint[] ring = [new(0, -1), new(1, -1), new(1, 0.5), new(0, 0.5), new(0, -1)]; + byte[] hatch = SavedProfileHatch(1, 1, 0, ring); + var profile = new byte[528 + hatch.Length]; + shapeClass.TryWriteBytes(profile); + BinaryPrimitives.WriteUInt16LittleEndian(profile.AsSpan(47), 1); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(49), 12); + byte[] header = [2, 0, 9, 1]; + header.CopyTo(profile, 53); + header.CopyTo(profile, 392); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(396), profile.Length - 400); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(400), 128); + BinaryPrimitives.WriteInt32LittleEndian(profile.AsSpan(469), 1); + hatch.CopyTo(profile, 528); + Add(14, shape, WithGeometryRelations(profile, HostRelation(shapeKey, section))); + } + + void AddJoint(Guid id) + { + var body = new byte[67]; + junctionClass.TryWriteBytes(body); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(body, 35); + double travel = tangency ? 6 * Math.Sin(1e-6) : 0; + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(50), -travel * Math.Cos(1e-6)); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(58), 3 - travel * Math.Sin(1e-6) + + (scenario == "stale node" ? 1e-7 : 0)); + body[66] = 1; + Add(12, id, WithGeometryRelations(body, HostRelation(ownRole, memo), HostRelation(peerRole, peerMemo))); + } + + void Add(ushort kind, Guid id, byte[] data) + { + int index = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, data, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, index * extent); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)index * units, units, id)); + } + } + + [Theory] + [InlineData(false, false, true)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + public void PreservesSlantedBeamBoundsWhenAProfiledWallMissesBothCaps(bool curvedCut, bool stalePlan, bool retainsBounds) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"), memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + Guid wallProfileClass = new("462b6598-57f0-41a5-ae81-739c8f487e04"), profileRole = new("e63e7632-0efd-412d-8077-d3f3906b638a"); + Guid junctionClass = new("9eb0036e-2b99-4db1-b043-051fb1817f47"), wallBeam = new("b7a142a1-2e5f-4b17-9b52-40604fbc3828"); + Guid wall = Guid.NewGuid(), profile = Guid.NewGuid(), junction = Guid.NewGuid(); + byte[] pool = new byte[7 * 1024]; + var entries = new List(); + AddBeamCutFixture(pool, entries, wall, junction, 0, 0, 2, 0.25, 0, [], wallTarget: true, endElevation: 5); + + var wallBody = WallWithPlanes(1, -4); + var settings = wallBody.AsSpan(209); + BinaryPrimitives.WriteDoubleLittleEndian(settings, -2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[8..], -0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[24..], -0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[161..], 0); + BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 3); + WriteRectangularPlan(settings[256..], -2, -0.5, 2, stalePlan ? 0.125 : 0, slab: false); + Add(5, 1, wall, WithGeometryRelations(wallBody, GeometryRelation(0x11, wallBeam, junction), + GeometryRelation(0x11, profileRole, profile))); + + PlaProfilePoint[] ring = [new(0, 2.5), new(0.5, 2.5), new(0.5, 3.6), new(0, 3.6), new(0, 2.5)]; + byte[] hatch = SavedProfileHatch(1, 1, curvedCut ? 4 : 0, ring); + byte[] saved = new byte[530 + hatch.Length]; + wallProfileClass.TryWriteBytes(saved); + BinaryPrimitives.WriteUInt16LittleEndian(saved.AsSpan(49), 1); + BinaryPrimitives.WriteUInt32LittleEndian(saved.AsSpan(51), 12); + BinaryPrimitives.WriteUInt16LittleEndian(saved.AsSpan(55), 2); + new byte[] { 2, 0, 9, 1 }.CopyTo(saved, 394); + BinaryPrimitives.WriteInt32LittleEndian(saved.AsSpan(398), 128 + hatch.Length); + BinaryPrimitives.WriteInt32LittleEndian(saved.AsSpan(402), 128); + BinaryPrimitives.WriteInt32LittleEndian(saved.AsSpan(471), 1); + hatch.CopyTo(saved, 530); + Add(6, 2, profile, WithGeometryRelations(saved, HostRelation(profileRole, wall))); + + using var document = Open(ClassTable((1, WallClass), (2, wallProfileClass), (3, sectionClass), (4, storyClass), + (7, materialClass), (8, layerClass), (9, BeamClass), (10, memoClass), (11, junctionClass)), + OwnedDirectory(false, Guid.Empty, 7 * 64, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 1100), JunctionAttribute(materialClass, 7, 2, 1000), + JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var beam = Assert.Single(document.ReadElements(), e => e.Type == "Beam"); + Assert.Equal(retainsBounds ? new PlaBoundingBox(-2, -0.25, -3.25, 2, 0.25, 1) : null, beam.BoundingBox); + Assert.Equal(retainsBounds ? -3.25 : null, beam.BottomElevationToProjectZero); + Assert.Equal(retainsBounds ? 1.0 : null, beam.TopElevationToProjectZero); + Assert.Null(beam.BeamNetVolume); + + void Add(int index, ushort kind, Guid id, byte[] data) + { + Synthetic.Block(PlaBlockMode.Raw, data, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, index * 1024); + entries.Add(new ObjectDirectoryRecord(kind, (ulong)index * 64, 64, id)); + } + } + + [Theory] + [InlineData(0.25, true)] + [InlineData(2.25, false)] + public void VerifiesTheInclinedBeamButtPlaneAgainstTheFarJunction(double farBeamWidth, bool retainsBounds) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"), layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"), memoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + Guid junctionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid firstEnd = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"), secondEnd = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid through = new("89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid nearJoint = Guid.NewGuid(), duplicate = Guid.NewGuid(), farJoint = Guid.NewGuid(); + var pool = new byte[18 * 1024]; + var entries = new List(); + Guid slanted = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 0, 0, 2, 0.25, 0, + GeometryRelationList(1, secondEnd, nearJoint, duplicate), endX: 0, endElevation: 3.5); + Guid beamId = entries[0].ObjectId; + Guid flat = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 5 * 1024, 0, 3.625, 0.25, 0, + GeometryRelationList(1, firstEnd, nearJoint, duplicate, farJoint), startX: 0); + Guid far = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 10 * 1024, 2, 3.625, farBeamWidth, 0, + GeometryRelation(0x11, through, farJoint), transverse: true); + AddJoint(15, nearJoint, 0, firstEnd, flat, secondEnd, slanted); + AddJoint(16, duplicate, 0, firstEnd, flat, secondEnd, slanted); + AddJoint(17, farJoint, 2, firstEnd, flat, through, far); + + using var document = Open(ClassTable((3, sectionClass), (4, storyClass), (7, materialClass), (8, layerClass), + (9, BeamClass), (10, memoClass), (12, junctionClass)), + OwnedDirectory(false, Guid.Empty, 18 * 64, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 2, 1000), JunctionAttribute(layerClass, 8, 1, 1), Pool(pool)); + var beam = Assert.Single(document.ReadElements(), e => e.Guid == beamId); + Assert.Equal(retainsBounds ? new PlaBoundingBox(-2, -0.25, -3.25, 0, 0.25, -0.5) : null, beam.BoundingBox); + Assert.Null(beam.BottomElevationToProjectZero); + Assert.Null(beam.TopElevationToProjectZero); + Assert.Null(beam.BeamNetVolume); + + void AddJoint(int slot, Guid id, double x, Guid firstRole, Guid first, Guid secondRole, Guid second) + { + byte[] node = new byte[67]; + junctionClass.TryWriteBytes(node); + new byte[] { 28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0 }.CopyTo(node, 35); + BinaryPrimitives.WriteDoubleLittleEndian(node.AsSpan(50), x); + node[66] = 1; + var payload = WithGeometryRelations(node, HostRelation(firstRole, first), HostRelation(secondRole, second)); + Synthetic.Block(PlaBlockMode.Raw, payload, ver: 1, guid: id, extra: 1, kind: 12).CopyTo(pool, slot * 1024); + entries.Add(new ObjectDirectoryRecord(12, (ulong)slot * 64, 64, id)); + } + } + + [Theory] + [InlineData(false, 800, true, true)] + [InlineData(true, 800, true, true)] + [InlineData(true, 1000, true, false)] + [InlineData(false, 1200, true, false)] + [InlineData(false, 800, false, false)] + [InlineData(true, 1000, true, true, 1)] + [InlineData(true, 1000, true, false, 2)] + [InlineData(false, 1200, true, true, 1)] + [InlineData(false, 1200, true, true, 3)] + [InlineData(false, 1200, true, true, 4)] + [InlineData(false, 1000, true, true, 4)] + [InlineData(true, 1000, true, true, 5)] + [InlineData(true, 1000, true, false, 6)] + [InlineData(false, 1200, true, true, 7)] + [InlineData(false, 1200, true, false, 8)] + [InlineData(false, 1200, true, true, 9)] + [InlineData(false, 1200, true, false, 10)] + [InlineData(false, 800, true, true, 11)] + [InlineData(false, 1200, true, true, 12)] + [InlineData(false, 1200, true, false, 13)] + [InlineData(true, 1200, true, true, 14)] + [InlineData(true, 1200, false, false, 14)] + [InlineData(true, 1200, true, false, 15)] + [InlineData(true, 1200, true, true, 16)] + [InlineData(true, 1200, true, false, 17)] + [InlineData(true, 1200, true, false, 18)] + [InlineData(true, 1200, true, false, 19)] + [InlineData(true, 1200, true, false, 20)] + public void ReadsWallPlanesWhoseJunctionCannotCutThem(bool attachedWall, int neighborPriority, bool reciprocal, bool supported, + int stripCase = 0) + { + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid junctionClass = new(attachedWall ? "68122649-d152-4046-8c2d-8880dfd880bf" : "324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid wallJunction = new(attachedWall ? "0e7a0206-f853-4c86-9f9e-43266b0ab58a" : "88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid neighborJunction = new(attachedWall ? "df61b698-e5ca-45bf-99fd-0e574a5e54d5" : "ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid contourClass = new("5f7c9d0d-a84b-4240-a67d-f1458abafd0e"); + Guid compositeClass = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid contourRelation = new("e6e5e667-9577-41ca-bf4a-da75b917513f"); + Guid wallId = Guid.NewGuid(), neighborId = Guid.NewGuid(), junctionId = Guid.NewGuid(); + Guid contourId = Guid.NewGuid(), neighborContour = Guid.NewGuid(), pointId = Guid.NewGuid(); + Guid pointClass = new("3367fbd4-7f06-4cef-bd01-09c83d399855"); + Guid pointRelation = new("90b557ed-5803-411b-af47-ef97d9d3e31e"); + Guid annotationClass = new("5793eecb-32e2-4fdd-b216-739ff6c806c4"); + Guid annotationRelation = new("386bc4fb-ea34-4287-8067-4f16b966b7af"); + Guid annotation = Guid.NewGuid(); + bool inlinePlan = stripCase is 14 or 15; + bool collinear = stripCase is 5 or 6; + bool butt = stripCase is 16 or 17; + bool overlap = stripCase is 18 or 19 or 20; + bool needsContour = stripCase == 3 || collinear; + byte[] pool = new byte[(collinear || butt ? 6 : 4) * 1024]; + var wall = WithGeometryRelations(WallWithPlanes(1, -3.75), GeometryRelation(0x11, wallJunction, junctionId), + needsContour ? GeometryRelation(0x11, contourRelation, contourId) : [], + inlinePlan ? GeometryRelationList(1, annotationRelation, annotation) : [], + inlinePlan ? GeometryRelation(0x11, new("7306b00e-ff8d-4051-a8b3-f76cfc597704"), Guid.NewGuid()) : []); + var neighbor = WithGeometryRelations(attachedWall ? WallWithPlanes(2, -3.75) : RectangularSlab(stripCase != 12, stripCase), + GeometryRelation(0x11, neighborJunction, reciprocal ? junctionId : Guid.NewGuid()), + collinear ? GeometryRelation(0x11, contourRelation, neighborContour) : []); + if (stripCase != 0) + { + WriteWallStrip(wall.AsSpan(209), alongX: true, 0.125); + if (attachedWall) + WriteWallStrip(neighbor.AsSpan(209), alongX: collinear || butt || overlap, stripCase == 2 ? 0.75 : 0.125); + } + if (needsContour) + { + wall.AsSpan(209 + 515, 48).Clear(); + WriteContour(-0.5, 0.5, wallId, contourId, 3072); + } + if (inlinePlan) + { + WriteInlinePlan(wall.AsSpan(209), alongX: true); + WriteInlinePlan(neighbor.AsSpan(209), alongX: false); + var body = WithGeometryRelations(annotationClass.ToByteArray(), + HostRelation(annotationRelation, stripCase == 14 ? wallId : neighborId)); + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: annotation, extra: 1, kind: 12).CopyTo(pool, 3072); + } + if (collinear) + { + BinaryPrimitives.WriteDoubleLittleEndian(neighbor.AsSpan(209), -0.25); + BinaryPrimitives.WriteDoubleLittleEndian(neighbor.AsSpan(225), 0.75); + neighbor.AsSpan(209 + 515, 48).Clear(); + WriteContour(-0.25, 0.75, neighborId, neighborContour, 4096); + } + if (butt) + { + const double offset = 1.5e-7; + var settings = neighbor.AsSpan(209); + BinaryPrimitives.WriteDoubleLittleEndian(settings, 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], 1.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[8..], offset); + BinaryPrimitives.WriteDoubleLittleEndian(settings[24..], offset); + BinaryPrimitives.WriteDoubleLittleEndian(settings[515..], 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[531..], 1.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[523..], -0.125 + offset); + BinaryPrimitives.WriteDoubleLittleEndian(settings[539..], 0.125 + offset); + } + if (overlap) + { + var settings = neighbor.AsSpan(209); + double peerBottom = stripCase == 20 ? 2.25 : -0.75; + BinaryPrimitives.WriteDoubleLittleEndian(settings[153..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[161..], peerBottom); + BinaryPrimitives.WriteDoubleLittleEndian(settings[547..], peerBottom - 4); + BinaryPrimitives.WriteDoubleLittleEndian(settings[555..], peerBottom - 2); + if (stripCase != 19) new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(settings[489..]); + } + if (collinear || butt) + { + var point = new byte[62]; + pointClass.TryWriteBytes(point); + BinaryPrimitives.WriteDoubleLittleEndian(point.AsSpan(46), stripCase switch { 5 => -0.25, 16 => 0.5, 17 => 0.25, _ => -0.5 }); + Synthetic.Block(PlaBlockMode.Raw, point, ver: 1, guid: pointId, extra: 1, kind: 11).CopyTo(pool, 5120); + } + + void WriteContour(double from, double to, Guid owner, Guid id, int offset) + { + byte[] contour = new byte[44 + 161]; + contourClass.TryWriteBytes(contour); + WriteRectangularPlan(contour.AsSpan(44), from, -0.125, to, 0.125, slab: false); + contour = WithGeometryRelations(contour, HostRelation(contourRelation, owner)); + Synthetic.Block(PlaBlockMode.Raw, contour, ver: 1, guid: id, extra: 1, kind: 9).CopyTo(pool, offset); + } + + static void WriteInlinePlan(Span settings, bool alongX) + { + new byte[] { 1, 0, 1, 0, 0, 0 }.CopyTo(settings[489..]); + settings[515..563].Clear(); + BinaryPrimitives.WriteDoubleLittleEndian(settings[243..], 0.125); + var polygon = settings[256..]; + WriteRectangularPlan(polygon, alongX ? -0.5 : -0.125, alongX ? -0.125 : -0.5, + alongX ? 0.5 : 0.125, alongX ? 0.125 : 0.5, slab: false); + if (!alongX) + { + var first = polygon.Slice(71, 16).ToArray(); + polygon.Slice(87, 64).CopyTo(polygon[71..]); + first.CopyTo(polygon[119..]); + polygon.Slice(71, 16).CopyTo(polygon[135..]); + } + } + + bool compositeSlab = stripCase is 4 or (>= 9 and <= 13); + if (compositeSlab) + { + var settings = neighbor.AsSpan(191); + BinaryPrimitives.WriteDoubleLittleEndian(settings, stripCase == 9 ? 1 : 3.25); + if (stripCase == 10) BinaryPrimitives.WriteDoubleLittleEndian(settings[17..], 0.875); + BinaryPrimitives.WriteUInt16LittleEndian(settings[83..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[87..], 1); + } + byte[] contact = new byte[62]; + junctionClass.TryWriteBytes(contact); + contact = WithGeometryRelations(contact, HostRelation(wallJunction, wallId), HostRelation(neighborJunction, neighborId), + collinear || butt ? HostRelation(pointRelation, pointId) : []); + Synthetic.Block(PlaBlockMode.Raw, wall, ver: 1, guid: wallId, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, neighbor, ver: 1, guid: neighborId, extra: 1, kind: attachedWall ? (ushort)1 : (ushort)2).CopyTo(pool, 1024); + Synthetic.Block(PlaBlockMode.Raw, contact, ver: 1, guid: junctionId, extra: 1, kind: 3).CopyTo(pool, 2048); + var records = new List + { + new(1, 0, 64, wallId), new(attachedWall ? (ushort)1 : (ushort)2, 64, 64, neighborId), new(3, 128, 64, junctionId), + }; + if (needsContour) records.Add(new(9, 192, 64, contourId)); + if (collinear) records.Add(new(9, 256, 64, neighborContour)); + if (collinear || butt) records.Add(new(11, 320, 64, pointId)); + if (inlinePlan) records.Add(new(12, 192, 64, annotation)); + using var doc = Open(ClassTable((1, WallClass), (2, SlabClass), (3, junctionClass), (4, storyClass), + (7, materialClass), (8, layerClass), (9, contourClass), (10, compositeClass), (11, pointClass), (12, annotationClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, records.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 1000), + JunctionAttribute(materialClass, 7, 2, (uint)neighborPriority), + JunctionAttribute(materialClass, 7, 3, 800), + JunctionAttribute(layerClass, 8, 1, 1), + CompositeForWallTest(compositeClass, splitCuts: stripCase == 13), + Pool(pool)); + + var element = Assert.Single(doc.ReadElements(), x => x.Guid == wallId); + double bottom = stripCase switch { 9 => 0.75, 1 or 3 or 7 when !attachedWall => 0.5, _ => 0.25 }; + double top = stripCase == 4 ? 2.5 : 3.25; + bool readsBottom = supported || stripCase == 20; + bool readsTop = supported || stripCase == 18; + Assert.Equal(readsBottom ? bottom : null, element.BottomElevationToHomeStory); + Assert.Equal(readsTop ? top : null, element.TopElevationToHomeStory); + Assert.Equal(readsBottom ? -4 + bottom : null, element.BottomElevationToProjectZero); + Assert.Equal(readsTop ? -4 + top : null, element.TopElevationToProjectZero); + if (attachedWall && stripCase is 5 or 6) + Assert.Equal(supported ? new PlaBoundingBox(-0.5, -0.125, -3.75, 0.5, 0.125, -0.75) : null, + element.BoundingBox); + } + + private static byte[] CompositeForWallTest(Guid compositeClass, bool splitCuts, ushort kind = 10, + byte[]? skinFunctions = null, (double Outer, double Core)? thickness = null) + { + byte[] attribute = new byte[61 + 45 + 3 * 23]; + compositeClass.TryWriteBytes(attribute); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(attribute, 47); + BinaryPrimitives.WriteUInt32LittleEndian(attribute.AsSpan(55), 1); + BinaryPrimitives.WriteUInt16LittleEndian(attribute.AsSpan(59), 'A'); + var body = attribute.AsSpan(61); + BinaryPrimitives.WriteUInt16LittleEndian(body, 1); + BinaryPrimitives.WriteInt32LittleEndian(body[2..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(body[43..], 3); + ushort outerMaterial = splitCuts ? (ushort)2 : (ushort)3; + ushort innerMaterial = splitCuts ? (ushort)3 : (ushort)2; + BinaryPrimitives.WriteUInt16LittleEndian(body[53..], outerMaterial); + BinaryPrimitives.WriteDoubleLittleEndian(body[60..], thickness?.Outer ?? 0.25); + BinaryPrimitives.WriteUInt16LittleEndian(body[76..], innerMaterial); + BinaryPrimitives.WriteDoubleLittleEndian(body[83..], thickness?.Core ?? 0.5); + BinaryPrimitives.WriteUInt16LittleEndian(body[99..], outerMaterial); + BinaryPrimitives.WriteDoubleLittleEndian(body[106..], thickness?.Outer ?? 0.25); + if (skinFunctions is not null) + { + BinaryPrimitives.WriteDoubleLittleEndian(body[35..], 1); + for (int i = 0; i < skinFunctions.Length; i++) + { + var skin = body[(45 + i * 23)..]; + new byte[] { 5, 1, 17, 0, 0, 0, 1, 0 }.CopyTo(skin); + skin[14] = skinFunctions[i]; + } + } + return Synthetic.Block(PlaBlockMode.Raw, attribute, ver: 1, kind: kind); + } + + [Theory] + [InlineData(0, 2.5)] + [InlineData(1, null)] + [InlineData(2, null)] + [InlineData(3, null)] + [InlineData(4, null)] + [InlineData(5, 2.125)] + [InlineData(6, null)] + [InlineData(7, 2.5)] + [InlineData(8, 2.125)] + [InlineData(9, null)] + [InlineData(10, 2.25)] + [InlineData(11, 2.125)] + [InlineData(12, null)] + [InlineData(13, null)] + [InlineData(14, 3.25, 1)] + [InlineData(15, 2.5)] + [InlineData(16, null)] + [InlineData(17, null)] + [InlineData(18, 2.5)] + [InlineData(19, 2.5)] + [InlineData(20, null)] + [InlineData(21, 2.5, 0.5)] + [InlineData(22, null)] + [InlineData(23, null)] + [InlineData(24, 2.5)] + [InlineData(25, 2.5)] + [InlineData(26, null)] + [InlineData(27, 2.5)] + [InlineData(28, null)] + [InlineData(29, null)] + [InlineData(30, 2.5)] + [InlineData(31, null)] + [InlineData(32, null)] + [InlineData(33, 2.5)] + [InlineData(34, null)] + [InlineData(35, null)] + [InlineData(36, 2.5)] + public void CutsJoinedWallOnlyWhereCompositeSlabKeepsCoverage(int variation, double? top, double bottom = 0.25) + { + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid material = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layer = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid composite = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid wallSlabClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid wallJoinClass = new("68122649-d152-4046-8c2d-8880dfd880bf"); + Guid pointClass = new("3367fbd4-7f06-4cef-bd01-09c83d399855"); + Guid beamSlabClass = new("7259c45f-97e3-434a-bc9e-fe3bcf980947"); + Guid beamPairClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + Guid firstBeamEnd = new("59655252-b20b-47a7-9d4a-27a2f2bf2c73"); + Guid secondBeamEnd = new("1dae4518-b353-42bc-bcb1-d037bcc603d6"); + Guid wallSlab = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slabWall = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid wallEnd = new("0e7a0206-f853-4c86-9f9e-43266b0ab58a"); + Guid peerEnd = new("df61b698-e5ca-45bf-99fd-0e574a5e54d5"); + if (variation == 7) peerEnd = wallEnd; + Guid junctionPoint = new("90b557ed-5803-411b-af47-ef97d9d3e31e"); + Guid slabBeam = new("d50bcd56-a71c-40f8-a3f1-551d14a4762b"); + Guid beamSlab = new("4df5ee09-8368-4f3b-ad64-056115b4c0ab"); + Guid wallBeam = new("b7a142a1-2e5f-4b17-9b52-40604fbc3828"); + Guid operationClass = new("47a28b23-f655-49fa-b219-1511ca52c49a"); + Guid solidRole = new("68236820-e176-4e8c-be39-d5d56a7a71c0"); + Guid operationId = Guid.NewGuid(); + Guid levelDimensionClass = new("690878fa-b11f-46c9-953c-3864d85bdee6"); + Guid slabDimension = new("9176a8c6-f502-440f-8ef3-f0a700178e4a"); + Guid wall = Guid.NewGuid(), peer = Guid.NewGuid(), slab = Guid.NewGuid(), point = Guid.NewGuid(); + Guid targetCut = Guid.NewGuid(), peerCut = Guid.NewGuid(), wallJoin = Guid.NewGuid(), beamJoin = Guid.NewGuid(); + Guid beamCut = Guid.NewGuid(), secondBeamCut = Guid.NewGuid(), secondBeamJoin = Guid.NewGuid(), pair = Guid.NewGuid(); + Guid foundation = Guid.NewGuid(), foundationCut = Guid.NewGuid(); + Guid additionalCut = Guid.NewGuid(); + bool repeatedSlab = variation is >= 33 and <= 35; + bool sharedBeams = variation is >= 21 and <= 23; + bool twoBeams = variation is >= 8 and <= 14 || sharedBeams, corner = variation is 11 or 12 or 13, cutsBottom = variation == 14; + bool remoteBeamJoin = variation is >= 15 and <= 20 or 24; + bool beamCutsWall = variation is 5 or 6 || twoBeams; + Guid dimension = Guid.NewGuid(); + byte[] pool = new byte[(sharedBeams ? 25 : twoBeams || remoteBeamJoin ? 23 : 18) * 1024]; + var entries = new List(); + var target = WallWithPlanes(1, -3.75); + WriteWallStrip(target.AsSpan(209), alongX: true, 0.125); + bool peerOperation = variation is >= 30 and <= 32; + var neighbor = WallWithPlanes(variation == 4 || peerOperation ? 4 : 1, peerOperation ? -0.5 : -3.75); + var peerSettings = neighbor.AsSpan(209); + bool oblique = variation is >= 27 and <= 32; + if (peerOperation) BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[161..], 3.5); + if (variation is 25 or 26 or 36) + { + WriteWallStrip(peerSettings, alongX: true, 0.25); + double start = variation == 26 ? 0.25 : 0.5; + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings, start); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[16..], 1.5); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[515..], start); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[531..], 1.5); + if (variation == 36) + { + const double transverseOffset = 1.5e-7; + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[8..], transverseOffset); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[24..], transverseOffset); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[523..], -0.25 + transverseOffset); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[539..], 0.25 + transverseOffset); + } + } + else if (oblique) + { + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings, 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[16..], 0.8); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[24..], 0.4); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[77..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[85..], 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[194..], Math.PI / 2); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[243..], 0.125); + var polygon = peerSettings[256..]; + WriteRectangularPlan(polygon, 0.4, -0.075, 0.9, 0.475, slab: false); + (double X, double Y)[] vertices = [(0.6, -0.075), (0.9, 0.325), (0.7, 0.475), (0.4, 0.075), (0.6, -0.075)]; + for (int i = 0; i < vertices.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(71 + 16 * i)..], vertices[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(79 + 16 * i)..], vertices[i].Y); + } + } + else + { + WriteWallStrip(peerSettings, alongX: false, 0.125); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings, 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[16..], variation == 7 ? 0.5 + 1e-12 : 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[515..], 0.375); + BinaryPrimitives.WriteDoubleLittleEndian(peerSettings[531..], 0.625); + } + var floor = sharedBeams ? OpeningSlab(0, -0.75, 1) : RectangularSlab(true); + if (sharedBeams) Array.Resize(ref floor, 191 + 270 + 247 + 16 + 4 * 27); + WriteLocation(floor.AsSpan(163), 1, 0); + var settings = floor.AsSpan(191); + BinaryPrimitives.WriteDoubleLittleEndian(settings, cutsBottom ? -3 : -0.75); + BinaryPrimitives.WriteUInt16LittleEndian(settings[83..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[87..], 1); + double slabEnd = remoteBeamJoin ? 3 : variation == 1 ? 0.5 : oblique && variation != 28 ? 1 : 0.625; + WriteRectangularPlan(settings[270..], -1, -1, slabEnd, 1, slab: true); + var xy = new byte[62]; + pointClass.TryWriteBytes(xy); + BinaryPrimitives.WriteDoubleLittleEndian(xy.AsSpan(46), variation == 2 ? 0.75 : 0.5); + if (variation == 29) BinaryPrimitives.WriteDoubleLittleEndian(xy.AsSpan(54), 0.01); + Add(0, 1, wall, WithGeometryRelations(target, + twoBeams && variation != 22 ? GeometryRelationList(1, wallBeam, beamCut, secondBeamCut) : + beamCutsWall ? GeometryRelation(0x11, wallBeam, beamCut) : [], + sharedBeams ? GeometryRelationList(1, wallSlab, targetCut, foundationCut) : + repeatedSlab ? GeometryRelationList(1, wallSlab, targetCut, additionalCut) : GeometryRelation(0x11, wallSlab, targetCut), + GeometryRelation(0x11, wallEnd, wallJoin))); + Add(1, 1, peer, WithGeometryRelations(neighbor, GeometryRelation(0x11, peerEnd, wallJoin), + GeometryRelation(0x11, wallSlab, peerCut), + peerOperation ? GeometryRelationList(1, solidRole, slab, operationId) : [])); + Add(2, 2, slab, WithGeometryRelations(floor, repeatedSlab && variation != 34 ? + GeometryRelationList(1, slabWall, targetCut, peerCut, additionalCut) : GeometryRelationList(1, slabWall, targetCut, peerCut), + twoBeams ? GeometryRelationList(1, slabBeam, beamJoin, secondBeamJoin) : GeometryRelation(0x11, slabBeam, beamJoin), + GeometryRelation(0x11, slabDimension, dimension), + peerOperation && variation != 32 ? GeometryRelationList(2, solidRole, peer, operationId) : [])); + Add(3, 5, targetCut, WithGeometryRelations(wallSlabClass.ToByteArray(), HostRelation(wallSlab, wall), HostRelation(slabWall, slab))); + Add(4, 5, peerCut, WithGeometryRelations(wallSlabClass.ToByteArray(), HostRelation(wallSlab, peer), HostRelation(slabWall, slab))); + Add(5, 6, wallJoin, WithGeometryRelations(wallJoinClass.ToByteArray(), + variation == 7 ? GeometryRelationList(2, wallEnd, wall, peer) : HostRelation(wallEnd, wall), + variation == 7 ? [] : HostRelation(peerEnd, peer), HostRelation(junctionPoint, point))); + Add(6, 12, point, xy); + if (repeatedSlab) + Add(7, 5, additionalCut, WithGeometryRelations(wallSlabClass.ToByteArray(), + HostRelation(wallSlab, variation == 35 ? peer : wall), HostRelation(slabWall, slab))); + if (peerOperation) + { + var memo = new byte[84]; + operationClass.TryWriteBytes(memo); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(52), variation == 31 ? 5u : 1u); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(56), 1); + Add(7, 17, operationId, WithGeometryRelations(memo, GeometryRelationList(4, solidRole, peer, slab))); + } + if (sharedBeams) + { + var lower = OpeningSlab(0, -3.5, 1); + Add(23, 2, foundation, WithGeometryRelations(lower, GeometryRelation(0x11, slabWall, foundationCut))); + Add(24, 5, foundationCut, WithGeometryRelations(wallSlabClass.ToByteArray(), + HostRelation(wallSlab, wall), HostRelation(slabWall, foundation))); + } + double offset = variation == 9 ? 0.1 : 0.0625; + double cornerY = variation == 13 ? -0.0625 : -0.125; + double beamY = sharedBeams ? -0.25 : corner ? cornerY : + twoBeams ? -offset : variation == 3 || beamCutsWall || remoteBeamJoin ? 0 : 0.75; + double beamTop = cutsBottom ? 1 : 3.125; + double halfWidth = sharedBeams ? variation == 23 ? 0.26 : 0.1 : + corner ? 0.25 : twoBeams ? 0.075 : variation == 6 ? 0.1 : 0.125; + double startX = remoteBeamJoin ? variation == 17 ? 0.75 : 1.5 : -2; + Guid beam = AddBeamCutFixture(pool, entries, beamCutsWall ? wall : Guid.Empty, beamCut, 8 * 1024, beamY, beamTop, + halfWidth, 0, Synthetic.Concat(GeometryRelation(0x11, beamSlab, beamJoin), + corner || remoteBeamJoin ? GeometryRelation(0x11, firstBeamEnd, pair) : []), + wallTarget: beamCutsWall, transverse: sharedBeams, endX: corner ? 0 : null, startX: startX); + Add(13, 13, beamJoin, WithGeometryRelations(beamSlabClass.ToByteArray(), HostRelation(slabBeam, slab), HostRelation(beamSlab, beam))); + Add(14, 14, dimension, WithGeometryRelations(levelDimensionClass.ToByteArray(), HostRelation(slabDimension, slab))); + if (twoBeams) + { + Guid second = AddBeamCutFixture(pool, entries, wall, secondBeamCut, 15 * 1024, sharedBeams ? 0.25 : corner ? 0 : offset, + variation == 10 ? 3.25 : beamTop, sharedBeams ? halfWidth : corner ? 0.75 : 0.075, 0, + Synthetic.Concat(GeometryRelation(0x11, beamSlab, secondBeamJoin), + corner ? GeometryRelation(0x11, secondBeamEnd, pair) : []), + wallTarget: true, transverse: corner || sharedBeams, material: variation == 12 ? 4u : 2u, startY: corner ? cornerY : -2); + Add(20, 13, secondBeamJoin, WithGeometryRelations(beamSlabClass.ToByteArray(), HostRelation(slabBeam, slab), + HostRelation(beamSlab, second))); + if (corner) AddPair(second, 0, cornerY); + } + if (remoteBeamJoin) + { + double peerWidth = variation >= 18 ? halfWidth : 0.25; + double? peerX = variation switch { 18 or 24 => startX + 1, 19 => startX - 0.5, 20 => startX + 0.5, _ => null }; + double peerTop = variation == 24 ? beamTop + 2e-8 : beamTop; + Guid second = AddBeamCutFixture(pool, entries, Guid.Empty, Guid.Empty, 15 * 1024, peerX is null ? startX : beamY, peerTop, + peerWidth, 0, variation == 16 ? [] : GeometryRelation(0x11, secondBeamEnd, pair), + transverse: peerX is null, startY: beamY, startX: startX, endX: peerX, + endY: variation is 19 or 20 ? beamY : 2); + AddPair(second, startX, beamY); + } + using var doc = Open(ClassTable((1, WallClass), (2, SlabClass), (3, new Guid("c4191955-87c6-4fb6-b074-5f094fe9f6a6")), + (4, story), (5, wallSlabClass), (6, wallJoinClass), (7, material), (8, layer), + (9, new Guid("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")), (10, new Guid("cbab7bc6-e03a-4133-9161-c28ed3368672")), + (11, new Guid("9eb0036e-2b99-4db1-b043-051fb1817f47")), (12, pointClass), (13, beamSlabClass), + (14, levelDimensionClass), (15, composite), (16, beamPairClass), (17, operationClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), + JunctionAttribute(material, 7, 1, 1000), JunctionAttribute(material, 7, 2, 1200), + JunctionAttribute(material, 7, 3, 800), JunctionAttribute(material, 7, 4, 1300), + JunctionAttribute(layer, 8, 1, 1), CompositeForWallTest(composite, splitCuts: false, kind: 15), + Pool(pool)); + var result = Assert.Single(doc.ReadElements(), x => x.Guid == wall); + Assert.Equal(top.HasValue ? bottom : null, result.BottomElevationToHomeStory); + Assert.Equal(top, result.TopElevationToHomeStory); + Assert.Equal(top.HasValue ? bottom - 4 : null, result.BottomElevationToProjectZero); + Assert.Equal(top - 4, result.TopElevationToProjectZero); + + void AddPair(Guid second, double x, double y) + { + var junction = new byte[67]; + beamPairClass.TryWriteBytes(junction); + byte[] frame = [28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0]; + frame.CopyTo(junction, 35); + BinaryPrimitives.WriteDoubleLittleEndian(junction.AsSpan(50), x); + BinaryPrimitives.WriteDoubleLittleEndian(junction.AsSpan(58), y); + junction[66] = 1; + Add(21, 16, pair, WithGeometryRelations(junction, HostRelation(firstBeamEnd, beam), HostRelation(secondBeamEnd, second))); + } + + void Add(int slot, ushort kind, Guid id, byte[] body) + { + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * 1024); + entries.Add(new(kind, (ulong)slot * 64, 64, id)); + } + } + + [Theory] + [InlineData(false, false, 2.75)] + [InlineData(true, false, 2.75)] + [InlineData(false, true, null)] + [InlineData(false, false, null, false)] + [InlineData(false, false, 2.75, true, 1)] + [InlineData(false, false, null, true, 2)] + [InlineData(false, false, null, true, 3)] + [InlineData(false, false, 2.75, true, 4)] + [InlineData(false, false, 2.75, true, 5)] + [InlineData(false, false, null, true, 6)] + [InlineData(false, false, null, true, 7)] + [InlineData(false, false, 2.75, true, 0, 1)] + [InlineData(false, false, 2.75, true, 0, 2)] + [InlineData(true, false, 2.75, true, 0, 0, 1)] + [InlineData(true, false, null, true, 0, 0, 2)] + [InlineData(true, false, null, true, 0, 0, 3)] + [InlineData(true, false, 2.75, true, 0, 0, 4)] + public void CompositeSlabsCutThroughAllWallSkinsAtEachEnd(bool cutBothEnds, bool beveled, double? top, + bool labelMatches = true, int openingCase = 0, int labelStorage = 0, int columnCase = 0) + { + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid material = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layer = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid composite = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid junctionClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid wallSlab = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slabWall = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid labelClass = new("1601b50c-a61f-447c-8b74-0f578c003d88"); + Guid labelRole = new("5dd68b40-d2b2-4e13-9238-8343cdb6c423"); + Guid openingClass = new("6746aa79-7498-4bea-bad8-191cdad31d05"); + Guid cutClass = new("9a756127-8689-486d-8873-5c1d7b0f8785"); + Guid hostRole = new("49f5b35f-3e0e-4644-a659-d024c2c93228"); + Guid openingRole = new("219fcd20-e2ef-4e61-bb1b-a771897ff878"); + Guid targetRole = new("fc9598c9-7004-45ef-93e0-8fdcbc306acf"); + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"); + Guid columnMemoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid columnSectionClass = new("d6c12939-d905-40e0-aa57-f7c8d687dc7b"); + Guid slabColumnClass = new("d5381783-6a19-4de8-9e52-2e04a3978db0"); + Guid columnMemoRole = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"); + Guid sectionRole = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid slabColumnRole = new("f6ee0d9c-27ad-44d0-824f-682969bb171e"); + Guid columnSlabRole = new("87811dc4-1686-45f4-b1a6-dfaa81da44e4"); + Guid wall = Guid.NewGuid(), upper = Guid.NewGuid(), lower = Guid.NewGuid(); + Guid upperJoint = Guid.NewGuid(), lowerJoint = Guid.NewGuid(), label = Guid.NewGuid(); + Guid opening = Guid.NewGuid(), cut = Guid.NewGuid(); + Guid slabColumnJoint = Guid.NewGuid(); + var target = WallWithPlanes(columnCase == 4 ? 2 : 1, -3.75); + var settings = target.AsSpan(209); + WriteWallStrip(settings, alongX: true, 0.5); + if (columnCase != 4) BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[229..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[243..], 0.5); + WriteRectangularPlan(settings[256..], -0.5, -0.5, 0.5, 0.5, slab: false); + const int slotSize = 2048; + var pool = new byte[(columnCase == 0 ? 8 : 12) * slotSize]; + var entries = new List(); + Add(1, wall, WithGeometryRelations(target, cutBothEnds ? GeometryRelationList(1, wallSlab, lowerJoint, upperJoint) : + GeometryRelation(0x11, wallSlab, upperJoint))); + AddSlab(upper, upperJoint, -0.5, beveled ? 0 : -1); + if (cutBothEnds) AddSlab(lower, lowerJoint, columnCase == 0 ? -3 : -3.25, -1); + var labelBody = WithGeometryRelations(labelClass.ToByteArray(), HostRelation(labelRole, labelMatches ? upper : lower)); + if (labelStorage == 0) Add(10, label, labelBody); + if (labelStorage == 2) entries.Add(new(10, (ulong)entries.Count * (slotSize / 16), slotSize / 16, label)); + if (openingCase != 0) + { + var openingSettings = OpeningSettings(openingCase >= 5 ? 2u : 1u, 0.2, 0.2); + double offset = openingCase switch { 1 or 3 or 5 => 0.5, 7 => 0.3502, _ => 0 }; + BinaryPrimitives.WriteDoubleLittleEndian(openingSettings.AsSpan(134), offset); + BinaryPrimitives.WriteDoubleLittleEndian(openingSettings.AsSpan(158), 1); + BinaryPrimitives.WriteDoubleLittleEndian(openingSettings.AsSpan(190), 1); + BinaryPrimitives.WriteDoubleLittleEndian(openingSettings.AsSpan(222), 1); + if (openingCase == 4) + { + BinaryPrimitives.WriteUInt32LittleEndian(openingSettings.AsSpan(278), 2); + BinaryPrimitives.WriteDoubleLittleEndian(openingSettings.AsSpan(282), -0.125); + } + Add(11, opening, WithGeometryRelations(Synthetic.Concat(FramedElementId(openingClass, 185, "OP"), openingSettings), + HostRelation(hostRole, upper), GeometryRelation(0x11, openingRole, openingCase == 3 ? Guid.NewGuid() : cut))); + Add(12, cut, WithGeometryRelations(cutClass.ToByteArray(), HostRelation(openingRole, opening), HostRelation(targetRole, upper))); + } + if (columnCase != 0) + { + Guid column = Guid.NewGuid(), memo = Guid.NewGuid(), section = Guid.NewGuid(); + var body = Synthetic.Concat(FramedElementId(columnClass, 735, "C"), new byte[95]); + ElementId("C").CopyTo(body.AsSpan(721)); + WriteLocation(body.AsSpan(701), 1, -1); + byte[] frame = [1, 0, 2, 0, 0, 0, 1, 0]; + frame.CopyTo(body, 304); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(368), 1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(328), -2); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(352), -1); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(386), columnCase == 2 ? 0.5 : 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(410), 1); + Add(13, column, WithGeometryRelations(body, GeometryRelation(0x11, columnMemoRole, memo))); + Add(14, memo, WithGeometryRelations(columnMemoClass.ToByteArray(), HostRelation(columnMemoRole, column), + GeometryRelation(0x11, sectionRole, section), GeometryRelation(0x11, columnSlabRole, slabColumnJoint))); + var circle = CircularColumnSection(columnSectionClass, 0.25, valid: true); + BinaryPrimitives.WriteUInt32LittleEndian(circle.AsSpan(149 + 482 + 18), 2); + Add(15, section, WithGeometryRelations(circle, HostRelation(sectionRole, memo))); + Add(16, slabColumnJoint, WithGeometryRelations(slabColumnClass.ToByteArray(), HostRelation(columnSlabRole, memo), + HostRelation(slabColumnRole, columnCase == 3 ? upper : lower))); + } + + using var doc = Open(ClassTable((1, WallClass), (2, SlabClass), (3, junctionClass), (4, story), + (7, material), (8, layer), (9, composite), (10, labelClass), (11, openingClass), (12, cutClass), + (13, columnClass), (14, columnMemoClass), (15, columnSectionClass), (16, slabColumnClass)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), + JunctionAttribute(material, 7, 2, 1200), JunctionAttribute(material, 7, 3, 800), + JunctionAttribute(layer, 8, 1, 1), CompositeForWallTest(composite, splitCuts: false, kind: 9), Pool(pool), + labelStorage == 1 ? Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(labelBody), ver: 1, guid: label, + unpacked: (uint)labelBody.Length, kind: 10) : []); + var result = Assert.Single(doc.ReadElements(), e => e.Guid == wall); + double? bottom = cutBothEnds ? top.HasValue ? 0.75 : null : beveled ? null : 0.25; + Assert.Equal(bottom, result.BottomElevationToHomeStory); + Assert.Equal(top, result.TopElevationToHomeStory); + Assert.Equal(bottom - 4, result.BottomElevationToProjectZero); + Assert.Equal(top - 4, result.TopElevationToProjectZero); + + void AddSlab(Guid slab, Guid intersection, double topPlane, int beveledEdge) + { + var body = OpeningSlab(0, topPlane, 1, beveledEdge >= 0); + var floor = body.AsSpan(191); + floor[8] = columnCase == 4 ? (byte)0 : (byte)3; + bool foundation = slab == lower && columnCase != 0; + BinaryPrimitives.WriteUInt16LittleEndian(floor[83..], foundation ? (ushort)1 : (ushort)2); + BinaryPrimitives.WriteUInt16LittleEndian(floor[87..], 1); + if (foundation) BinaryPrimitives.WriteInt32LittleEndian(floor[73..], 2); + bool hosts = slab == upper && openingCase != 0; + Add(2, slab, WithGeometryRelations(body, GeometryRelation(0x11, slabWall, intersection), + slab == upper ? GeometryRelation(0x11, labelRole, label) : [], + hosts ? GeometryRelation(0x11, hostRole, opening) : [], hosts ? GeometryRelation(0x11, targetRole, cut) : [], + foundation ? GeometryRelation(0x11, slabColumnRole, slabColumnJoint) : [])); + Add(3, intersection, WithGeometryRelations(junctionClass.ToByteArray(), HostRelation(wallSlab, wall), HostRelation(slabWall, slab))); + } + + void Add(ushort kind, Guid id, byte[] body) + { + int slot = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * slotSize); + entries.Add(new(kind, (ulong)slot * (slotSize / 16), slotSize / 16, id)); + } + } + + [Theory] + [InlineData(0, 0, true, 1.0)] + [InlineData(3, 0, true, 1.0)] + [InlineData(1, 0, true, 0.25)] + [InlineData(3, 0.125, true, 0.25)] + [InlineData(3, 0, false, null)] + [InlineData(5, 0, true, null)] + [InlineData(3, 0, true, 0.25, true)] + [InlineData(0, 0, true, 0.25, false, true)] + [InlineData(3, -0.2, true, 0.25, true, false, 1)] + [InlineData(3, -0.2, true, null, true, false, 2)] + [InlineData(3, -0.2, true, null, true, false, 3)] + [InlineData(0, 0.125, true, 0.25, false, false, 0, true)] + [InlineData(3, 0.125, true, 0.25, false, false, 0, false, 1)] + [InlineData(3, 0, true, null, false, false, 0, false, 1)] + [InlineData(3, 0.000001, true, null, false, false, 0, false, 1)] + [InlineData(3, 0.125, true, null, false, false, 0, false, 2)] + [InlineData(0, -1, true, 1.0, false, false, 0, false, 3)] + [InlineData(0, 0, true, null, false, false, 0, false, 3)] + [InlineData(0, -1, true, 1.0, false, false, 0, false, 4)] + [InlineData(0, -1, true, null, false, false, 0, false, 5)] + public void ResolvesWallCapFromTheUnionOfSlabCuts(uint operation, double gap, bool reciprocal, double? bottom, + bool upper = false, bool withHole = false, int nestedCase = 0, bool roundoff = false, int wallContactCase = 0) + { + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid material = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layer = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid junction = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid operationClass = new("47a28b23-f655-49fa-b219-1511ca52c49a"); + Guid wallRole = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slabRole = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid solidRole = new("68236820-e176-4e8c-be39-d5d56a7a71c0"); + Guid wall = Guid.NewGuid(), left = Guid.NewGuid(), right = Guid.NewGuid(); + Guid leftLink = Guid.NewGuid(), rightLink = Guid.NewGuid(); + Guid peer = Guid.NewGuid(), peerLink = Guid.NewGuid(); + bool peerCutsLeft = wallContactCase is 3 or 5; + bool bothCaps = wallContactCase is 4 or 5; + var target = WallWithPlanes(1, -3.75); + WriteWallStrip(target.AsSpan(209), alongX: true, 0.125); + const int slotSize = 2048; + var pool = new byte[(nestedCase == 3 ? 8 : nestedCase != 0 || wallContactCase != 0 ? 7 : 5) * slotSize]; + var entries = new List(); + if (nestedCase != 0) + { + Guid nestedLink = Guid.NewGuid(), reverseLink = Guid.NewGuid(); + Add(1, wall, WithGeometryRelations(target, GeometryRelationList(1, solidRole, left, leftLink, right, rightLink))); + Add(2, left, WithGeometryRelations(Slab(-1, 0, fullDepth: true), GeometryRelationList(1, solidRole, right, nestedLink), + nestedCase == 3 ? GeometryRelationList(2, solidRole, wall, leftLink, right, reverseLink) : + GeometryRelationList(2, solidRole, wall, leftLink))); + Add(2, right, WithGeometryRelations(Slab(gap, 1, fullDepth: false), GeometryRelationList(2, solidRole, wall, rightLink, left, nestedLink), + nestedCase == 3 ? GeometryRelationList(1, solidRole, left, reverseLink) : [])); + AddSubtraction(leftLink, wall, left, operation, 1); + AddSubtraction(rightLink, wall, right, operation, 1); + AddSubtraction(nestedLink, left, right, operation, nestedCase == 2 ? -1 : 1); + if (nestedCase == 3) AddSubtraction(reverseLink, right, left, operation, 1); + } + else + { + Add(1, wall, operation == 0 ? WithGeometryRelations(target, GeometryRelationList(1, wallRole, leftLink, rightLink)) : + WithGeometryRelations(target, GeometryRelation(0x11, wallRole, leftLink), GeometryRelationList(1, solidRole, right, rightLink))); + Add(2, left, WithGeometryRelations(Slab(-1, bothCaps ? 1 : 0, fullDepth: true), peerCutsLeft ? + GeometryRelationList(1, slabRole, leftLink, peerLink) : GeometryRelation(0x11, slabRole, leftLink))); + Add(3, leftLink, WithGeometryRelations(junction.ToByteArray(), HostRelation(wallRole, wall), HostRelation(slabRole, left))); + if (operation == 0) + { + Add(2, right, WithGeometryRelations(Slab(gap, 1, fullDepth: true, topOperand: bothCaps), wallContactCase == 4 ? + GeometryRelationList(1, slabRole, rightLink, peerLink) : GeometryRelation(0x11, slabRole, rightLink))); + Add(3, rightLink, WithGeometryRelations(junction.ToByteArray(), HostRelation(wallRole, wall), HostRelation(slabRole, right))); + } + else + { + Add(2, right, WithGeometryRelations(Slab(gap, 1, fullDepth: false), + GeometryRelationList(2, solidRole, reciprocal ? wall : Guid.NewGuid(), rightLink), + wallContactCase != 0 ? GeometryRelation(0x11, slabRole, peerLink) : [])); + AddSubtraction(rightLink, wall, right, operation, operation == 3 ? upper ? 1 : -1 : 0); + } + } + if (wallContactCase != 0) + { + var neighbor = WallWithPlanes(4, -3.75); + WriteWallStrip(neighbor.AsSpan(209), alongX: true, 0.125); + Add(1, peer, WithGeometryRelations(neighbor, GeometryRelation(0x11, wallRole, + wallContactCase == 2 ? Guid.NewGuid() : peerLink))); + Add(3, peerLink, WithGeometryRelations(junction.ToByteArray(), HostRelation(wallRole, peer), + HostRelation(slabRole, peerCutsLeft ? left : right))); + } + + using var doc = Open(ClassTable((1, WallClass), (2, SlabClass), (3, junction), (4, story), + (5, operationClass), (7, material), (8, layer)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), + JunctionAttribute(material, 7, 1, 1000), JunctionAttribute(material, 7, 2, 1200), + JunctionAttribute(material, 7, 3, 800), JunctionAttribute(material, 7, 4, 1400), + JunctionAttribute(layer, 8, 1, 1), Pool(pool)); + var result = Assert.Single(doc.ReadElements(), e => e.Guid == wall); + Assert.Equal(bottom, result.BottomElevationToHomeStory); + Assert.Equal(bottom - 4, result.BottomElevationToProjectZero); + double? top = wallContactCase switch + { + 4 => null, + 5 => 2.5, + 1 or 3 => 3.25, + _ => bottom.HasValue ? upper ? 2.5 : 3.25 : null, + }; + Assert.Equal(top, result.TopElevationToHomeStory); + Assert.Equal(top - 4, result.TopElevationToProjectZero); + + byte[] Slab(double minX, double maxX, bool fullDepth, bool topOperand = false) + { + var body = RectangularSlab(true); + Array.Resize(ref body, 191 + 270 + 247 + 16 + 4 * 27); + WriteLocation(body.AsSpan(163), 1, 0); + var floor = body.AsSpan(191); + double reference = topOperand ? -0.5 : upper ? fullDepth ? -0.5 : -1.25 : -3; + if (roundoff) reference = Math.BitIncrement(-2.75); + BinaryPrimitives.WriteDoubleLittleEndian(floor, reference); + BinaryPrimitives.WriteDoubleLittleEndian(floor[17..], fullDepth ? 1 : 0.25); + BinaryPrimitives.WriteInt32LittleEndian(floor[73..], fullDepth ? 2 : 3); + BinaryPrimitives.WriteUInt32LittleEndian(floor[165..], 20); + WriteRectangularPlan(floor[270..], minX, -1, maxX, 1, slab: true); + WriteSlabEdges(floor[(270 + 247)..], 4, -1); + if (withHole && minX == gap) + { + var rings = SlabWithStraightRings(-1, [(minX, -1), (maxX, -1), (maxX, 1), (minX, 1), (minX, -1)], + [(0.2, -0.0625), (0.2, 0.0625), (0.4, 0.0625), (0.4, -0.0625), (0.2, -0.0625)]); + Array.Resize(ref body, rings.Length + 104); + var polygon = body.AsSpan(191 + 270); + rings.AsSpan(191 + 166).CopyTo(polygon); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[11..], minX); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[19..], -1); + } + return body; + } + + void AddSubtraction(Guid id, Guid owner, Guid cutter, uint type, double direction) + { + var memo = new byte[84]; + operationClass.TryWriteBytes(memo); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(52), type); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(56), 1); + BinaryPrimitives.WriteDoubleLittleEndian(memo.AsSpan(76), direction); + Add(5, id, WithGeometryRelations(memo, GeometryRelationList(4, solidRole, owner, cutter))); + } + + void Add(ushort kind, Guid id, byte[] body) + { + int slot = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * slotSize); + entries.Add(new(kind, (ulong)slot * (slotSize / 16), slotSize / 16, id)); + } + } + + private static void WriteWallStrip(Span settings, bool alongX, double halfWidth) + { + BinaryPrimitives.WriteDoubleLittleEndian(settings[(alongX ? 0 : 8)..], -0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[(alongX ? 16 : 24)..], 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[77..], 2 * halfWidth); + BinaryPrimitives.WriteDoubleLittleEndian(settings[85..], 2 * halfWidth); + BinaryPrimitives.WriteDoubleLittleEndian(settings[194..], Math.PI / 2); + BinaryPrimitives.WriteDoubleLittleEndian(settings[515..], alongX ? -0.5 : -halfWidth); + BinaryPrimitives.WriteDoubleLittleEndian(settings[523..], alongX ? -halfWidth : -0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[531..], alongX ? 0.5 : halfWidth); + BinaryPrimitives.WriteDoubleLittleEndian(settings[539..], alongX ? halfWidth : 0.5); + } + + [Theory] + [InlineData(false, false, true, true, true)] + [InlineData(true, false, true, true, true)] + [InlineData(false, true, true, true, false)] + [InlineData(true, true, true, true, false)] + [InlineData(false, false, false, true, false)] + [InlineData(false, false, true, false, false)] + [InlineData(false, false, true, true, true, 1)] + [InlineData(false, false, true, true, true, 2)] + [InlineData(false, false, true, true, false, 3)] + [InlineData(false, false, true, true, true, 4)] + [InlineData(false, false, true, true, true, 5)] + [InlineData(true, false, true, true, true, 5)] + [InlineData(false, false, true, true, false, 6)] + [InlineData(false, false, true, true, false, 7)] + [InlineData(false, false, true, true, true, 8)] + [InlineData(false, false, true, true, true, 9)] + [InlineData(true, false, true, true, true, 9)] + [InlineData(false, false, true, true, false, 10)] + [InlineData(false, false, true, true, true, 11)] + [InlineData(false, false, true, true, false, 12)] + [InlineData(false, false, true, true, true, 0, 1)] + [InlineData(true, false, true, true, true, 0, 2)] + [InlineData(false, false, true, true, false, 0, 3)] + [InlineData(false, false, true, true, false, 0, 4)] + [InlineData(false, false, true, true, false, 0, 5)] + [InlineData(false, false, true, true, true, 0, 6)] + [InlineData(true, false, true, true, true, 0, 6)] + [InlineData(false, false, true, true, false, 0, 7)] + [InlineData(false, false, true, true, false, 0, 8)] + [InlineData(false, false, true, true, false, 13, 6)] + public void PreservesWallCapsOutsideVerifiedRectangularDoorCuts(bool reverse, bool bothHalves, + bool reciprocal, bool knownRevision, bool readsPlanes, int slabCase = 0, int libraryCase = 0) + { + Guid doorClass = new("d8f07689-9cfa-4fbe-aeb4-0a60b8e667ee"); + Guid libraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f"); + Guid libraryRole = new("672f1c46-64f3-41f5-8a4a-ffdfd86bcbfd"); + Guid tableClass = new("11db227d-dbe4-45af-88b6-6fddea993f71"); + Guid tableRole = new("76ebf0a4-c2ef-483f-a1a8-28d3adde99a0"); + Guid hostRole = new("1f6bfe02-d60c-40ae-9ac8-c3953ce12814"); + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid material = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layer = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid junctionClass = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid wallSlab = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slabWall = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid composite = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + bool pocket = libraryCase >= 6; + var (family, revision) = libraryCase switch + { + 0 => (new Guid("ffd54fba-1ad6-4cf7-87cc-918accd4e480"), new Guid("6ebb67a2-5c74-4640-ab79-86e54703485a")), + 2 => (new Guid("e155d0a0-7435-41af-8668-b4bae047f2b2"), new Guid("460fe002-f8e8-4d2c-859e-e99587473cef")), + >= 6 => (new Guid("e4b25630-169a-4820-8bd9-962ed253b6c1"), new Guid("318e68fb-15e0-4e0b-92ed-bbf67a14b2eb")), + _ => (new Guid("13d8efa7-3fee-4993-b7a5-d826a6830657"), new Guid("a4ce2f76-b4d0-4b26-a920-4a84fbe513dc")), + }; + if (!knownRevision) revision = Guid.NewGuid(); + Guid wall = Guid.NewGuid(), door = Guid.NewGuid(), other = Guid.NewGuid(); + Guid joint = Guid.NewGuid(), upperJoint = Guid.NewGuid(); + bool twoSlabs = slabCase is 6 or 8 or 9 or 10 or 13; + var target = WallWithPlanes(1, -3.75); + var settings = target.AsSpan(209); + WriteWallStrip(settings, alongX: true, pocket ? 0.05 : 0.125); + double halfLength = pocket ? 0.75 : 0.5; + BinaryPrimitives.WriteDoubleLittleEndian(settings, reverse ? halfLength : -halfLength); + BinaryPrimitives.WriteDoubleLittleEndian(settings[16..], reverse ? -halfLength : halfLength); + if (pocket) + { + // The aperture bounds span the wall length. The cap needs a strip outside the pocket depth. + BinaryPrimitives.WriteDoubleLittleEndian(settings[515..], -halfLength); + BinaryPrimitives.WriteDoubleLittleEndian(settings[531..], halfLength); + BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[229..], 1); + } + const int slotSize = 1024; + const int tableSlotSize = 4096; + var pool = new byte[7 * slotSize]; + var entries = new List(); + var tables = new List(); + var tableBlocks = new List(); + Add(1, wall, WithGeometryRelations(target, bothHalves ? GeometryRelationList(1, hostRole, door, other) : + GeometryRelation(0x11, hostRole, door), twoSlabs ? GeometryRelationList(1, wallSlab, joint, upperJoint) : + slabCase != 0 ? GeometryRelation(0x11, wallSlab, joint) : [])); + AddDoor(door, pocket ? halfLength : 0.25); + if (bothHalves) AddDoor(other, 0.75); + if (slabCase == 13) + { + // At the bottom the slabs leave only the path occupied by the passage and pocket envelopes. + AddSlab(joint, -1, [(-1, -1), (1, -1), (1, -0.02), (-1, -0.02), (-1, -1)], 0.5); + AddSlab(upperJoint, -1, [(-1, 0.02), (1, 0.02), (1, 1), (-1, 1), (-1, 0.02)], 0.5); + } + else if (slabCase is 11 or 12) + { + AddSlab(joint, slabCase == 12 ? 4 : -1, [(-0.75, -1), (0.75, -1), (0.75, 1), (-0.75, 1), (-0.75, -1)], + 3.25, [(0.125, -0.0625), (0.125, 0.0625), (0.375, 0.0625), (0.375, -0.0625), (0.125, -0.0625)]); + } + else if (slabCase >= 5) + { + double edge = slabCase == 7 ? 0.125 - 1e-6 : -0.03125; + AddSlab(joint, slabCase == 10 ? 0 : -1, [(-0.75, -1), (0.75, -1), (0.75, edge), (-0.75, edge), (-0.75, -1)]); + if (twoSlabs) + { + double lower = slabCase == 8 ? 0.0625 : -0.0625; + AddSlab(upperJoint, -1, [(-0.75, lower), (0.75, lower), (0.75, 1), (-0.75, 1), (-0.75, lower)], + slabCase is 9 or 10 ? 1 : 3.25); + } + } + else if (slabCase != 0) + { + double left = slabCase == 4 ? 5e-8 : -0.125; + double farEdge = slabCase switch { 2 => 0, 4 => 0.75, _ => -0.1 }; + double nearEdge = slabCase is 2 or 4 ? 1.5 : 0.6; + AddSlab(joint, slabCase == 3 ? 0 : -1, + [(left, -1), (nearEdge, -1), (farEdge, 1), (left, 1), (left, -1)]); + } + + void AddSlab(Guid contact, int beveledEdge, (double X, double Y)[] ring, double top = 3.25, + params (double X, double Y)[][] holes) + { + Guid slab = Guid.NewGuid(); + var floor = SlabWithStraightRings(beveledEdge, [ring, .. holes]); + const int smallOutline = 191 + 166, largeOutline = 191 + 270; + Array.Resize(ref floor, floor.Length + largeOutline - smallOutline); + floor.AsSpan(smallOutline, floor.Length - largeOutline).CopyTo(floor.AsSpan(largeOutline)); + BinaryPrimitives.WriteDoubleLittleEndian(floor.AsSpan(largeOutline + 11), ring.Min(p => p.X)); + BinaryPrimitives.WriteDoubleLittleEndian(floor.AsSpan(largeOutline + 19), ring.Min(p => p.Y)); + BinaryPrimitives.WriteDoubleLittleEndian(floor.AsSpan(191), top); + if (slabCase == 13) BinaryPrimitives.WriteInt32LittleEndian(floor.AsSpan(191 + 73), 4); + BinaryPrimitives.WriteUInt32LittleEndian(floor.AsSpan(191 + 165), 20); + Add(5, slab, WithGeometryRelations(floor, GeometryRelation(0x11, slabWall, contact))); + Add(6, contact, WithGeometryRelations(junctionClass.ToByteArray(), HostRelation(wallSlab, wall), HostRelation(slabWall, slab))); + } + + using var doc = Open(ClassTable((1, WallClass), (2, doorClass), (3, libraryClass), (4, story), + (5, SlabClass), (6, junctionClass), (7, material), (8, layer), (9, tableClass), (10, composite)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), + JunctionAttribute(material, 7, 1, 1000), JunctionAttribute(material, 7, 2, 1200), + pocket ? JunctionAttribute(material, 7, 3, 1000) : [], + slabCase == 13 ? JunctionAttribute(material, 7, 4, 1400) : [], + pocket ? CompositeForWallTest(composite, splitCuts: false, thickness: libraryCase == 8 ? (0.02, 0.06) : (0.024, 0.052)) : [], + JunctionAttribute(layer, 8, 1, 1), Pool(pool), + tables.Count == 0 ? [] : OwnedDirectory(false, Guid.Empty, (ulong)tables.Count * (tableSlotSize / 16), tables.ToArray()), + tables.Count == 0 ? [] : Pool(tableBlocks.ToArray())); + var elements = doc.ReadElements(); + var result = Assert.Single(elements, e => e.Guid == wall); + var placedDoor = Assert.Single(elements, e => e.Guid == door); + Assert.Equal(reciprocal ? new PlaLibraryPartReference(family, revision) : (PlaLibraryPartReference?)null, + placedDoor.LibraryPartReference); + double? bottom = readsPlanes || slabCase is 6 or 7 ? 0.25 : null; + double? top = readsPlanes || bothHalves || slabCase == 13 ? 3.25 : slabCase == 6 ? 2.25 : null; + Assert.Equal(bottom, result.BottomElevationToHomeStory); + Assert.Equal(top, result.TopElevationToHomeStory); + Assert.Equal(bottom - 4, result.BottomElevationToProjectZero); + Assert.Equal(top - 4, result.TopElevationToProjectZero); + Assert.Null(result.WallExtrusion); + + void AddDoor(Guid id, double position) + { + Guid library = Guid.NewGuid(); + Guid table = Guid.NewGuid(); + var descriptor = new byte[89]; + libraryClass.TryWriteBytes(descriptor); + new byte[] { 1, 0, 131, 0, 3, 0, 0, 0, 1, 0, 2, 0 }.CopyTo(descriptor, 39); + family.TryWriteBytes(descriptor.AsSpan(51)); + revision.TryWriteBytes(descriptor.AsSpan(67)); + Add(3, library, WithGeometryRelations(descriptor, HostRelation(libraryRole, reciprocal ? id : Guid.NewGuid()), + libraryCase == 0 ? [] : GeometryRelation(0x11, tableRole, table))); + if (libraryCase != 0) + { + byte[] body = PlainDoorPassageTable(tableClass, tableRole, libraryCase == 5 ? Guid.NewGuid() : library, + positiveOversize: libraryCase == 3, revealType: libraryCase == 4 ? 2 : 1, + pocket: pocket, centeredPocket: libraryCase != 7); + byte[] storage = new byte[tableSlotSize]; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: table, extra: 1, kind: 9).CopyTo(storage, 0); + tables.Add(new(9, (ulong)tables.Count * (tableSlotSize / 16), tableSlotSize / 16, table)); + tableBlocks.Add(storage); + } + + var framed = FramedElementId(doorClass, 286, "D"); + WriteLocation(framed.AsSpan(175), 1, -1); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(185), 1); + BinaryPrimitives.WriteDoubleLittleEndian(framed.AsSpan(202), pocket ? 0.7 : 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(framed.AsSpan(210), pocket ? 2.1 : 2); + BinaryPrimitives.WriteUInt32LittleEndian(framed.AsSpan(268), 1); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(272), 83); + BinaryPrimitives.WriteUInt16LittleEndian(framed.AsSpan(274), libraryCase == 0 ? (ushort)1 : (ushort)2); + var placement = new byte[72]; + new byte[] { 0, 1, 0, 14, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }.CopyTo(placement, 0); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(24), position); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(48), 1); + Add(2, id, WithGeometryRelations(Synthetic.Concat(framed, placement), + GeometryRelation(0x11, libraryRole, library), HostRelation(hostRole, wall))); + } + + void Add(ushort kind, Guid id, byte[] body) + { + int slot = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * slotSize); + entries.Add(new(kind, (ulong)slot * (slotSize / 16), slotSize / 16, id)); + } + } + + private static byte[] WallWithPlanes(int material, double boxBottom) + { + byte[] wall = Synthetic.Concat(FramedElementId(WallClass, 197, "WL-1"), new byte[563]); + ElementId("WL-1").CopyTo(wall, 183); + WriteLocation(wall.AsSpan(163), 1, -1); + var settings = wall.AsSpan(209); + BinaryPrimitives.WriteDoubleLittleEndian(settings[153..], 3); + BinaryPrimitives.WriteDoubleLittleEndian(settings[161..], 0.25); + BinaryPrimitives.WriteInt32LittleEndian(settings[215..], material); + BinaryPrimitives.WriteUInt16LittleEndian(settings[225..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(settings[227..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[547..], boxBottom); + BinaryPrimitives.WriteDoubleLittleEndian(settings[555..], boxBottom + 3); + return wall; + } + + [Theory] + [InlineData(3, 1, true, true, true)] + [InlineData(1, 0, true, true, true)] + [InlineData(3, 1, false, true, false)] + [InlineData(3, 1, true, false, false)] + [InlineData(5, 1, true, true, false)] + public void ReadsWallPlanesWhenTheWallIsASubtractionOperator(uint type, double z, bool reverseLink, + bool matchingOperand, bool readsPlanes) + { + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid assembly = new("8f2fee46-6a3f-41ac-a32b-69e44dc6276d"); + Guid member = new("47a28b23-f655-49fa-b219-1511ca52c49a"); + Guid operation = new("68236820-e176-4e8c-be39-d5d56a7a71c0"); + Guid wall = Guid.NewGuid(), target = Guid.NewGuid(), link = Guid.NewGuid(); + var body = WithGeometryRelations(WallWithPlanes(1, -3.75), GeometryRelationList(2, operation, target, link)); + var operand = WithGeometryRelations(assembly.ToByteArray(), GeometryRelationList(1, operation, wall, + reverseLink ? link : Guid.NewGuid())); + var memo = new byte[84]; + member.TryWriteBytes(memo); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(52), type); + BinaryPrimitives.WriteUInt32LittleEndian(memo.AsSpan(56), 1); + BinaryPrimitives.WriteDoubleLittleEndian(memo.AsSpan(76), z); + memo = WithGeometryRelations(memo, GeometryRelationList(4, operation, target, matchingOperand ? wall : Guid.NewGuid())); + var pool = new byte[3072]; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: wall, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, operand, ver: 1, guid: target, extra: 1, kind: 2).CopyTo(pool, 1024); + Synthetic.Block(PlaBlockMode.Raw, memo, ver: 1, guid: link, extra: 1, kind: 3).CopyTo(pool, 2048); + using var doc = Open(ClassTable((1, WallClass), (2, assembly), (3, member), (4, story)), + OwnedDirectory(false, Guid.Empty, 192, new ObjectDirectoryRecord(1, 0, 64, wall), + new ObjectDirectoryRecord(2, 64, 64, target), new ObjectDirectoryRecord(3, 128, 64, link)), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), Pool(pool)); + + var result = Assert.Single(doc.ReadElements(), e => e.Guid == wall); + Assert.Equal(readsPlanes ? 0.25 : null, result.BottomElevationToHomeStory); + Assert.Equal(readsPlanes ? 3.25 : null, result.TopElevationToHomeStory); + Assert.Equal(readsPlanes ? -3.75 : null, result.BottomElevationToProjectZero); + Assert.Equal(readsPlanes ? -0.75 : null, result.TopElevationToProjectZero); + } + + [Theory] + [InlineData(1200, true, 0.5)] + [InlineData(800, true, 0.25)] + [InlineData(1200, false, null)] + [InlineData(1200, true, 0.5, 2, 1)] + [InlineData(1200, true, null, 2, 2)] + public void ReadsWallEndCutByRectangularBeam(uint beamPriority, bool reciprocal, double? expectedBottom, + int beamLayer = 1, uint beamGroup = 1) + { + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"); + Guid wallBeam = new("b7a142a1-2e5f-4b17-9b52-40604fbc3828"); + Guid wallId = Guid.NewGuid(), junctionId = Guid.NewGuid(); + + byte[] pool = new byte[5 * 1024 + 1024]; + var wall = WithGeometryRelations(WallWithPlanes(1, -3.75), + GeometryRelation(0x11, wallBeam, reciprocal ? junctionId : Guid.NewGuid())); + WriteWallStrip(wall.AsSpan(209), alongX: true, halfWidth: 0.125); + Synthetic.Block(PlaBlockMode.Raw, wall, ver: 1, guid: wallId, extra: 1, kind: 1).CopyTo(pool, 0); + var entries = new List { new(1, 0, 64, wallId) }; + AddBeamCutFixture(pool, entries, wallId, junctionId, 1024, 0, 0.5, 1, 0, [], wallTarget: true, layer: beamLayer); + using var doc = Open(ClassTable((1, WallClass), (3, sectionClass), (4, storyClass), (7, materialClass), (8, layerClass), + (9, new Guid("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")), (10, new Guid("cbab7bc6-e03a-4133-9161-c28ed3368672")), + (11, new Guid("9eb0036e-2b99-4db1-b043-051fb1817f47"))), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 1000), + JunctionAttribute(materialClass, 7, 2, beamPriority), + JunctionAttribute(layerClass, 8, 1, 1), + JunctionAttribute(layerClass, 8, 2, beamGroup), + Pool(pool)); + + var element = Assert.Single(doc.ReadElements(), x => x.Guid == wallId); + Assert.Equal(expectedBottom, element.BottomElevationToHomeStory); + Assert.Equal(expectedBottom - 4, element.BottomElevationToProjectZero); + Assert.Equal(expectedBottom.HasValue ? 3.25 : null, element.TopElevationToHomeStory); + Assert.Equal(expectedBottom.HasValue ? -0.75 : null, element.TopElevationToProjectZero); + } + + [Theory] + [InlineData(false, false, false, false)] + [InlineData(true, false, false, false)] + [InlineData(false, true, false, false)] + [InlineData(false, false, true, false)] + [InlineData(false, false, false, true)] + [InlineData(false, false, false, false, 1200, true, 0.5)] + [InlineData(false, false, false, false, 1200, false, 0)] + [InlineData(false, false, false, false, 800, true, 0)] + [InlineData(false, false, false, false, 1000, true, 0)] + [InlineData(false, false, false, false, 0, false, 0.5, 1)] + [InlineData(false, false, false, false, 0, false, 0, 2)] + [InlineData(false, false, false, false, 0, false, 0, 3)] + [InlineData(false, false, false, false, 0, false, 0, 4)] + [InlineData(false, false, false, false, 0, false, 0.5, 5)] + [InlineData(false, false, false, false, 0, false, 0, 6)] + [InlineData(false, false, false, false, 0, false, 1.5, 7)] + [InlineData(false, false, false, false, 0, false, 0.5, 8)] + [InlineData(false, false, false, false, 0, false, 0, 9)] + [InlineData(false, false, false, false, 0, false, 0.5, 10)] + [InlineData(false, false, false, false, 0, false, 0, 11)] + [InlineData(false, false, false, false, 0, false, 0.5, 12)] + [InlineData(false, false, false, false, 0, false, 0.5, 13)] + [InlineData(false, false, false, false, 0, false, 0, 14)] + [InlineData(false, false, false, false, 0, false, 0.5, 15)] + [InlineData(false, false, false, false, 0, false, 0, 16)] + [InlineData(false, false, false, false, 0, false, 0, 0, Math.PI / 2)] + public void ProjectsTheColumnEndCutsOverItsStoredRectangle(bool connected, bool curved, bool wrongOwner, bool unknownOperation, + int slabPriority = 0, bool coversColumn = false, double expectedBottom = 0, int beamCase = 0, double planAngle = 0) + { + Guid columnClass = new("13e8eb85-5a33-47a3-a4d4-1e05296aec7e"); + Guid memoClass = new("7a1a82ab-69cd-40e6-a7d8-76564f981cf9"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid memoRelation = new("27448621-9adc-43e6-b5aa-fc76e4cd62ce"); + Guid sectionRelation = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid slabJunctionClass = new("d5381783-6a19-4de8-9e52-2e04a3978db0"); + Guid materialClass = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layerClass = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid columnBeam = new("6346a816-1d7c-4e46-9609-67624e99d0fb"); + Guid columnSlab = new("87811dc4-1686-45f4-b1a6-dfaa81da44e4"); + Guid slabColumn = new("f6ee0d9c-27ad-44d0-824f-682969bb171e"); + Guid contactId = Guid.NewGuid(), secondContactId = Guid.NewGuid(), slabId = Guid.NewGuid(); + Guid columnId = Guid.NewGuid(), memoId = Guid.NewGuid(), sectionId = Guid.NewGuid(); + bool multipleBeams = beamCase is >= 5 and <= 9 or >= 12 and <= 16; + bool endJoin = beamCase >= 10; + byte[] column = Synthetic.Concat(FramedElementId(columnClass, 735, "C-1"), new byte[95]); + var record = column.AsSpan(); + ElementId("C-1").CopyTo(record[721..]); + byte[] planes = [1, 0, 2, 0, 0, 0, 1, 0]; + planes.CopyTo(record[304..]); + BinaryPrimitives.WriteDoubleLittleEndian(record[352..], -1); + BinaryPrimitives.WriteUInt16LittleEndian(record[368..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(record[386..], 3); + bool horizontalTop = multipleBeams || planAngle != 0; + BinaryPrimitives.WriteDoubleLittleEndian(record[402..], horizontalTop ? 0 : 0.6); + BinaryPrimitives.WriteDoubleLittleEndian(record[410..], horizontalTop ? 1 : 0.8); + BinaryPrimitives.WriteDoubleLittleEndian(record[(745 + 87)..], planAngle); + WriteLocation(record[701..], 1, -1); + column = WithGeometryRelations(column, GeometryRelation(0x11, memoRelation, memoId), + unknownOperation ? GeometryRelation(0x12, Guid.NewGuid(), Guid.NewGuid()) : []); + + var memo = new byte[40]; + memoClass.TryWriteBytes(memo); + memo = WithGeometryRelations(memo, + HostRelation(memoRelation, wrongOwner ? Guid.NewGuid() : columnId), + GeometryRelation(0x11, sectionRelation, sectionId), + connected || beamCase != 0 ? GeometryRelation(0x11, columnBeam, connected ? Guid.NewGuid() : contactId) : [], + multipleBeams ? GeometryRelation(0x11, columnBeam, secondContactId) : [], + slabPriority != 0 ? GeometryRelation(0x11, columnSlab, contactId) : []); + + double halfDepth = planAngle == 0 ? 0.25 : 0.125; + byte[] section = WithGeometryRelations(RectangularSection(sectionClass, 1, 0.25, -halfDepth, halfDepth, curved), + HostRelation(sectionRelation, memoId)); + bool joinedBeams = beamCase is 8 or 9 || endJoin; + byte[] pool = new byte[(joinedBeams ? 14 : multipleBeams ? 13 : beamCase == 0 ? 5 : 8) * 1024]; + Synthetic.Block(PlaBlockMode.Raw, column, ver: 1, guid: columnId, extra: 1, kind: 1).CopyTo(pool, 0); + Synthetic.Block(PlaBlockMode.Raw, memo, ver: 1, guid: memoId, extra: 1, kind: 2).CopyTo(pool, 1024); + Synthetic.Block(PlaBlockMode.Raw, section, ver: 1, guid: sectionId, extra: 1, kind: 3).CopyTo(pool, 2048); + if (slabPriority != 0) + { + byte[] contact = new byte[48]; + slabJunctionClass.TryWriteBytes(contact); + contact = WithGeometryRelations(contact, HostRelation(slabColumn, slabId), HostRelation(columnSlab, memoId)); + var slab = WithGeometryRelations(RectangularSlab(coversColumn), GeometryRelation(0x11, slabColumn, contactId)); + Synthetic.Block(PlaBlockMode.Raw, slab, ver: 1, guid: slabId, extra: 1, kind: 5).CopyTo(pool, 3072); + Synthetic.Block(PlaBlockMode.Raw, contact, ver: 1, guid: contactId, extra: 1, kind: 6).CopyTo(pool, 4096); + } + var entries = new List { new(1, 0, 64, columnId), new(2, 64, 64, memoId), new(3, 128, 64, sectionId) }; + var classes = new List<(ushort, Guid)> + { + (1, columnClass), (2, memoClass), (3, sectionClass), (4, storyClass), + (5, SlabClass), (6, slabJunctionClass), (7, materialClass), (8, layerClass), + }; + if (slabPriority != 0) + entries.AddRange([new(5, 192, 64, slabId), new(6, 256, 64, contactId)]); + if (beamCase != 0) + { + classes.AddRange([(9, new Guid("a5c2d285-5a7c-4a68-9554-9eda9d4556ca")), + (10, new Guid("cbab7bc6-e03a-4133-9161-c28ed3368672")), (11, new Guid("f7f60005-35d0-4346-87ab-29e087ac0bbf"))]); + double half = beamCase is 3 or 5 or 6 or 8 or 9 ? 0.125 : 1; + double y = beamCase is 5 or 6 or 8 or 9 ? -0.125 : 0; + Guid collision = Guid.NewGuid(); + bool branchStronger = beamCase is 13 or 14 or 16; + Guid firstKey = new(branchStronger ? "1dae4518-b353-42bc-bcb1-d037bcc603d6" : + endJoin ? "59655252-b20b-47a7-9d4a-27a2f2bf2c73" : "89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid secondKey = new(branchStronger || !endJoin ? "1d381463-2edc-4aad-91b0-027291e8da94" : + "89d11bdb-3a78-48ad-96e7-5b69836c591d"); + Guid firstMemo = AddBeamCutFixture(pool, entries, memoId, contactId, 3072, y, beamCase == 2 ? 3.25 : 0.5, half, + beamCase == 4 ? Math.PI / 6 : 0, joinedBeams ? GeometryRelation(0x11, firstKey, collision) : [], + endX: beamCase >= 12 ? 0 : null, material: beamCase == 15 ? 1u : 2u); + if (multipleBeams || endJoin) + { + double elevation = beamCase == 7 ? 1.5 : joinedBeams ? 0.5 : 0.75; + Guid secondMemo = AddBeamCutFixture(pool, entries, multipleBeams ? memoId : Guid.Empty, secondContactId, 8192, + beamCase >= 12 ? 0 : endJoin ? 2 : beamCase == 6 ? 0.1875 : -y, + beamCase == 16 ? 0.75 : elevation, beamCase == 14 ? 0.125 : half, 0, + joinedBeams ? GeometryRelation(0x11, secondKey, collision) : [], transverse: endJoin, + material: branchStronger ? 1u : 2u); + if (joinedBeams) + { + Guid collisionClass = new("92ee3161-7e81-4cb2-a403-b814edb2ae37"); + var contact = new byte[67]; + collisionClass.TryWriteBytes(contact); + if (endJoin) + { + byte[] pointFrame = [28, 0, 0, 0, 1, 2, 22, 0, 0, 0, 2, 0, 3, 0, 0]; + pointFrame.CopyTo(contact, 35); + BinaryPrimitives.WriteDoubleLittleEndian(contact.AsSpan(50), beamCase >= 12 ? 0 : beamCase == 10 ? 2 : 1); + contact[66] = 1; + } + contact = WithGeometryRelations(contact, HostRelation(firstKey, firstMemo), + HostRelation(secondKey, beamCase == 9 ? Guid.NewGuid() : secondMemo)); + Synthetic.Block(PlaBlockMode.Raw, contact, ver: 1, guid: collision, extra: 1, kind: 12).CopyTo(pool, 13312); + classes.Add((12, collisionClass)); + entries.Add(new(12, 832, 64, collision)); + } + } + } + using var doc = Open(ClassTable(classes.ToArray()), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(storyClass), ver: 1, kind: 4), + JunctionAttribute(materialClass, 7, 1, 1000), + JunctionAttribute(materialClass, 7, 2, beamCase != 0 ? 1200u : (uint)slabPriority), + JunctionAttribute(layerClass, 8, 1, 1), + Pool(pool)); + + var element = Assert.Single(doc.ReadElements(), x => x.Type == "Column"); + bool supported = !connected && !curved && !wrongOwner && !unknownOperation && beamCase is not (9 or 11 or 16); + if (beamCase == 4) expectedBottom = 0.5 - 0.25 * Math.Tan(Math.PI / 6); + double expectedTop = horizontalTop ? 3 : beamCase == 2 ? 2.25 : 3.1875; + Assert.Equal(-1, element.HomeStoryIndex); + Assert.Equal("Подвал", element.HomeStoryName); + Assert.Equal(supported ? expectedBottom : null, element.BottomElevationToHomeStory); + Assert.Equal(supported ? expectedTop : null, element.TopElevationToHomeStory); + Assert.Equal(supported ? -4 + expectedBottom : null, element.BottomElevationToProjectZero); + Assert.Equal(supported ? -4 + expectedTop : null, element.TopElevationToProjectZero); + bool hasSolid = supported && (beamCase is 1 or 2 or 7 or 8 or 10 or 12 or 13 or 15 || + beamCase == 0 && (slabPriority is 0 or 800 or 1000 || coversColumn)); + if (hasSolid) + { + var solid = Assert.IsType(element.ColumnExtrusion); + var box = solid.BoundingBox; + Assert.Equal(box, element.BoundingBox); + Assert.Equal(planAngle == 0 ? -0.25 : -halfDepth, box.XMin, 12); + Assert.Equal(planAngle == 0 ? 0.25 : halfDepth, box.XMax, 12); + Assert.Equal(-0.25, box.YMin, 12); + Assert.Equal(0.25, box.YMax, 12); + Assert.Equal(expectedBottom - 4, box.ZMin); + Assert.Equal(expectedTop - 4, box.ZMax); + double upperAtCenter = horizontalTop || beamCase == 2 ? expectedTop : 3; + Assert.Equal(upperAtCenter - 4, solid.UpperPlane.Elevation); + Assert.Equal(0, solid.UpperPlane.SlopeX); + Assert.Equal(horizontalTop || beamCase == 2 ? 0 : -0.75, solid.UpperPlane.SlopeY, 12); + Assert.Equal(halfDepth * (upperAtCenter - expectedBottom), solid.Volume, 12); + } + else + Assert.Null(element.ColumnExtrusion); + } + + private static byte[] RectangularSection(Guid sectionClass, uint material, double halfWidth, double bottom, double top, + bool curved = false, bool concave = false) + { + (double X, double Y)[] vertices = concave + ? [(-halfWidth, bottom), (halfWidth, bottom), (halfWidth, top), (0, top), + (0, (bottom + top) / 2), (-halfWidth, (bottom + top) / 2), (-halfWidth, bottom)] + : [(-halfWidth, bottom), (halfWidth, bottom), (halfWidth, top), (-halfWidth, top), (-halfWidth, bottom)]; + int hatchLength = 59 + 16 * (vertices.Length + 1) + 6; + byte[] section = new byte[149 + 482 + hatchLength]; + sectionClass.TryWriteBytes(section); + BinaryPrimitives.WriteDoubleLittleEndian(section.AsSpan(91), 2 * halfWidth); + BinaryPrimitives.WriteDoubleLittleEndian(section.AsSpan(99), top - bottom); + new byte[] { 2, 0, 9, 1 }.CopyTo(section, 141); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(145), (uint)(482 + hatchLength)); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(149), 128); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(149 + 69), 1); + var hatch = section.AsSpan(149 + 482); + hatch[0] = 3; + hatch[1] = 1; + BinaryPrimitives.WriteUInt32LittleEndian(hatch[2..], (uint)(hatchLength - 6)); + BinaryPrimitives.WriteUInt16LittleEndian(hatch[8..], 2); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[18..], material); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[55..], (uint)(vertices.Length + 1)); + for (int i = 0; i < vertices.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(hatch[(75 + 16 * i)..], vertices[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(hatch[(83 + 16 * i)..], vertices[i].Y); + } + BinaryPrimitives.WriteUInt16LittleEndian(hatch[(hatchLength - 6)..], 1); + BinaryPrimitives.WriteUInt32LittleEndian(hatch[(hatchLength - 4)..], curved ? 1u : 0u); + return section; + } + + private static Guid AddBeamCutFixture(byte[] pool, List entries, + Guid targetId, Guid contactId, int offset, double y, double elevation, double halfWidth, double roll, byte[] join, + bool wallTarget = false, bool transverse = false, double? endX = null, int layer = 1, uint material = 2, double startY = -2, + double? endElevation = null, (double X, double Z)? endNormal = null, double startX = -2, Guid? additionalColumnContact = null, + double? endY = null, bool concaveSection = false) + { + Guid beamClass = new("a5c2d285-5a7c-4a68-9554-9eda9d4556ca"); + Guid beamMemoClass = new("cbab7bc6-e03a-4133-9161-c28ed3368672"); + Guid contactClass = new(wallTarget ? "9eb0036e-2b99-4db1-b043-051fb1817f47" : "f7f60005-35d0-4346-87ab-29e087ac0bbf"); + Guid sectionClass = new("c4191955-87c6-4fb6-b074-5f094fe9f6a6"); + Guid beamMemo = new("d5762ca7-d920-455d-a373-28ba6d47152a"); + Guid beamTarget = new(wallTarget ? "b6d5f795-c750-4a2f-9bb0-e659fb07513a" : "cd0b0837-0b34-4e96-8d66-9fe7d926478c"); + Guid targetBeam = new(wallTarget ? "b7a142a1-2e5f-4b17-9b52-40604fbc3828" : "6346a816-1d7c-4e46-9609-67624e99d0fb"); + Guid sectionRelation = new("63b86c30-a221-421c-84fb-926c694bf611"); + Guid beamId = Guid.NewGuid(), memoId = Guid.NewGuid(), sectionId = Guid.NewGuid(); + + double x0 = transverse ? y : startX, yy0 = transverse ? startY : y; + double x1 = endX ?? (transverse ? y : 2), yy1 = endY ?? (transverse ? 2 : y); + byte[] placement = HorizontalBeam(beamClass, x0, yy0, x1, yy1, elevation, roll, layer); + if (endElevation is { } end) BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(386), end); + if (endNormal is { } normal) + { + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(394), normal.X); + BinaryPrimitives.WriteDoubleLittleEndian(placement.AsSpan(410), normal.Z); + } + byte[] beam = WithGeometryRelations(placement, GeometryRelation(0x11, beamMemo, memoId)); + var memo = WithGeometryRelations(beamMemoClass.ToByteArray(), HostRelation(beamMemo, beamId), + GeometryRelation(0x11, sectionRelation, sectionId), + additionalColumnContact is { } extra ? GeometryRelationList(1, beamTarget, contactId, extra) : + targetId != Guid.Empty ? GeometryRelation(0x11, beamTarget, contactId) : [], join); + var contact = WithGeometryRelations(contactClass.ToByteArray(), HostRelation(beamTarget, memoId), HostRelation(targetBeam, targetId)); + var section = WithGeometryRelations(RectangularSection(sectionClass, material, halfWidth, -1, 0, concave: concaveSection), + HostRelation(sectionRelation, memoId)); + Synthetic.Block(PlaBlockMode.Raw, beam, ver: 1, guid: beamId, extra: 1, kind: 9).CopyTo(pool, offset); + Synthetic.Block(PlaBlockMode.Raw, memo, ver: 1, guid: memoId, extra: 1, kind: 10).CopyTo(pool, offset + 2048); + ulong start = (ulong)offset / 16; + entries.AddRange([new(9, start, 128, beamId), new(10, start + 128, 64, memoId)]); + if (targetId != Guid.Empty) + { + Synthetic.Block(PlaBlockMode.Raw, contact, ver: 1, guid: contactId, extra: 1, kind: 11).CopyTo(pool, offset + 3072); + entries.Add(new(11, start + 192, 64, contactId)); + } + Synthetic.Block(PlaBlockMode.Raw, section, ver: 1, guid: sectionId, extra: 1, kind: 3).CopyTo(pool, offset + 4096); + entries.Add(new(3, start + 256, 64, sectionId)); + return memoId; + } + + private static byte[] HorizontalBeam(Guid beamClass, double x0, double y0, double x1, double y1, + double elevation, double roll, int layer) + { + byte[] beam = Synthetic.Concat(FramedElementId(beamClass, 735, "B"), new byte[254]); + ElementId("B").CopyTo(beam, 721); + byte[] planes = [1, 0, 2, 0, 0, 0, 1, 0]; + planes.CopyTo(beam, 304); + BinaryPrimitives.WriteUInt16LittleEndian(beam.AsSpan(368), 1); + double length = double.Hypot(x1 - x0, y1 - y0); + double dx = (x1 - x0) / length, dy = (y1 - y0) / length; + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(312), x0); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(320), y0); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(328), elevation); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(336), -dx); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(344), -dy); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(370), x1); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(378), y1); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(386), elevation); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(394), dx); + BinaryPrimitives.WriteDoubleLittleEndian(beam.AsSpan(402), dy); + WriteLocation(beam.AsSpan(701), layer, -1); + var settings = beam.AsSpan(741); + BinaryPrimitives.WriteDoubleLittleEndian(settings[17..], x0); + BinaryPrimitives.WriteDoubleLittleEndian(settings[25..], y0); + BinaryPrimitives.WriteDoubleLittleEndian(settings[33..], x1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[41..], y1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[133..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[238..], 1); + BinaryPrimitives.WriteDoubleLittleEndian(settings[155..], roll); + BinaryPrimitives.WriteDoubleLittleEndian(settings[246..], roll); + return beam; + } + + private static byte[] RectangularSlab(bool coversColumn, int polygonCase = 0) + { + byte[] slab = Synthetic.Concat(FramedElementId(SlabClass, 185, "S"), new byte[575]); + WriteLocation(slab.AsSpan(163), 1, -1); + var settings = slab.AsSpan(191); + BinaryPrimitives.WriteDoubleLittleEndian(settings, 0.5); + BinaryPrimitives.WriteDoubleLittleEndian(settings[17..], 1); + BinaryPrimitives.WriteInt32LittleEndian(settings[73..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[83..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(settings[85..], 1); + WriteRectangularPlan(settings[270..], -1, -1, coversColumn ? 1 : 0, 1, slab: true); + if (polygonCase is 7 or 8) + { + var polygon = settings[270..]; + double notchX = polygonCase == 7 ? 0.75 : 0; + double notchY = polygonCase == 7 ? 0.75 : -0.05; + var vertices = new (double X, double Y)[] { (-1, -1), (1, -1), (1, notchY), (notchX, notchY), (notchX, 1), (-1, 1), (-1, -1) }; + BinaryPrimitives.WriteUInt32LittleEndian(polygon[4..], 295); + BinaryPrimitives.WriteInt32LittleEndian(polygon[43..], vertices.Length); + for (int i = 0; i < vertices.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(71 + i * 16)..], vertices[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(79 + i * 16)..], vertices[i].Y); + } + BinaryPrimitives.WriteInt32LittleEndian(polygon[(75 + 16 * vertices.Length)..], vertices.Length); + } + return slab; + } + + private static void WriteRectangularPlan(Span polygon, double left, double bottom, double right, double top, bool slab) + { + new byte[] { slab ? (byte)2 : (byte)0, 0, 2, 1, 247, 0, 0, 0, slab ? (byte)1 : (byte)0, 31, 0 }.CopyTo(polygon); + double[] envelope = [left, bottom, right, top]; + for (int i = 0; i < envelope.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(11 + 8 * i)..], envelope[i]); + BinaryPrimitives.WriteInt32LittleEndian(polygon[43..], 5); + BinaryPrimitives.WriteInt32LittleEndian(polygon[51..], 1); + BinaryPrimitives.WriteInt32LittleEndian(polygon[155..], 5); + var rectangle = new (double X, double Y)[] { (left, bottom), (right, bottom), (right, top), (left, top), (left, bottom) }; + for (int i = 0; i < rectangle.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(71 + 16 * i)..], rectangle[i].X); + BinaryPrimitives.WriteDoubleLittleEndian(polygon[(79 + 16 * i)..], rectangle[i].Y); + } + } + + private static byte[] JunctionAttribute(Guid type, ushort kind, int index, uint priority) + { + byte[] attribute = new byte[61 + 45]; + type.TryWriteBytes(attribute); + new byte[] { 0x83, 0, 3, 0, 0, 0, 1, 0 }.CopyTo(attribute, 47); + BinaryPrimitives.WriteUInt32LittleEndian(attribute.AsSpan(55), 1); + BinaryPrimitives.WriteUInt16LittleEndian(attribute.AsSpan(59), 'A'); + BinaryPrimitives.WriteUInt16LittleEndian(attribute.AsSpan(61), 1); + BinaryPrimitives.WriteInt32LittleEndian(attribute.AsSpan(63), index); + BinaryPrimitives.WriteUInt32LittleEndian(attribute.AsSpan(61 + (kind == 7 ? 41 : 35)), priority); + return Synthetic.Block(PlaBlockMode.Raw, attribute, ver: 1, kind: kind); + } + + private static byte[] WithGeometryRelations(byte[] data, params byte[][] items) + { + byte[] header = new byte[6]; + BinaryPrimitives.WriteUInt32LittleEndian(header, (uint)(3 + items.Sum(r => r.Length))); + header[4] = 1; + return Synthetic.Concat(data, header, Synthetic.Concat(items), [0]); + } + + private static byte[] GeometryRelation(byte tag, Guid key, Guid target) => + Synthetic.Concat([tag], key.ToByteArray(), target.ToByteArray()); + + private static byte[] GeometryRelationList(byte tag, Guid key, params Guid[] targets) + { + var count = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(count, targets.Length); + return Synthetic.Concat([tag], key.ToByteArray(), count, Synthetic.Concat(targets.Select(id => id.ToByteArray()).ToArray())); + } + + private static (int? Layer, string? LayerName, int? Story, string? StoryName) Location(PlaElement element) => + (element.LayerIndex, element.LayerName, element.HomeStoryIndex, element.HomeStoryName); + + private static void WriteLocation(Span record, int layer, short story) + { + BinaryPrimitives.WriteUInt16LittleEndian(record, 1); + BinaryPrimitives.WriteInt32LittleEndian(record[2..], layer); + BinaryPrimitives.WriteInt16LittleEndian(record[6..], story); + } + + private static byte[] HostRelation(Guid relation, Guid host) => + Synthetic.Concat([0x12], relation.ToByteArray(), host.ToByteArray()); + + private static byte[] StoryTable(Guid storyClass) + { + byte[] header = new byte[50]; + Assert.True(storyClass.TryWriteBytes(header)); + byte[] frame = [1, 0, 3, 0, 0, 1, 0]; + frame.CopyTo(header, 39); + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(46), 3); + byte[] row = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + byte[] endOfRow = [0, 0, 1]; + byte[] basement = Synthetic.Concat(row, ElementId("Подвал")[14..], endOfRow); + BinaryPrimitives.WriteDoubleLittleEndian(basement.AsSpan(2), -4); + byte[] unnamed = Synthetic.Concat(row, ElementId("")[14..], endOfRow); + return Synthetic.Concat(header, basement, unnamed, unnamed, [0xFF, 0xFF, 0, 0, 0, 0]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsTheFlaggedZeroMaskBodyAtItsDirectoryExtent(bool wrongGuid) + { + Guid id = Guid.NewGuid(); + byte[] body = Wall("Wall-1"); + byte[] subgroup = Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(body), ver: 1, + unpacked: (uint)body.Length, guid: wrongGuid ? Guid.NewGuid() : id, extra: 0xFFFFFFFF, kind: 1); + byte[] decodedPool = new byte[32 * 16]; + subgroup.CopyTo(decodedPool, 2 * 16); + using var doc = Open(ClassTable((1, WallClass)), ElementDirectory(false, new ObjectDirectoryRecord(1, 2, 8, id)), + Pool(decodedPool)); + + var wall = Assert.Single(doc.ReadElements()); + Assert.Equal(wrongGuid ? new PlaElement(id, "Wall", null, null, null) : new PlaElement(id, "Wall", "Wall-1", 0.25, 5), wall); + } + + [Theory] + [InlineData(false, false, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(true, false, true)] + public void ObjectsMustBeInTheDatabaseListAndOutsideTheGridList(bool storedFrame, bool truncatedGridList, bool olderLayout) + { + Guid owner = Guid.NewGuid(), placed = Guid.NewGuid(), grid = Guid.NewGuid(), orphan = Guid.NewGuid(); + byte[] root = Relationship(DatabaseClass, olderLayout ? 137 : 101, + new Guid("bd9b270b-0347-4dcf-92cf-d2d872117ba1"), placed, grid); + byte[] gridList = Relationship(GridStoreClass, 59, new Guid("d940e8f4-4d66-4faa-86a1-6bf94c703228"), grid); + if (truncatedGridList) BinaryPrimitives.WriteUInt32LittleEndian(gridList.AsSpan(82), 2); + + byte[] decodedPool = new byte[4 * 512]; + if (storedFrame) + { + byte[] frame = Synthetic.QuickLzFrame(root, root.Length, 0x46); + Synthetic.Block(PlaBlockMode.Lz, frame, ver: 1, unpacked: (uint)root.Length, guid: owner, extra: 5, kind: 2) + .CopyTo(decodedPool, 0); + } + else + Synthetic.Block(PlaBlockMode.Raw, root, ver: 1, guid: owner, extra: 5, kind: 2).CopyTo(decodedPool, 0); + + byte[] body = new byte[olderLayout ? 212 : 338]; + Assert.True(ObjectClass.TryWriteBytes(body)); + byte[] marker = [1, 0, 9, 0, 0x83, 0, 3, 0, 0, 1]; + if (olderLayout) marker[4] = 0x82; + marker.CopyTo(body, 49); + Assert.True(ObjectClass.TryWriteBytes(body.AsSpan(59))); + int layer = 49 + (olderLayout ? 45 : 171); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(layer - 2), 1); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(layer), 13); + BinaryPrimitives.WriteInt16LittleEndian(body.AsSpan(layer + 4), -2); + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(body.Length - 2), 1); + byte[] plain = Synthetic.Concat(body, ElementId("МЕБ - 001")[14..]); + byte[] packed = Synthetic.ZeroMask(plain); + Synthetic.Block(PlaBlockMode.ZeroMask, packed, ver: 1, unpacked: (uint)plain.Length, guid: placed, extra: 5, kind: 1) + .CopyTo(decodedPool, 512); + Synthetic.Block(PlaBlockMode.ZeroMask, packed, ver: 1, unpacked: (uint)plain.Length, guid: grid, extra: 5, kind: 1) + .CopyTo(decodedPool, 1024); + Synthetic.Block(PlaBlockMode.ZeroMask, packed, ver: 1, unpacked: (uint)plain.Length, guid: orphan, extra: 5, kind: 1) + .CopyTo(decodedPool, 1536); + + using var doc = Open(ClassTable((1, ObjectClass), (2, DatabaseClass), (3, GridStoreClass)), + OwnedDirectory(false, owner, 128, new(2, 0, 32, owner), new(1, 32, 32, placed), new(1, 64, 32, grid), new(1, 96, 32, orphan)), + Synthetic.Block(PlaBlockMode.Raw, gridList, ver: 1, kind: 3), Pool(decodedPool)); + + if (truncatedGridList) Assert.Throws(doc.ReadElements); + else Assert.Equal(new PlaElement(placed, "Object", "МЕБ - 001", null, null) { LayerIndex = 13, HomeStoryIndex = -2 }, + Assert.Single(doc.ReadElements())); + } + + private static byte[] Relationship(Guid recordClass, int sizeOffset, Guid listKind, params Guid[] members) + { + int offset = sizeOffset + 4; + byte[] data = new byte[offset + 23 + 16 * members.Length]; + Assert.True(recordClass.TryWriteBytes(data)); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(35), (uint)(sizeOffset - 39)); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(sizeOffset), (uint)(data.Length - offset)); + data[offset] = 1; + data[offset + 2] = 1; + Assert.True(listKind.TryWriteBytes(data.AsSpan(offset + 3))); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(offset + 19), (uint)members.Length); + for (int i = 0; i < members.Length; i++) Assert.True(members[i].TryWriteBytes(data.AsSpan(offset + 23 + 16 * i))); + return data; + } + + private static byte[] FramedElementId(Guid classGuid, int offset, string elementId) + { + var header = new byte[offset]; + byte[] marker = [1, 0, 9, 0, 0x83, 0, 3, 0, 0, 1]; + marker.CopyTo(header, 0); + Assert.True(classGuid.TryWriteBytes(header.AsSpan(marker.Length))); + BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(offset - 2), 1); + return Synthetic.Concat(header, ElementId(elementId)[14..]); + } + + internal static byte[] WallFile(Guid id) => Synthetic.Fdb( + ClassTable((1, WallClass)), ElementDirectory(false, new ObjectDirectoryRecord(1, 0, 8, id)), + Pool(Subgroup(1, id, Wall("Wall-1")))); + + private static PlaDocument Open(params byte[][] parts) => PlaDocument.Open(new MemoryStream(Synthetic.Fdb(parts))); + + private static byte[] ClassTable(params (ushort Number, Guid Class)[] classes) + { + var payload = new byte[2 + 16 * (classes.Max(entry => entry.Number) + 1)]; + foreach (var (number, guid) in classes) + Assert.True(guid.TryWriteBytes(payload.AsSpan(2 + 16 * number))); + return Synthetic.Block(PlaBlockMode.Raw, payload, ver: 1, kind: 0xFDE9); + } + + private static byte[] ElementDirectory(bool prefixed, params ObjectDirectoryRecord[] records) => + OwnedDirectory(prefixed, Guid.Empty, 32, records); + + private static byte[] OwnedDirectory(bool prefixed, Guid owner, ulong length, params ObjectDirectoryRecord[] records) + { + int start = prefixed ? 2 : 0; + byte[] header = new byte[start + 40]; + BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(start), length); + Assert.True(owner.TryWriteBytes(header.AsSpan(start + 8))); + Assert.True(new Guid("1f9b53da-bb9f-4f97-b5d9-532843923eac").TryWriteBytes(header.AsSpan(start + 24))); + var data = Synthetic.Concat(header, records.SelectMany(Synthetic.Record).ToArray()); + return Synthetic.Block(PlaBlockMode.Raw, data, ver: 1); + } + + private static byte[] Subgroup(ushort kind, Guid id, byte[] data) => + Synthetic.Block(PlaBlockMode.Raw, data, ver: 1, guid: id, kind: kind); + + private static byte[] Pool(params byte[][] subgroups) + { + byte[] data = Synthetic.Concat(subgroups); + return Synthetic.QuickLzPool(((uint)data.Length, Synthetic.QuickLzFrame(data, data.Length, 0x46))); + } + + private static byte[] ElementId(string id) => + Synthetic.Concat([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, (byte)id.Length, 0, 0, 0], + Encoding.Unicode.GetBytes(id)); + + private static byte[] Wall(string id) + { + byte[] tail = new byte[93]; + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(16), 3); + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(24), 4); + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(77), 0.25); + BinaryPrimitives.WriteDoubleLittleEndian(tail.AsSpan(85), 0.25); + return Synthetic.Concat(ElementId(id), tail); + } +} diff --git a/tests/PlaIO.Tests/PlaSceneReaderTests.cs b/tests/PlaIO.Tests/PlaSceneReaderTests.cs index 96616a6..1aa79e9 100644 --- a/tests/PlaIO.Tests/PlaSceneReaderTests.cs +++ b/tests/PlaIO.Tests/PlaSceneReaderTests.cs @@ -27,7 +27,7 @@ public void OneModelWithTheFileNameAsItsKey() Assert.StartsWith("PlaIO.Scene ", model.Producer); Assert.Equal("sample.pla", document.Title); - // The container reader decodes no elements yet, so the scene is geometry-free and property-free. + // This fixture contains only a container header and an unrelated block. Assert.Empty(document.Elements); Assert.Empty(document.Geometries); Assert.Empty(document.Instances); @@ -86,13 +86,692 @@ public void AnEmptyModelKeyThrows() Assert.Throws(() => PlaSceneReader.Read(scope.Path, new PlaSceneOptions { ModelKey = "" })); } + [Fact] + public void RejectsAMalformedClassTable() + { + byte[] file = Synthetic.Fdb(Synthetic.Block(PlaBlockMode.Raw, new byte[18], ver: 1, kind: 0xFDE9)); + using var scope = TempContainer("malformed.pln", file); + Assert.Throws(() => PlaSceneReader.Read(scope.Path)); + } + + [Theory] + [InlineData(true, 1, true)] + [InlineData(true, 2, false)] + [InlineData(false, 1, false)] + public void MapsOnlyVerifiedDoorPlacement(bool matchingHost, int placementCase, bool hasPlacement) + { + var fixture = ElementReaderTests.HostedElementsFixture(matchingHost, reciprocal: 1, invalidDimensions: 0, placementCase); + using var scope = TempContainer("door.pln", fixture.File); + + var scene = SceneJson.Read(SceneJson.Write(PlaSceneReader.Read(scope.Path).Document)); + Assert.Empty(scene.Validate()); + var door = Assert.Single(scene.Elements, element => element.SourceId == fixture.Door.ToString("D")); + var wall = Assert.Single(scene.Elements, element => element.SourceId == fixture.Wall.ToString("D")); + Assert.Equal(matchingHost ? wall.Id : (long?)null, door.ParentId); + var properties = Assert.Single(scene.PropertySets, set => set.Id == Assert.Single(door.PropertySetIds)).Properties; + (string Key, double Number)[] expected = + [ + ("door-reference-x", 3.25), + ("door-reference-y", 5), + ("door-distance-along-wall", 1.25), + ("door-sill-to-project-zero", -3.65), + ("door-sill-to-host-story", 0.35), + ]; + foreach (var (key, number) in expected) + { + var values = properties.Where(property => property.Key == "archicad:" + key); + if (hasPlacement) + { + var value = Assert.Single(values).Value; + Assert.Equal(number, value.Number); + Assert.Equal(SceneUnits.Metre, value.Unit); + } + else + Assert.Empty(values); + } + } + + [Theory] + [InlineData(0.25, 4, false, 3.5)] + [InlineData(0.25, 4, true, 3.5)] + [InlineData(-0.25, 4, false, 3.625)] + [InlineData(0.25, 2.5, false, 3.75)] + public void BuildsClosedWallsAroundThroughDoorCuts(double sill, double secondStation, bool reverse, double expectedVolume) + { + var (file, wallId) = ElementReaderTests.WallWithDoorCutsFixture(sill, secondStation, reverse); + using var scope = TempContainer("wall.pln", file); + using var doc = PlaDocument.Open(scope.Path); + var elements = doc.ReadElements(); + var element = Assert.Single(elements, e => e.Guid == wallId); + Assert.Equal(new PlaBoundingBox(0, 1.8125, -3.75, 6, 2.0625, -0.75), element.BoundingBox); + Assert.All(elements.Where(e => e.Type == "Door"), door => + { + Assert.Equal(wallId, door.HostGuid); + Assert.NotNull(door.DoorPlacement); + Assert.Equal(new PlaDoorWallHoleDimensions(1, 2), door.DoorWallHoleDimensions); + }); + var solid = Assert.IsType(element.WallExtrusion); + Assert.Equal(expectedVolume, solid.Volume, 12); + Assert.Equal((-3.75, -0.75, 0.25, 3.25), ( + element.BottomElevationToProjectZero, element.TopElevationToProjectZero, + element.BottomElevationToHomeStory, element.TopElevationToHomeStory)); + + var scene = SceneJson.Read(SceneJson.Write(PlaSceneReader.Read(scope.Path).Document)); + Assert.Empty(scene.Validate()); + var wall = Assert.Single(scene.Elements, e => e.SourceId == wallId.ToString("D")); + var instance = Assert.Single(scene.Instances); + Assert.Equal(wall.Id, instance.ElementId); + Assert.Equal(expectedVolume, MeasureClosedMesh(Assert.Single(scene.Geometries), measureHorizontalCaps: false).Volume, 12); + Assert.Equal(new Vector3d(0, 1.8125, -3.75), scene.ComputeBounds().Min); + Assert.Equal(new Vector3d(6, 2.0625, -0.75), scene.ComputeBounds().Max); + } + + [Theory] + [InlineData(0.125, false)] + [InlineData(0, true)] + public void WithholdsDoorCutWallMeshesWhenTheCutOrAnotherRelationshipIsUnsupported(double oversize, bool unsupportedRelation) + { + var (file, wallId) = ElementReaderTests.WallWithDoorCutsFixture(0.25, 4, reverse: false, oversize, unsupportedRelation); + using var scope = TempContainer("wall.pln", file); + using var doc = PlaDocument.Open(scope.Path); + var element = Assert.Single(doc.ReadElements(), e => e.Guid == wallId); + Assert.Null(element.WallExtrusion); + Assert.Null(element.BoundingBox); + Assert.Null(element.BottomElevationToProjectZero); + Assert.Null(element.TopElevationToHomeStory); + Assert.Empty(PlaSceneReader.Read(scope.Path).Document.Instances); + } + + [Fact] + public void MapsTheVerifiedWallTopWhenDoorCutsCoverTheWholeBottom() + { + var (file, wallId) = ElementReaderTests.WallWithDoorCutsFixture(0, 4.5, reverse: false, width: 3, firstStation: 1.5); + using var scope = TempContainer("wall.pln", file); + var scene = SceneJson.Read(SceneJson.Write(PlaSceneReader.Read(scope.Path).Document)); + Assert.Empty(scene.Validate()); + Assert.Empty(scene.Instances); + + var wall = Assert.Single(scene.Elements, e => e.SourceId == wallId.ToString("D")); + var properties = scene.PropertySets.Where(set => wall.PropertySetIds.Contains(set.Id)).SelectMany(set => set.Properties).ToArray(); + Assert.DoesNotContain(properties, p => p.Key is "archicad:bottom-to-project-zero" or "archicad:bottom-to-home-story"); + var topProject = Assert.Single(properties, p => p.Key == "archicad:top-to-project-zero").Value; + var topStory = Assert.Single(properties, p => p.Key == "archicad:top-to-home-story").Value; + Assert.Equal((-0.75, SceneUnits.Metre), (topProject.Number, topProject.Unit)); + Assert.Equal((3.25, SceneUnits.Metre), (topStory.Number, topStory.Unit)); + } + + [Theory] + [InlineData(false, 4.0)] + [InlineData(true, 3.9375)] + public void MapsLevelsPropertiesAndAClosedSlabMesh(bool concave, double volume) + { + var fixture = ElementReaderTests.SlabSceneFixture(concave, beveled: false); + using var scope = TempContainer("floor.pln", fixture.File); + + var result = PlaSceneReader.Read(scope.Path); + var scene = SceneJson.Read(SceneJson.Write(result.Document)); + Assert.Empty(result.Diagnostics); + Assert.Empty(scene.Validate()); + var element = Assert.Single(scene.Elements); + Assert.Equal(fixture.Element.ToString("D"), element.SourceId); + Assert.Equal("Slab", element.Category); + Assert.Equal("S", element.Name); + Assert.Equal(2, scene.Levels.Count); + var level = Assert.Single(scene.Levels, level => level.Id == element.LevelId); + Assert.Equal("Подвал", level.Name); + Assert.Equal(-4, level.Elevation); + var properties = Assert.Single(scene.PropertySets); + Assert.Equal(properties.Id, Assert.Single(element.PropertySetIds)); + Assert.Equal("archicad:instance", properties.Key); + Assert.Equal(-1, Assert.Single(properties.Properties, p => p.Key == "archicad:home-story-index").Value.Integer); + var netVolume = Assert.Single(properties.Properties, p => p.Key == "archicad:slab-net-volume").Value; + Assert.Equal(SceneUnits.CubicMetre, netVolume.Unit); + Assert.Equal(volume, netVolume.Number); + var mesh = Assert.Single(scene.Geometries); + var instance = Assert.Single(scene.Instances); + Assert.Equal(element.Id, instance.ElementId); + Assert.Equal(mesh.Id, instance.GeometryId); + Assert.Equal(concave ? 20 : 12, mesh.Indices.Count / 3); + Assert.Equal(new Vector3d(-1, -1, -4.5), scene.ComputeBounds().Min); + Assert.Equal(new Vector3d(1, 1, -3.5), scene.ComputeBounds().Max); + + var (measuredVolume, top, bottom) = MeasureClosedMesh(mesh); + Assert.Equal(volume, measuredVolume, 12); + Assert.Equal(volume, top, 12); + Assert.Equal(volume, bottom, 12); + } + + [Fact] + public void TessellatesTheConcaveSlabAroundBothSavedHoles() + { + var fixture = ElementReaderTests.SlabWithHolesSceneFixture(); + using var scope = TempContainer("holes.pln", fixture.File); + var result = PlaSceneReader.Read(scope.Path); + Assert.Empty(result.Diagnostics); + var mesh = Assert.Single(result.Document.Geometries); + Assert.Equal(60, mesh.Indices.Count / 3); + Assert.Equal((10, 10, 10), MeasureClosedMesh(mesh)); + Assert.Empty(result.Document.Validate()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ExportsTheRotatedWallPrismOnlyWhenItsConnectionsAreVerified(bool joined) + { + var (file, wallId) = ElementReaderTests.WallReferenceSceneFixture(0, flipped: false, 0, joined, inconsistentContour: false); + using var scope = TempContainer("wall.pln", file); + var result = PlaSceneReader.Read(scope.Path); + var element = Assert.Single(result.Document.Elements); + Assert.Equal(wallId.ToString("D"), element.SourceId); + if (joined) + { + Assert.Empty(result.Document.Instances); + Assert.Empty(result.Document.Geometries); + Assert.Equal("geometry-incomplete", Assert.Single(result.Diagnostics).Code); + return; + } + + var mesh = Assert.Single(result.Document.Geometries); + var instance = Assert.Single(result.Document.Instances); + Assert.Equal(element.Id, instance.ElementId); + Assert.Equal((3.75, 0.75, 0.75), MeasureClosedMesh(mesh)); + var bounds = result.Document.ComputeBounds(); + Assert.Equal(new Vector3d(1, -3, -3.75), bounds.Min); + Assert.Equal(new Vector3d(4.2, 1.15, -0.75), bounds.Max); + var volume = Assert.Single(Assert.Single(result.Document.PropertySets).Properties, p => p.Key == "archicad:wall-net-volume"); + Assert.Equal(SceneUnits.CubicMetre, volume.Value.Unit); + Assert.Equal(3.75, volume.Value.Number); + Assert.Empty(result.Document.Validate()); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RetainsTheWallSolidWhenItsZoneCalculationIdentifiesTheSameWall(bool valid) + { + var (file, wallId) = ElementReaderTests.WallReferenceSceneFixture(0, flipped: false, 0, + joined: false, inconsistentContour: false, validZoneCalculation: valid); + using var scope = TempContainer("zone-boundary.pln", file); + var scene = PlaSceneReader.Read(scope.Path).Document; + var wall = Assert.Single(scene.Elements, e => e.SourceId == wallId.ToString("D")); + if (!valid) + { + Assert.Empty(scene.Instances); + return; + } + Assert.Equal(wall.Id, Assert.Single(scene.Instances).ElementId); + Assert.Equal((3.75, 0.75, 0.75), MeasureClosedMesh(Assert.Single(scene.Geometries))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void JoinsTheProfileFillsAlongTheirSharedEdgeAndKeepsTheHole(bool overlapping) + { + var (file, wallId) = ElementReaderTests.ProfiledWallSceneFixture(overlapping); + using var scope = TempContainer("profiled-wall.pla", file); + using var document = PlaDocument.Open(scope.Path); + var wall = Assert.Single(document.ReadElements(), e => e.Guid == wallId); + Assert.NotNull(wall.WallProfile); + var scene = PlaSceneReader.Read(scope.Path).Document; + Assert.Empty(scene.Validate()); + if (overlapping) + { + Assert.Null(wall.WallExtrusion); + Assert.Empty(scene.Instances); + return; + } + + var extrusion = Assert.IsType(wall.WallExtrusion); + Assert.Equal(2, Assert.Single(extrusion.Sections).Rings.Count); + Assert.Equal(24, extrusion.Volume); + Assert.Equal((24, 12, 12), MeasureClosedMesh(Assert.Single(scene.Geometries))); + Assert.Equal(new Vector3d(-1, -5, -3.75), scene.ComputeBounds().Min); + Assert.Equal(new Vector3d(1, 0, -0.75), scene.ComputeBounds().Max); + } + + [Theory] + [InlineData(0, 2, 3.75, null, false)] + [InlineData(0, 2, 3.75, null, true)] + [InlineData(4, 2, 3.75, 0.9375, false)] + [InlineData(5, 0, null, null, false)] + [InlineData(5, 0, null, null, true)] + [InlineData(7, 2, 3.75, 1.0, false)] + [InlineData(9, 0, null, null, false)] + [InlineData(10, 1, 3.75, null, false)] + public void MeshesTheVerifiedSlabAroundASeparateThroughOpening(int variation, int rings, double? volume, + double? secondaryVolume, bool slabAlignedFrame) + { + var (file, opening, slab, _, secondary) = ElementReaderTests.SlabOpeningFixture(variation, rectangular: true, + slabAlignedFrame: slabAlignedFrame); + using var scope = TempContainer("aperture.pln", file); + using var document = PlaDocument.Open(scope.Path); + var elements = document.ReadElements(); + var geometry = Assert.IsType(Assert.Single(elements, e => e.Guid == slab).SlabGeometry); + Assert.Single(geometry.Rings); + Assert.Equal(-4.5, geometry.Bottom); + Assert.Equal(-3.5, geometry.Top); + Assert.False(geometry.IsUncutVerticalPrism); + if (rings == 0) Assert.Null(geometry.VerticalPrisms); + else Assert.Equal(rings, Assert.Single(geometry.VerticalPrisms!).Rings.Count); + if (slabAlignedFrame && rings != 0) + { + var aperture = Assert.IsType(Assert.Single(elements, e => e.Guid == opening).OpeningGeometry); + Assert.Equal(new PlaPlanPoint(0.25, -0.375), aperture.Origin); + Assert.Equal(-0.625, Assert.Single(aperture.Rings!).Min(p => p.Y)); + Assert.Equal(-0.125, Assert.Single(aperture.Rings!).Max(p => p.Y)); + } + + var scene = PlaSceneReader.Read(scope.Path).Document; + Assert.Empty(scene.Validate()); + Assert.Equal((volume.HasValue ? 1 : 0) + (secondaryVolume.HasValue ? 1 : 0), scene.Instances.Count); + CheckSlabMesh(slab, volume, 1); + if (secondaryVolume is not null) CheckSlabMesh(secondary, secondaryVolume, 0.25); + + void CheckSlabMesh(Guid sourceId, double? expected, double height) + { + var element = Assert.Single(scene.Elements, e => e.SourceId == sourceId.ToString("D")); + if (expected is not { } value) + { + Assert.DoesNotContain(scene.Instances, i => i.ElementId == element.Id); + return; + } + var instance = Assert.Single(scene.Instances, i => i.ElementId == element.Id); + var mesh = Assert.Single(scene.Geometries, m => m.Id == instance.GeometryId); + var measured = MeasureClosedMesh(mesh); + Assert.Equal(value, measured.Volume, 12); + Assert.Equal(value / height, measured.Top, 12); + Assert.Equal(value / height, measured.Bottom, 12); + } + } + + [Theory] + [InlineData((int)ElementReaderTests.SlabColumnContact.PartialInterior, 0, 0, 3.90625, 0)] + [InlineData((int)ElementReaderTests.SlabColumnContact.Interior, 1, 2, 3.875, 1)] + [InlineData((int)ElementReaderTests.SlabColumnContact.Edge, 1, 1, 3.9375, 1)] + [InlineData((int)ElementReaderTests.SlabColumnContact.Split, 2, 1, 3.5, 1)] + [InlineData((int)ElementReaderTests.SlabColumnContact.TrimOuterEdge, 1, 1, 3.75, 0.875)] + public void MapsTheEvaluatedSlabWhenTheColumnCutsEverySkin(int contact, int parts, int ringsPerPart, double volume, + double maxX) + { + var (file, slabId) = ElementReaderTests.SlabColumnSceneFixture(contact: (ElementReaderTests.SlabColumnContact)contact); + using var scope = TempContainer("column-cut.pla", file); + using var document = PlaDocument.Open(scope.Path); + var slab = Assert.IsType(Assert.Single(document.ReadElements(), e => e.Guid == slabId).SlabGeometry); + Assert.Single(slab.Rings); + Assert.Equal(1, slab.Rings[0].Max(p => p.X)); + Assert.False(slab.IsUncutVerticalPrism); + Assert.Equal(volume, Assert.IsType(slab.Volume), 12); + if (parts == 0) Assert.Null(slab.VerticalPrisms); + else + { + Assert.NotNull(slab.VerticalPrisms); + Assert.Equal(parts, slab.VerticalPrisms.Count); + Assert.All(slab.VerticalPrisms, prism => Assert.Equal(ringsPerPart, prism.Rings.Count)); + } + var result = PlaSceneReader.Read(scope.Path); + if (parts == 0) Assert.Equal("geometry-incomplete", Assert.Single(result.Diagnostics).Code); + else Assert.Empty(result.Diagnostics); + var scene = result.Document; + var element = Assert.Single(scene.Elements, e => e.Category == "Slab"); + var slabInstances = scene.Instances.Where(i => i.ElementId == element.Id).ToArray(); + Assert.Equal(parts, slabInstances.Length); + Assert.Equal(parts + 1, scene.Geometries.Count); + var measured = slabInstances.Select(i => MeasureClosedMesh(scene.Geometries.Single(g => g.Id == i.GeometryId))).ToArray(); + if (parts != 0) + { + Assert.Equal(volume, measured.Sum(m => m.Volume), 12); + Assert.Equal(volume, measured.Sum(m => m.Top), 12); + Assert.Equal(volume, measured.Sum(m => m.Bottom), 12); + Assert.Equal(maxX, slabInstances.Max(i => scene.Geometries.Single(g => g.Id == i.GeometryId).Vertices + .Max(v => (i.Transform ?? Transform3d.Identity).Apply(v).X)), 12); + } + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column"); + var solid = Assert.IsType(column.ColumnExtrusion); + var sceneColumn = Assert.Single(scene.Elements, e => e.Category == "Column"); + var instance = Assert.Single(scene.Instances, i => i.ElementId == sceneColumn.Id); + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + var transform = Assert.IsType(instance.Transform); + Assert.Equal(solid.Volume, MeasureClosedMesh(mesh).Volume, 12); + Assert.Equal(solid.BoundingBox.ZMin, mesh.Vertices.Min(v => transform.Apply(v).Z), 12); + Assert.Equal(solid.BoundingBox.XMax, mesh.Vertices.Max(v => transform.Apply(v).X), 12); + Assert.Contains(scene.PropertySets.Where(p => sceneColumn.PropertySetIds.Contains(p.Id)).SelectMany(p => p.Properties), + p => p.Key == "archicad:column-net-volume" && p.Value.Number == solid.Volume); + Assert.Empty(scene.Validate()); + } + + [Fact] + public void MapsASlopedColumnCapInProjectCoordinates() + { + var (file, _) = ElementReaderTests.SlabColumnSceneFixture(contact: ElementReaderTests.SlabColumnContact.Split, + slopeUpperCap: true); + using var scope = TempContainer("sloped-cap.pln", file); + var scene = PlaSceneReader.Read(scope.Path).Document; + var column = Assert.Single(scene.Elements, e => e.Category == "Column"); + var instance = Assert.Single(scene.Instances, i => i.ElementId == column.Id); + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + var frame = Assert.IsType(instance.Transform); + var vertices = mesh.Vertices.Select(frame.Apply).ToArray(); + Assert.Equal(-5, vertices.Min(v => v.Z)); + Assert.Equal(-2.9375, vertices.Max(v => v.Z)); + foreach (var point in vertices.Where(v => v.Z > -5)) + Assert.Equal(-3 - 0.5 * point.Y, point.Z, 12); + Assert.Equal(1, MeasureClosedMesh(mesh).Volume, 12); + Assert.Empty(scene.Validate()); + } + + [Theory] + [InlineData(true, 900, false, 0.25, 36)] + [InlineData(true, 900, false, 0.4, 48)] + [InlineData(true, 900, false, 0.02, 12)] + [InlineData(false, 900, false, 0.25, 36)] + [InlineData(true, 1200, false, 0.25, 36)] + [InlineData(true, 900, true, 0.25, 36)] + public void MapsAValidatedCircularColumn(bool validArcs, int slabPriority, bool wrongOwner, double radius, int listedSides) + { + var (file, _) = ElementReaderTests.SlabColumnSceneFixture(slabPriority, wrongOwner, validCircularSection: validArcs, + circularRadius: radius); + using var scope = TempContainer("circular-column.pln", file); + using var document = PlaDocument.Open(scope.Path); + var element = Assert.Single(document.ReadElements(), e => e.Type == "Column"); + var scene = PlaSceneReader.Read(scope.Path).Document; + var column = Assert.Single(scene.Elements, e => e.SourceId == element.Guid.ToString("D")); + if (!validArcs || slabPriority > 1000 || wrongOwner) + { + Assert.Null(element.ColumnExtrusion); + Assert.DoesNotContain(scene.Instances, i => i.ElementId == column.Id); + return; + } + + var cylinder = Assert.IsType(element.ColumnExtrusion); + Assert.Equal(radius, cylinder.CircularRadius); + double area = Math.PI * radius * radius; + Assert.Equal(area * 1.25, cylinder.Volume); + double listedArea = listedSides * (radius * radius) / 2 * Math.Sin(Math.Tau / listedSides); + Assert.Equal(listedArea, cylinder.ScheduledCapArea!.Value, 14); + double listedPerimeter = 2 * listedSides * radius * Math.Sin(Math.PI / listedSides); + Assert.Equal(listedPerimeter * 1.25, cylinder.ScheduledLateralArea!.Value, 14); + Assert.Equal(listedArea * 1.25, cylinder.ScheduledVolume!.Value, 14); + var properties = scene.PropertySets.Where(set => column.PropertySetIds.Contains(set.Id)).SelectMany(set => set.Properties).ToArray(); + Assert.Equal(cylinder.Volume, Assert.Single(properties, p => p.Key == "archicad:column-geometric-volume").Value.Number); + Assert.Equal(cylinder.ScheduledVolume, Assert.Single(properties, p => p.Key == "archicad:column-net-volume").Value.Number); + Assert.Equal((-0.25, 1, -4.25, -3), (element.BottomElevationToHomeStory, element.TopElevationToHomeStory, + element.BottomElevationToProjectZero, element.TopElevationToProjectZero)); + var instance = Assert.Single(scene.Instances, i => i.ElementId == column.Id); + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + var frame = Assert.IsType(instance.Transform); + var vertices = mesh.Vertices.Select(frame.Apply).ToArray(); + Assert.Equal(new PlaBoundingBox(1 - radius, -radius, -4.25, 1 + radius, radius, -3), cylinder.BoundingBox); + Assert.Equal(1 - radius, vertices.Min(p => p.X), 14); + Assert.Equal(1 + radius, vertices.Max(p => p.X), 14); + Assert.Equal(-radius, vertices.Min(p => p.Y), 14); + Assert.Equal(radius, vertices.Max(p => p.Y), 14); + Assert.Equal((-4.25, -3), (vertices.Min(p => p.Z), vertices.Max(p => p.Z))); + var (volume, top, bottom) = MeasureClosedMesh(mesh); + double perimeter = Math.Tau * radius, surface = perimeter * 1.25 + 2 * area; + Assert.InRange(volume, cylinder.Volume - 1e-7 * surface, cylinder.Volume); + Assert.InRange(top, area - 1e-7 * perimeter, area); + Assert.Equal(top, bottom, 12); + var ring = vertices.Take(vertices.Length / 2).ToArray(); + for (int i = 0; i < ring.Length; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Length]; + double midpointRadius = double.Hypot((a.X + b.X) / 2 - cylinder.Origin.X, (a.Y + b.Y) / 2 - cylinder.Origin.Y); + Assert.InRange(radius - midpointRadius, 0, 1e-7); + } + Assert.Empty(scene.Validate()); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(true, true)] + public void SeparatesFullColumnSpansAfterBeamCuts(bool otherColumn, bool wrongOtherOwner) + { + using var scope = TempContainer("column-spans.pln", ElementReaderTests.ColumnBeamBandsFixture(false, otherColumn, wrongOtherOwner)); + using var document = PlaDocument.Open(scope.Path); + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column" && e.MemberProfile is not null); + var scene = PlaSceneReader.Read(scope.Path).Document; + var element = Assert.Single(scene.Elements, e => e.SourceId == column.Guid.ToString("D")); + var instances = scene.Instances.Where(i => i.ElementId == element.Id).ToArray(); + if (wrongOtherOwner) + { + Assert.Null(column.ColumnExtrusion); + Assert.Null(column.ColumnCutMesh); + Assert.Empty(instances); + return; + } + + var solid = Assert.IsType(column.ColumnExtrusion); + Assert.Equal(new PlaColumnSpan[] { new(-3.25, -2.5), new(-1.5, 0) }, solid.Spans); + Assert.Equal((0.75, 4, -3.25, 0), (column.BottomElevationToHomeStory, column.TopElevationToHomeStory, + column.BottomElevationToProjectZero, column.TopElevationToProjectZero)); + Assert.Equal(0.5625, solid.Volume); + Assert.Equal(2, instances.Length); + double volume = 0; + foreach (var (instance, span) in instances.Zip(solid.Spans!)) + { + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + var frame = Assert.IsType(instance.Transform); + var heights = mesh.Vertices.Select(v => frame.Apply(v).Z).ToArray(); + Assert.Equal((span.Bottom, span.Top), (heights.Min(), heights.Max())); + volume += MeasureClosedMesh(mesh).Volume; + } + Assert.Equal(solid.Volume, volume, 12); + Assert.Empty(scene.Validate()); + } + + [Fact] + public void KeepsAProfiledColumnWhenVerifiedBeamSweepsMissIt() + { + using var scope = TempContainer("column-clear-beams.pln", ElementReaderTests.ColumnBeamBandsFixture( + partialCut: false, otherColumn: false, wrongOtherOwner: false, clearBeams: true)); + using var document = PlaDocument.Open(scope.Path); + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column"); + var solid = Assert.IsType(column.ColumnExtrusion); + Assert.Null(solid.Spans); + Assert.Equal(new PlaBoundingBox(-0.25, -0.25, -4, 0.25, 0.25, 0), solid.BoundingBox); + Assert.Equal(1, solid.Volume); + } + + [Theory] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.EqualTee, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.WeakerTee, 0.625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.RepeatedWeakerTee, 0.625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.DifferentHeightTee, null)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.TrimmedThroughTee, null)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.AngledTee, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.AngledTeeNearCap, 0.375)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.AngledWeakerTee, 0.626923525400276)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.MiterAway, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.MiterAtFace, null)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.EqualMiter, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.EqualMiterWithWeakPeer, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.EqualMiterWithDifferentWeakPeer, null)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.WeakerOverlap, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.SeparateEqualOverlap, 0.5625)] + [InlineData((int)ElementReaderTests.ColumnBeamEnd.EqualOverlap, null)] + public void CutsAProfiledColumnWithConnectedRectangularBeams(int end, double? volume) + { + using var scope = TempContainer("column-beam-junction.pln", ElementReaderTests.ColumnBeamBandsFixture( + partialCut: false, otherColumn: false, wrongOtherOwner: false, beamEnd: (ElementReaderTests.ColumnBeamEnd)end)); + using var document = PlaDocument.Open(scope.Path); + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column"); + var scene = PlaSceneReader.Read(scope.Path).Document; + var owner = Assert.Single(scene.Elements, e => e.SourceId == column.Guid.ToString("D")); + var meshes = scene.Instances.Where(i => i.ElementId == owner.Id) + .Select(i => Assert.Single(scene.Geometries, g => g.Id == i.GeometryId)).ToArray(); + if (volume is null) + { + Assert.Null(column.ColumnCutMesh); + Assert.Null(column.ColumnExtrusion); + Assert.Empty(meshes); + return; + } + + double? evaluatedVolume = column.ColumnCutMesh?.Volume ?? column.ColumnExtrusion?.Volume; + Assert.NotNull(evaluatedVolume); + Assert.Equal(volume.Value, evaluatedVolume.Value, 12); + Assert.Equal(volume.Value, meshes.Sum(g => MeasureClosedMesh(g, measureHorizontalCaps: false).Volume), 12); + var elevations = end == (int)ElementReaderTests.ColumnBeamEnd.AngledTeeNearCap ? (2.5, 4, -1.5, 0) : (0.75, 4, -3.25, 0); + Assert.Equal(elevations, (column.BottomElevationToHomeStory, column.TopElevationToHomeStory, + column.BottomElevationToProjectZero, column.TopElevationToProjectZero)); + Assert.Empty(scene.Validate()); + } + + [Theory] + [InlineData(false, false, false)] + [InlineData(false, false, true)] + [InlineData(true, false, false)] + [InlineData(true, true, false)] + public void CutsAProfiledColumnWithAHorizontalPartialBeam(bool concave, bool wrongOwner, bool skewed) + { + using var scope = TempContainer("column-partial-beam.pln", ElementReaderTests.ColumnBeamBandsFixture( + partialCut: true, otherColumn: true, wrongOtherOwner: wrongOwner, concaveProfile: concave, skewedBeam: skewed)); + using var document = PlaDocument.Open(scope.Path); + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column" && e.MemberProfile is not null); + var scene = PlaSceneReader.Read(scope.Path).Document; + var owner = Assert.Single(scene.Elements, e => e.SourceId == column.Guid.ToString("D")); + if (wrongOwner) + { + Assert.Null(column.ColumnCutMesh); + Assert.DoesNotContain(scene.Instances, i => i.ElementId == owner.Id); + return; + } + + var cut = Assert.IsType(column.ColumnCutMesh); + var instance = Assert.Single(scene.Instances, i => i.ElementId == owner.Id); + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + Assert.Equal((0.75, 4, -3.25, 0), (column.BottomElevationToHomeStory, column.TopElevationToHomeStory, + column.BottomElevationToProjectZero, column.TopElevationToProjectZero)); + Assert.Equal(new PlaBoundingBox(-0.25, -0.25, -3.25, 0.25, 0.25, 0), cut.BoundingBox); + Assert.Equal(new PlaBoundingBox(-0.25, -0.25, -4, 0.25, 0.25, 0), column.BoundingBox); + double expected = concave ? 0.515625 : skewed ? 0.8125 - Math.Sqrt(17) / 32 : 0.6875; + Assert.Equal(expected, cut.Volume, 12); + Assert.Equal(cut.Volume, MeasureClosedMesh(mesh, measureHorizontalCaps: false).Volume, 12); + Assert.Empty(scene.Validate()); + } + + [Theory] + [InlineData(false, null)] + [InlineData(true, null)] + [InlineData(false, true)] + [InlineData(false, false)] + public void CutsAnObliqueColumnWithAnInclinedPartialBeam(bool wrongOwner, bool? validWallLabel) + { + using var scope = TempContainer("oblique-column.pln", ElementReaderTests.ColumnBeamBandsFixture( + partialCut: true, otherColumn: true, wrongOtherOwner: wrongOwner, oblique: true, validWallLabel)); + using var document = PlaDocument.Open(scope.Path); + var column = Assert.Single(document.ReadElements(), e => e.Type == "Column" && e.MemberProfile is not null); + var scene = PlaSceneReader.Read(scope.Path).Document; + var owner = Assert.Single(scene.Elements, e => e.SourceId == column.Guid.ToString("D")); + if (wrongOwner || validWallLabel == false) + { + Assert.Null(column.ColumnCutMesh); + Assert.DoesNotContain(scene.Instances, i => i.ElementId == owner.Id); + return; + } + + var cut = Assert.IsType(column.ColumnCutMesh); + var instance = Assert.Single(scene.Instances, i => i.ElementId == owner.Id); + var mesh = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId); + Assert.Equal((0.75, 4, -3.25, 0), (column.BottomElevationToHomeStory, column.TopElevationToHomeStory, + column.BottomElevationToProjectZero, column.TopElevationToProjectZero)); + Assert.Equal(new PlaBoundingBox(-0.25, -0.25, -4, 0.25, 0.25, 0), column.BoundingBox); + Assert.Equal(0.8125 - Math.Sqrt(17) / 32, cut.Volume, 12); + Assert.Equal(cut.Volume, MeasureClosedMesh(mesh, measureHorizontalCaps: false).Volume, 12); + Assert.Empty(scene.Validate()); + } + + private static (double Volume, double Top, double Bottom) MeasureClosedMesh(SceneGeometry mesh, bool measureHorizontalCaps = true) + { + double signedVolume = 0, top = 0, bottom = 0; + var edges = new Dictionary<(int, int), (int Count, int Orientation)>(); + for (int i = 0; i < mesh.Indices.Count; i += 3) + { + var a = mesh.Vertices[mesh.Indices[i]]; + var b = mesh.Vertices[mesh.Indices[i + 1]]; + var c = mesh.Vertices[mesh.Indices[i + 2]]; + signedVolume += a.X * (b.Y * c.Z - b.Z * c.Y) + + a.Y * (b.Z * c.X - b.X * c.Z) + a.Z * (b.X * c.Y - b.Y * c.X); + if (measureHorizontalCaps && a.Z == b.Z && b.Z == c.Z) + { + double area = ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)) / 2; + Assert.True(a.Z == 0 ? area < 0 : area > 0); + if (a.Z == 0) bottom -= area; + else top += area; + } + for (int j = 0; j < 3; j++) + { + int from = mesh.Indices[i + j], to = mesh.Indices[i + (j + 1) % 3]; + Assert.NotEqual(from, to); + var key = (Math.Min(from, to), Math.Max(from, to)); + var (count, orientation) = edges.GetValueOrDefault(key); + edges[key] = (count + 1, orientation + (from < to ? 1 : -1)); + } + } + Assert.All(edges.Values, e => Assert.Equal((2, 0), e)); + return (signedVolume / 6, top, bottom); + } + + [Fact] + public void KeepsSlabMetadataWithoutCreatingAMeshForAnUnverifiedSolid() + { + var fixture = ElementReaderTests.SlabSceneFixture(concave: false, beveled: true); + using var scope = TempContainer("beveled.pla", fixture.File); + var result = PlaSceneReader.Read(scope.Path); + Assert.Single(result.Document.Elements); + Assert.Empty(result.Document.Geometries); + Assert.Empty(result.Document.Instances); + Assert.Equal("geometry-incomplete", Assert.Single(result.Diagnostics).Code); + var properties = Assert.Single(result.Document.PropertySets).Properties; + Assert.Contains(properties, p => p.Key == "archicad:slab-outline-area"); + Assert.DoesNotContain(properties, p => p.Key == "archicad:slab-net-volume"); + } + + [Fact] + public void MapsOnlyVerifiedClassificationAssignments() + { + var fixture = ElementReaderTests.ClassificationFixture(); + using var scope = TempContainer("classes.pln", fixture.File); + var scene = PlaSceneReader.Read(scope.Path).Document; + var classified = Assert.Single(scene.Elements, e => e.SourceId == fixture.Classified.ToString("D")); + var unclassified = Assert.Single(scene.Elements, e => e.SourceId == fixture.Unclassified.ToString("D")); + var set = Assert.Single(scene.PropertySets, s => s.Key == "archicad:classifications"); + Assert.Contains(set.Id, classified.PropertySetIds); + Assert.DoesNotContain(set.Id, unclassified.PropertySetIds); + Assert.Equal(fixture.Leaf.ToString("D"), + Assert.Single(set.Properties, p => p.Key == $"archicad:classification:{fixture.First:D}").Value.Text); + } + + [Theory] + [InlineData(null, 0.5)] + [InlineData("unlinked override", 0.125)] + public void MapsApplicableUserPropertyValuesAndLeavesUndefinedValuesOut(string? fixtureError, double expectedLength) + { + var fixture = ElementReaderTests.PropertyCatalogFixture(fixtureError, withOverride: true, classified: true); + using var scope = TempContainer("properties.pln", fixture.File); + var scene = PlaSceneReader.Read(scope.Path).Document; + var set = Assert.Single(scene.PropertySets, s => s.Key == $"archicad:group:{fixture.Group:D}"); + Assert.Contains(set.Id, Assert.Single(scene.Elements).PropertySetIds); + Assert.Equal("Параметры", set.Name); + Assert.Equal(2, set.Properties.Count); + var length = Assert.Single(set.Properties, p => p.Key == $"archicad:property:{fixture.Length:D}").Value; + Assert.Equal(SceneValueKind.Number, length.Kind); + Assert.Equal(SceneUnits.Metre, length.Unit); + Assert.Equal(expectedLength, length.Number); + Assert.Equal("Étage", Assert.Single(set.Properties, p => p.Key == $"archicad:property:{fixture.Single:D}").Value.Text); + } + /// A synthetic container written to a file of the given name in its own temporary directory. - private static TempScope TempContainer(string fileName) + private static TempScope TempContainer(string fileName, byte[]? bytes = null) { var directory = Path.Combine(Path.GetTempPath(), $"plaio-scene-{Guid.NewGuid():N}"); Directory.CreateDirectory(directory); var path = Path.Combine(directory, fileName); - File.WriteAllBytes(path, Synthetic.Fdb(Synthetic.Block(PlaBlockMode.Raw, [0x01, 0x02, 0x03]))); + File.WriteAllBytes(path, bytes ?? Synthetic.Fdb(Synthetic.Block(PlaBlockMode.Raw, [0x01, 0x02, 0x03]))); return new TempScope(path, directory); } From 32721371bfd84207f0b5aff215425a97d20c4d6c Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:19 +0300 Subject: [PATCH 2/3] Resolve wall caps cut by slabs and openings --- docs/public-api.md | 6 +- src/PlaIO/Internal/ElementReader.SlabCuts.cs | 2 +- .../Internal/ElementReader.SlabOpenings.cs | 4 +- .../ElementReader.WallSlabOperations.cs | 71 +++++++++++++------ .../ElementReaderTests.JoinedSlabCaps.cs | 69 ++++++++++++++++++ tests/PlaIO.Tests/ElementReaderTests.cs | 4 +- 6 files changed, 130 insertions(+), 26 deletions(-) create mode 100644 tests/PlaIO.Tests/ElementReaderTests.JoinedSlabCaps.cs diff --git a/docs/public-api.md b/docs/public-api.md index 5189227..17113a0 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -216,12 +216,16 @@ may remove material from a slab, PlaIO evaluates the cuts with the full saved sl 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. A verified separate opening +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 diff --git a/src/PlaIO/Internal/ElementReader.SlabCuts.cs b/src/PlaIO/Internal/ElementReader.SlabCuts.cs index 35cd8f0..3c2d966 100644 --- a/src/PlaIO/Internal/ElementReader.SlabCuts.cs +++ b/src/PlaIO/Internal/ElementReader.SlabCuts.cs @@ -150,7 +150,7 @@ private static bool SlabContactKeepsCuttingBand(ModelGeometry geometry, Guid sla return geometry.Read(id, PropertyOverrideClass) is { } property && ReadSingleRelation(property, key, requireSection: true) == slab; if (key == CutElementRelation || key == OpeningHostRelation) - return SlabOpeningMissesStrip(geometry, slab, key, id, footprint, home, band); + return SlabOpeningMissesStrip(geometry, slab, key, id, footprint, home, band, out _); if (key == SlabLevelDimensionRelation) return geometry.Read(id, SlabLevelDimensionClass) is { } dimension && ReadSingleRelation(dimension, key, requireSection: true) == slab; diff --git a/src/PlaIO/Internal/ElementReader.SlabOpenings.cs b/src/PlaIO/Internal/ElementReader.SlabOpenings.cs index 08bda5a..f3caff9 100644 --- a/src/PlaIO/Internal/ElementReader.SlabOpenings.cs +++ b/src/PlaIO/Internal/ElementReader.SlabOpenings.cs @@ -81,8 +81,9 @@ private static ReadOnlySpan ReadOpeningSlab(ModelGeometry geometry, Guid i geometry.Read(id, SlabClass) is { } record ? record.AsSpan(FindClassFrame(record, SlabClass)) : default; private static bool SlabOpeningMissesStrip(ModelGeometry geometry, Guid slab, Guid role, Guid relation, - (double X0, double Y0, double X1, double Y1) strip, double home, Elevations band) + (double X0, double Y0, double X1, double Y1) strip, double home, Elevations band, out bool verifiedCut) { + verifiedCut = false; var (opening, target) = role == CutElementRelation ? ReadOpeningCut(geometry, relation) : (relation, slab); if (target != slab || geometry.Read(opening, OpeningClass) is not { } record) return false; var hostIds = ReadOpeningRelation(record, OpeningHostRelation, owner: true); @@ -105,6 +106,7 @@ private static bool SlabOpeningMissesStrip(ModelGeometry geometry, Guid slab, Gu var settings = AfterCountedString(record.AsSpan(FindClassFrame(record, OpeningClass)), ClassElementIdOffset("Opening")); if (ReadSlabOpeningLimits(settings, source, story - home) is not { } limits) return false; + verifiedCut = true; if (limits.Top <= band.Bottom + JunctionTolerance || limits.Bottom >= band.Top - JunctionTolerance) return true; if (ReadSlabOpeningOrigin(source) is not { } origin || ReadOpeningProfile(settings) is not { } profile || ReadSlabOpeningPlan(settings, profile) is not { } plan) diff --git a/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs b/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs index 8d577c1..6838889 100644 --- a/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs +++ b/src/PlaIO/Internal/ElementReader.WallSlabOperations.cs @@ -128,6 +128,8 @@ private static bool SlabJunctionIsInactive(ModelGeometry geometry, Guid owner, i completeCaps = []; if (geometry.StoryElevation(location.HomeStoryIndex) is not { } home) return null; var bands = new List(); + var partialCaps = new Dictionary<(bool IsBottom, Elevations Skin), List>(); + double floor = bounds.Bottom + home, ceiling = bounds.Top + home; foreach (var (joint, _, priority) in contacts) { if (ReadWallSlabContact(geometry, wall, joint, out Guid slab) is not { } body) return null; @@ -146,6 +148,7 @@ private static bool SlabJunctionIsInactive(ModelGeometry geometry, Guid owner, i ? [new SlabSkin(planes.Top - planes.Bottom, maximum)] : geometry.Attributes.Composite.GetValueOrDefault(BinaryPrimitives.ReadUInt16LittleEndian(settings[87..])); if (skins is null) return null; + int firstBand = bands.Count; double high = planes.Top, cuttingBottom = double.PositiveInfinity, cuttingTop = double.NegativeInfinity; foreach (var skin in skins) { @@ -156,12 +159,7 @@ private static bool SlabJunctionIsInactive(ModelGeometry geometry, Guid owner, i if (skin.Priority >= priority && band.Top > band.Bottom) { bool mayLoseMaterial = false; - if (!HasSupportedSlabContacts(record, SlabWallRelation, joint, - (key, id) => key == SlabWallRelation && IsSameWallSlabPair(geometry, wall, slab, id) || - SlabContactKeepsCuttingBand(geometry, slab, key, id, skin.Priority, home, wallStrip.Footprint, band) || - allowSharedBeamCoverage && key == SlabBeamRelation && - SharedBeamPreservesSlabCoverage(geometry, wall, slab, id, location, home, priority, wallStrip.Footprint) || - MayLoseAfterWallContact(key, id), + if (!HasSupportedSlabContacts(record, SlabWallRelation, joint, CheckCuttingBand, acceptsOperatorTarget: (target, operation) => IsSlabOperatorTarget(geometry, target, slab, operation))) return null; bands.Add(new WallSlabOperation(new Elevations(low, high), rings, Priority: skin.Priority, @@ -169,32 +167,61 @@ private static bool SlabJunctionIsInactive(ModelGeometry geometry, Guid owner, i cuttingBottom = Math.Min(cuttingBottom, low); cuttingTop = Math.Max(cuttingTop, high); - bool MayLoseAfterWallContact(Guid role, Guid id) + bool CheckCuttingBand(Guid role, Guid id) { - if (!HasSlabWallPeerWithPriority(geometry, slab, role, id)) return false; - mayLoseMaterial = true; - return true; + if (role == CutElementRelation || role == OpeningHostRelation) + { + if (SlabOpeningMissesStrip(geometry, slab, role, id, wallStrip.Footprint, home, band, out bool verifiedCut)) + return true; + // A verified opening can only reduce the slab's cutting band. + mayLoseMaterial |= verifiedCut; + return verifiedCut; + } + if (role == SlabWallRelation && IsSameWallSlabPair(geometry, wall, slab, id) || + SlabContactKeepsCuttingBand(geometry, slab, role, id, skin.Priority, home, wallStrip.Footprint, band) || + allowSharedBeamCoverage && role == SlabBeamRelation && + SharedBeamPreservesSlabCoverage(geometry, wall, slab, id, location, home, priority, wallStrip.Footprint)) + return true; + bool verifiedWall = HasSlabWallPeerWithPriority(geometry, slab, role, id); + mayLoseMaterial |= verifiedWall; + return verifiedWall; } } high = low; } if (Math.Abs(high - planes.Bottom) > JunctionTolerance) return null; - double floor = bounds.Bottom + home, ceiling = bounds.Top + home; bool lowerGap = planes.Bottom <= floor + JunctionTolerance && cuttingBottom > floor + JunctionTolerance; bool upperGap = planes.Top >= ceiling - JunctionTolerance && cuttingTop < ceiling - JunctionTolerance; - if (basic && composite && settings[8] == 0 && double.IsFinite(cuttingBottom) && (lowerGap || upperGap) && - WallPlanHasGap(wallStrip.Footprint, [rings]) is false) + if (!basic || !composite || settings[8] != 0 || !double.IsFinite(cuttingBottom) || !(lowerGap || upperGap)) + continue; + bool? hasGap = WallPlanHasGap(wallStrip.Footprint, [rings]); + if (hasGap is true && lowerGap != upperGap && !allowSharedBeamCoverage && + bands.Count == firstBand + 1 && !bands[firstBand].MayLoseMaterial) { - // A complete slab cut can remove the wall cap beyond its cutting skins. - if (ClipBySlab(geometry, location, record, settings, wallStrip.Footprint, bounds, bounds.Bottom, bounds.Top, - out var beams, priority, (wall, slab, joint), allowSharedBeamCoverage: allowSharedBeamCoverage) is not { } clip || - beams is not null) - return null; - if (lowerGap && clip.Bottom > bounds.Bottom && Math.Abs(clip.Bottom + home - cuttingTop) <= JunctionTolerance) - completeCaps.Add((new WallSlabOperation(new Elevations(floor, cuttingTop), rings, Priority: priority), true)); - if (upperGap && clip.Top < bounds.Top && Math.Abs(clip.Top + home - cuttingBottom) <= JunctionTolerance) - completeCaps.Add((new WallSlabOperation(new Elevations(cuttingBottom, ceiling), rings, Priority: priority), false)); + var skin = bands[firstBand]; + var key = (lowerGap, skin.Planes); + if (!partialCaps.TryGetValue(key, out var caps)) partialCaps.Add(key, caps = []); + caps.Add(skin); } + if (hasGap is not false) continue; + + // A complete slab cut can remove the wall cap beyond its cutting skins. + if (ClipBySlab(geometry, location, record, settings, wallStrip.Footprint, bounds, bounds.Bottom, bounds.Top, + out var beams, priority, (wall, slab, joint), allowSharedBeamCoverage: allowSharedBeamCoverage) is not { } clip || + beams is not null) + return null; + if (lowerGap && clip.Bottom > bounds.Bottom && Math.Abs(clip.Bottom + home - cuttingTop) <= JunctionTolerance) + completeCaps.Add((new WallSlabOperation(new Elevations(floor, cuttingTop), rings, Priority: priority), true)); + if (upperGap && clip.Top < bounds.Top && Math.Abs(clip.Top + home - cuttingBottom) <= JunctionTolerance) + completeCaps.Add((new WallSlabOperation(new Elevations(cuttingBottom, ceiling), rings, Priority: priority), false)); + } + foreach (var ((isBottom, skin), caps) in partialCaps) + { + // Coplanar cutting skins can sever the cap together if their union covers the joined footprint. + if (caps.Count < 2 || WallPlanHasGap(wallStrip.Footprint, caps.Select(s => s.Rings).ToArray()) is not false) + continue; + var end = isBottom ? new Elevations(floor, skin.Top) : new Elevations(skin.Bottom, ceiling); + bands.Add(new WallSlabOperation(end, RectangleRing(wallStrip.Footprint), Priority: caps.Min(s => s.Priority))); } return bands; } diff --git a/tests/PlaIO.Tests/ElementReaderTests.JoinedSlabCaps.cs b/tests/PlaIO.Tests/ElementReaderTests.JoinedSlabCaps.cs new file mode 100644 index 0000000..4a03f15 --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.JoinedSlabCaps.cs @@ -0,0 +1,69 @@ +using System.Buffers.Binary; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + [Theory] + [InlineData(false, 0, 0, true, 0.25, 2.5)] + [InlineData(true, 0, 0, true, 1.0, 3.25)] + [InlineData(false, 0.02, 0, true, 0.25, 3.25)] + [InlineData(false, 2e-7, 0, true, 0.25, 3.25)] + [InlineData(false, 0, 0.125, true, 0.25, 3.25)] + [InlineData(false, 0, 0, false, null, null)] + public void CoplanarCompositeSlabsCanShareACompleteWallEndCut(bool lower, double gap, double heightDifference, + bool reciprocal, double? bottom, double? top) + { + Guid story = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + Guid material = new("2b0c5e9b-605e-4b8f-aaae-cc166f03bee5"); + Guid layer = new("6fda3fe2-8e75-4e3f-b8c0-d0c4777e5d4d"); + Guid composite = new("c7ecb629-3cf3-4c9c-a222-11082672e04b"); + Guid junction = new("324477ff-7a26-4d53-a38e-8f39f678c2b8"); + Guid wallRole = new("88f6f041-4ce9-43cd-b0c1-056bf842bf5a"); + Guid slabRole = new("ae1816f7-dc76-4857-b0e9-fbb3378a3800"); + Guid wall = Guid.NewGuid(), left = Guid.NewGuid(), right = Guid.NewGuid(); + Guid leftLink = Guid.NewGuid(), rightLink = Guid.NewGuid(); + const int slotSize = 1024; + byte[] pool = new byte[5 * slotSize]; + var entries = new List(); + var target = WallWithPlanes(1, -3.75); + WriteWallStrip(target.AsSpan(209), alongX: true, 0.125); + Add(1, wall, WithGeometryRelations(target, GeometryRelationList(1, wallRole, leftLink, rightLink))); + double elevation = lower ? 1.25 : 3.25; + AddSlab(left, leftLink, -1, 0, elevation, reciprocal: true); + AddSlab(right, rightLink, gap, 1, elevation + heightDifference, reciprocal); + + using var doc = Open(ClassTable((1, WallClass), (2, SlabClass), (3, junction), (4, story), + (7, material), (8, layer), (10, composite)), + OwnedDirectory(false, Guid.Empty, (ulong)pool.Length / 16, entries.ToArray()), + Synthetic.Block(PlaBlockMode.Raw, StoryTable(story), ver: 1, kind: 4), + JunctionAttribute(material, 7, 1, 1000), JunctionAttribute(material, 7, 2, 1200), + JunctionAttribute(material, 7, 3, 800), JunctionAttribute(layer, 8, 1, 1), + CompositeForWallTest(composite, splitCuts: false), Pool(pool)); + var result = Assert.Single(doc.ReadElements(), item => item.Guid == wall); + Assert.Equal(bottom, result.BottomElevationToHomeStory); + Assert.Equal(bottom - 4, result.BottomElevationToProjectZero); + Assert.Equal(top, result.TopElevationToHomeStory); + Assert.Equal(top - 4, result.TopElevationToProjectZero); + + void AddSlab(Guid id, Guid link, double start, double end, double slabTop, bool reciprocal) + { + var body = OpeningSlab(0, slabTop - 4, 1); + var settings = body.AsSpan(191); + BinaryPrimitives.WriteUInt16LittleEndian(settings[83..], 2); + BinaryPrimitives.WriteUInt16LittleEndian(settings[87..], 1); + WriteRectangularPlan(settings[270..], start, -1, end, 1, slab: true); + Add(2, id, WithGeometryRelations(body, GeometryRelation(0x11, slabRole, reciprocal ? link : Guid.NewGuid()))); + Add(3, link, WithGeometryRelations(junction.ToByteArray(), HostRelation(wallRole, wall), HostRelation(slabRole, id))); + } + + void Add(ushort kind, Guid id, byte[] body) + { + int slot = entries.Count; + Synthetic.Block(PlaBlockMode.Raw, body, ver: 1, guid: id, extra: 1, kind: kind).CopyTo(pool, slot * slotSize); + entries.Add(new(kind, (ulong)slot * (slotSize / 16), slotSize / 16, id)); + } + } +} diff --git a/tests/PlaIO.Tests/ElementReaderTests.cs b/tests/PlaIO.Tests/ElementReaderTests.cs index 63529cd..00834f6 100644 --- a/tests/PlaIO.Tests/ElementReaderTests.cs +++ b/tests/PlaIO.Tests/ElementReaderTests.cs @@ -3686,6 +3686,8 @@ void Add(int slot, ushort kind, Guid id, byte[] body) [InlineData(false, false, 2.75, true, 5)] [InlineData(false, false, null, true, 6)] [InlineData(false, false, null, true, 7)] + [InlineData(true, false, null, true, 2)] + [InlineData(true, false, null, true, 3)] [InlineData(false, false, 2.75, true, 0, 1)] [InlineData(false, false, 2.75, true, 0, 2)] [InlineData(true, false, 2.75, true, 0, 0, 1)] @@ -3788,7 +3790,7 @@ public void CompositeSlabsCutThroughAllWallSkinsAtEachEnd(bool cutBothEnds, bool labelStorage == 1 ? Synthetic.Block(PlaBlockMode.ZeroMask, Synthetic.ZeroMask(labelBody), ver: 1, guid: label, unpacked: (uint)labelBody.Length, kind: 10) : []); var result = Assert.Single(doc.ReadElements(), e => e.Guid == wall); - double? bottom = cutBothEnds ? top.HasValue ? 0.75 : null : beveled ? null : 0.25; + double? bottom = cutBothEnds ? top.HasValue || openingCase == 2 ? 0.75 : null : beveled ? null : 0.25; Assert.Equal(bottom, result.BottomElevationToHomeStory); Assert.Equal(top, result.TopElevationToHomeStory); Assert.Equal(bottom - 4, result.BottomElevationToProjectZero); From 33d4743535f87065646dbd099ad1673f05e0f227 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:30 +0300 Subject: [PATCH 3/3] Read Archicad grids and include them in scenes --- Directory.Packages.props | 5 +- README.md | 6 +- docs/cli.md | 10 + docs/dependencies.md | 4 +- docs/public-api.md | 3 + docs/reader-parity.md | 9 +- docs/scene.md | 12 +- src/PlaIO.Cli/Cli.cs | 8 +- src/PlaIO.Scene/PlaSceneReader.cs | 67 ++++- src/PlaIO.Scene/PlaSceneResult.cs | 2 +- .../Internal/ElementReader.DoorParameters.cs | 95 +++++-- src/PlaIO/Internal/ElementReader.Doors.cs | 6 +- src/PlaIO/Internal/ElementReader.Grids.cs | 265 ++++++++++++++++++ src/PlaIO/Internal/ElementReader.Junctions.cs | 2 +- src/PlaIO/Internal/ElementReader.cs | 11 +- src/PlaIO/Model/PlaGridAxis.cs | 65 +++++ src/PlaIO/PlaDocument.cs | 6 + tests/PlaIO.Tests/ElementReaderTests.Grids.cs | 229 +++++++++++++++ tests/PlaIO.Tests/PlaSceneReaderTests.cs | 69 +++++ 19 files changed, 810 insertions(+), 64 deletions(-) create mode 100644 src/PlaIO/Internal/ElementReader.Grids.cs create mode 100644 src/PlaIO/Model/PlaGridAxis.cs create mode 100644 tests/PlaIO.Tests/ElementReaderTests.Grids.cs 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 28023fb..db367f1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ PlaIO is a pure managed .NET library and command line tool that reads the contai `.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 with no dependency on scene types. -The `PlaIO.Scene` adapter maps decoded elements, storeys, properties and supported slab meshes into an `IOScene` +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 @@ -20,6 +20,7 @@ document for [IOViewer](https://github.com/IOExtend/IOViewer) and coordination t - 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. @@ -53,6 +54,7 @@ plaio blocks # one tab-separated line per indexe 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) @@ -76,7 +78,7 @@ 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`, `directory`, `elements`, `stories`, `layers`, `materials`, `profiles`, `classifications`, `properties` and `layouts` work on `.pla` +`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 85a2112..28b1111 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -12,6 +12,7 @@ standard error and tells success from failure by its exit code. It uses only the | `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. | @@ -95,6 +96,15 @@ See the [supported types and parameters](public-api.md#model-elements). 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 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/public-api.md b/docs/public-api.md index 17113a0..72c4b5b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -95,6 +95,9 @@ and script evaluation require separate readers. | `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`. | diff --git a/docs/reader-parity.md b/docs/reader-parity.md index 48e7de3..9802b12 100644 --- a/docs/reader-parity.md +++ b/docs/reader-parity.md @@ -8,7 +8,7 @@ counterpart only where they represent comparable model data. See the [RvtIO publ | --- | --- | --- | | 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` | `ReadStories()` provides the full saved catalog for supported story tables. 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. Grid paths and general element placement are pending. | +| 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. | @@ -16,7 +16,7 @@ counterpart only where they represent comparable model data. See the [RvtIO publ | 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 and layers. The scene adapter maps recognized elements, saved levels, 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. | +| 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 @@ -24,6 +24,11 @@ separately for each type and field. Record the tolerances with the comparison. F 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 diff --git a/docs/scene.md b/docs/scene.md index 82375fc..8deb03c 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -9,6 +9,10 @@ - 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. @@ -52,12 +56,14 @@ The adapter uses `archicad:instance` for intrinsic properties. A saved user-defi | Severity | Code | Meaning | |---|---|---| -| Info | `container-only` | The container has no decoded model 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 raises an error. +A malformed or ambiguous indexed object class table, invalid grid store or invalid recognized story table raises an error. ## Publication 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.1, 0.2.0-0.0)` range. +The package configuration specifies an exact PlaIO dependency and an `IOScene [0.1.2, 0.2.0-0.0)` range. diff --git a/src/PlaIO.Cli/Cli.cs b/src/PlaIO.Cli/Cli.cs index 2d09d1e..7f4eb8d 100644 --- a/src/PlaIO.Cli/Cli.cs +++ b/src/PlaIO.Cli/Cli.cs @@ -20,6 +20,7 @@ plaio blocks plaio directory [--out ] plaio elements plaio stories + plaio grids plaio layers plaio materials plaio profiles @@ -38,6 +39,7 @@ offset tag id kind ver flags class mode packed unpacked extra payloadOffset guid 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. @@ -64,7 +66,7 @@ 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" or "elements" or "stories" or "layers" or "materials" or "profiles" + 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: @@ -116,6 +118,10 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr) 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)); diff --git a/src/PlaIO.Scene/PlaSceneReader.cs b/src/PlaIO.Scene/PlaSceneReader.cs index 602e936..15b0892 100644 --- a/src/PlaIO.Scene/PlaSceneReader.cs +++ b/src/PlaIO.Scene/PlaSceneReader.cs @@ -1,11 +1,12 @@ using System.Reflection; using IOScene; +using PlaIO.Model; namespace PlaIO.Scene; /// /// Turns an Archicad container (a .pla or .pln file) into a scene () with its decoded -/// elements, levels, properties and supported meshes. +/// elements, levels, grids, properties and supported meshes. /// /// /// The persisted identity is the model key together with the saved Archicad element GUID in D format. @@ -38,6 +39,7 @@ private static PlaSceneResult Map(string path, string key) Producer = Producer, }); bool hasClassTable = document.HasObjectClassTable; + var diagnostics = new List(); var levels = new Dictionary(); foreach (var story in hasClassTable ? document.ReadStories() : []) { @@ -46,13 +48,14 @@ private static PlaSceneResult Map(string path, string key) 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) - return new PlaSceneResult - { - Document = scene, - Diagnostics = [new(SceneSeverity.Info, "container-only", "The model contains no decoded elements.")], - }; + { + 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); @@ -102,13 +105,53 @@ private static PlaSceneResult Map(string path, string key) } int withoutMesh = elements.Count - scene.Instances.Select(i => i.ElementId).Distinct().Count(); - return new PlaSceneResult + 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) { - Document = scene, - Diagnostics = withoutMesh == 0 ? [] : - [new(SceneSeverity.Info, "geometry-incomplete", FormattableString.Invariant( - $"Triangle meshes are unavailable for {withoutMesh} of {elements.Count} decoded elements."))], - }; + 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 449feb7..b5f5a10 100644 --- a/src/PlaIO.Scene/PlaSceneResult.cs +++ b/src/PlaIO.Scene/PlaSceneResult.cs @@ -8,6 +8,6 @@ public sealed class PlaSceneResult /// The converted model and its available scene data. public required SceneDocument Document { get; init; } - /// Conversion diagnostics for scenes without decoded elements or with incomplete mesh coverage. + /// Conversion diagnostics for empty scenes or incomplete mesh and grid coverage. public IReadOnlyList Diagnostics { get; init; } = []; } diff --git a/src/PlaIO/Internal/ElementReader.DoorParameters.cs b/src/PlaIO/Internal/ElementReader.DoorParameters.cs index eabbeb4..1209a89 100644 --- a/src/PlaIO/Internal/ElementReader.DoorParameters.cs +++ b/src/PlaIO/Internal/ElementReader.DoorParameters.cs @@ -9,7 +9,10 @@ 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), @@ -88,35 +91,17 @@ private sealed record DoorParameterTable(PlaDoorWallHoleDimensions Dimensions, H private static DoorParameterTable? ReadDoorParameterTable(ReadOnlySpan data) { - const int bodyOffset = 39; - const int tableOffset = 57; - const int trailerSize = 24; - const int rowStart = 65; - const int rowSize = 72; - if (data.Length < rowStart || new Guid(data[..16]) != LibraryParameterClass || - !data[bodyOffset..].StartsWith(LibraryParameterFrame)) return null; - uint bodySize = BinaryPrimitives.ReadUInt32LittleEndian(data[35..]); - uint tableSize = BinaryPrimitives.ReadUInt32LittleEndian(data[53..]); - uint count = BinaryPrimitives.ReadUInt32LittleEndian(data[tableOffset..]); - if (bodySize < rowStart - bodyOffset || bodySize > data.Length - bodyOffset - 7 || - bodySize != (long)tableSize + tableOffset + trailerSize - bodyOffset || - tableSize < rowStart - tableOffset || count > (tableSize - (rowStart - tableOffset)) / rowSize) - return null; - int end = bodyOffset + (int)bodySize; - if (BinaryPrimitives.ReadUInt32LittleEndian(data[end..]) != data.Length - end - 4 || - BinaryPrimitives.ReadUInt16LittleEndian(data[(end + 4)..]) != 1) return null; + 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 < count; i++) + for (int i = 0; i < rows.Length; i += LibraryParameterRowSize) { - var row = data.Slice(rowStart + i * rowSize, rowSize); - var name = row.Slice(32, 32); - int terminator = name.IndexOf((byte)0); - if (terminator < 0) continue; - name = name[..terminator]; + 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)) { @@ -158,7 +143,54 @@ private sealed record DoorParameterTable(PlaDoorWallHoleDimensions Dimensions, H } if (width is not double w || height is not double h) return null; - var relation = data[(end + 6)..]; + 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]) @@ -170,12 +202,13 @@ private sealed record DoorParameterTable(PlaDoorWallHoleDimensions Dimensions, H Guid id = new(ids.Slice(i, 16)); if (id == Guid.Empty || !descriptors.Add(id)) return null; } - return descriptors.Count == 0 ? null : new DoorParameterTable(new(w, h), descriptors, - noOversize && oversizes == 15, plainSettings == PlainPassageMask, pocketSettings == PocketPassageMask); - - static bool IsScalarLength(ReadOnlySpan row) => - BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) == 2 && - BinaryPrimitives.ReadUInt64LittleEndian(row[12..]) == 0 && - BinaryPrimitives.ReadUInt32LittleEndian(row[68..]) == sizeof(double); + 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 index 6927f77..59f1e92 100644 --- a/src/PlaIO/Internal/ElementReader.Doors.cs +++ b/src/PlaIO/Internal/ElementReader.Doors.cs @@ -5,7 +5,7 @@ namespace PlaIO.Internal; internal static partial class ElementReader { - private static readonly Guid DoorLibraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f"); + 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"); @@ -60,8 +60,8 @@ private static Guid ReadDoorHost(ReadOnlySpan door, Guid id, ModelGeometry { parameterLink = default; Guid part = ReadSingleRelation(door, DoorLibraryRelation, 0x11, requireSection: true); - if (geometry.Read(part, DoorLibraryClass) is not { Length: >= 89 } descriptor || - !descriptor.AsSpan(39).StartsWith(new byte[] { 1, 0, 131, 0, 3, 0, 0, 0, 1, 0, 2, 0 }) || + 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)); diff --git a/src/PlaIO/Internal/ElementReader.Grids.cs b/src/PlaIO/Internal/ElementReader.Grids.cs new file mode 100644 index 0000000..1a9e26c --- /dev/null +++ b/src/PlaIO/Internal/ElementReader.Grids.cs @@ -0,0 +1,265 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; + +namespace PlaIO.Internal; + +internal static partial class ElementReader +{ + private static readonly Guid GridLibraryFamily = new("b286e7ff-8856-42d5-b293-6084b1784db2"); + private static readonly Guid ObjectLibraryRelation = new("189f453e-ea2e-4e38-afe9-660d1d25afc6"); + + private readonly record struct GridPlacement(Guid Descriptor, PlaPlanPoint Anchor, double Rotation, bool Mirrored, + int? Story, double? ElevationToHomeStory); + private readonly record struct GridLibraryLink(Guid Owner, Guid Table); + private readonly record struct GridDefinition(string Label, double Extent, double Sweep, double? SegmentLength, bool IsHidden); + private sealed record GridParameters(GridDefinition Definition, HashSet Owners); + + internal static IReadOnlyList ReadGridAxes(PlaDocument document, IReadOnlyList classes) + { + var stores = ReadGridStores(document, classes); + if (stores is null) throw new InvalidDataException("A grid store has an unsupported frame or relationship section."); + var members = stores.Where(store => store.Key != Guid.Empty).SelectMany(store => store.Value).ToHashSet(); + if (members.Count == 0) return []; + + var classIds = classes.Where(c => c.Guid == ObjectClass || c.Guid == PlacedLibraryClass || c.Guid == LibraryParameterClass) + .ToDictionary(c => c.Number, c => c.Guid); + var directories = new Dictionary>(); + foreach (var block in document.Blocks) + { + if (!IsRawTable(block, DirectoryKind)) continue; + var data = document.ReadPayload(block).AsSpan(); + int header = DirectoryHeaderSize(data, DirectoryLayout); + bool parameterDirectory = header == 0; + if (parameterDirectory) header = DirectoryHeaderSize(data, LibraryParameterDirectory); + if (header == 0) continue; + + ulong units = BinaryPrimitives.ReadUInt64LittleEndian(data[(header - 40)..]); + for (int offset = header; offset <= data.Length - DirectoryFinder.RecordSize; offset += DirectoryFinder.RecordSize) + { + var record = DirectoryFinder.ReadRecord(data[offset..]); + if (record.ObjectId == Guid.Empty || record.Count == 0 || record.Position > units || record.Count > units - record.Position || + !classIds.TryGetValue(record.ClassNumber, out Guid kind) || + (parameterDirectory && kind != LibraryParameterClass) || (kind == ObjectClass && !members.Contains(record.ObjectId))) + continue; + if (!directories.TryGetValue(units, out var entries)) directories.Add(units, entries = []); + entries.Add(record); + } + } + + var placements = new Dictionary(); + var descriptors = new Dictionary(); + var parameters = new Dictionary(); + foreach (var pool in document.FindCompressedPools()) + { + if (pool.TotalDecompressed % ExtentUnit != 0 || + !directories.TryGetValue((ulong)(pool.TotalDecompressed / ExtentUnit), out var entries)) continue; + var data = pool.Decode(); + foreach (var record in entries) + { + if (ReadIndexedPayload(data, record) is not { } payload) continue; + Guid id = record.ObjectId, kind = classIds[record.ClassNumber]; + if (kind == ObjectClass) + AddGridRecord(placements, id, ReadGridPlacement(payload, id, stores)); + else if (kind == PlacedLibraryClass) + AddGridRecord(descriptors, id, ReadGridLibraryLink(payload, members)); + else + { + var table = ReadGridParameters(payload); + if (!parameters.TryAdd(id, table) && (table is null || parameters[id] is not { } previous || + previous.Definition != table.Definition || !previous.Owners.SetEquals(table.Owners))) + parameters[id] = null; + } + } + } + + var axes = new List(); + var stories = new Lazy>(() => ReadStories(document, classes)); + foreach (var (id, candidate) in placements.OrderBy(pair => pair.Key)) + { + if (candidate is not { } placement || + descriptors.GetValueOrDefault(placement.Descriptor) is not { } link || link.Owner != id || + parameters.GetValueOrDefault(link.Table) is not { } table || !table.Owners.Contains(placement.Descriptor)) + continue; + + double? storyElevation = placement.Story is { } story && placement.ElevationToHomeStory.HasValue + ? stories.Value.GetValueOrDefault(story).Elevation : null; + if (ReadGridAxis(id, placement, table.Definition, storyElevation) is { } axis) axes.Add(axis); + } + return axes.AsReadOnly(); + } + + private static PlaGridAxis? ReadGridAxis(Guid id, GridPlacement placement, GridDefinition definition, double? storyElevation) + { + var (label, extent, sweep, segmentLength, isHidden) = definition; + var start = placement.Anchor; + PlaPlanPoint end; + PlaGridArc? arc = null; + if (sweep == 0) + { + end = PointFromAnchor(placement.Rotation, placement.Mirrored ? -extent : extent); + } + else + { + // The circular anchor is the center. Reflection reverses the arc, so use its other end first for CCW order. + double startAngle = placement.Mirrored ? placement.Rotation + Math.PI - sweep : placement.Rotation; + start = PointFromAnchor(startAngle, extent); + end = sweep == Math.Tau ? start : PointFromAnchor(startAngle + sweep, extent); + if (start == placement.Anchor || end == placement.Anchor) return null; + arc = new PlaGridArc(placement.Anchor, extent, sweep); + } + + if (!double.IsFinite(start.X) || !double.IsFinite(start.Y) || !double.IsFinite(end.X) || !double.IsFinite(end.Y) || + (end == start && sweep != Math.Tau)) return null; + return new(id, label, start, end, placement.Story) + { + ElevationToHomeStory = placement.ElevationToHomeStory, + ElevationToProjectZero = ToProjectZero(placement.ElevationToHomeStory, storyElevation), + Arc = arc, + FloorPlanSegmentLength = segmentLength, + IsFloorPlanLineHidden = isHidden, + }; + + PlaPlanPoint PointFromAnchor(double angle, double distance) + { + var (sin, cos) = Math.SinCos(angle); + return new(placement.Anchor.X + distance * cos, placement.Anchor.Y + distance * sin); + } + } + + private static void AddGridRecord(Dictionary records, Guid id, T? value) where T : struct + { + if (!records.TryAdd(id, value) && !EqualityComparer.Default.Equals(records[id], value)) records[id] = null; + } + + private static GridPlacement? ReadGridPlacement(ReadOnlySpan data, Guid id, Dictionary> stores) + { + if (!TryReadDeclaredRelations(data, out int end, out var relations) || new Guid(data[..16]) != ObjectClass) return null; + Guid store = ReadGridRelation(relations, GridElementList, 0x12); + if (store == Guid.Empty || !stores.TryGetValue(store, out var members) || !members.Contains(id) || + ReadGridRelation(relations, ElementPartitionRelation, 0x12) == Guid.Empty) return null; + + Guid descriptor = ReadGridRelation(relations, ObjectLibraryRelation, 0x11); + int frame = FindClassFrame(data[..end], ObjectClass); + if (descriptor == Guid.Empty || frame < 0 || end - frame < 254) return null; + + var body = data[frame..end]; + double x = ReadDouble(body, 206), y = ReadDouble(body, 214), rotation = ReadDouble(body, 222); + double elevation = ReadDouble(body, 230), scaleX = ReadDouble(body, 238), scaleY = ReadDouble(body, 246); + ushort placementFlags = BinaryPrimitives.ReadUInt16LittleEndian(body[204..]); + // The zero-flags placement variant stores no explicit scale. + bool unitScale = (scaleX, scaleY) is (1, 1) || (placementFlags, scaleX, scaleY) is (0, 0, 0); + if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(rotation) || + body[201] > 1 || !unitScale) return null; + return new(descriptor, new(x, y), rotation, body[201] == 1, ReadElementLocation(body, "Object", 0).HomeStoryIndex, + double.IsFinite(elevation) ? elevation : null); + } + + private static GridLibraryLink? ReadGridLibraryLink(ReadOnlySpan data, HashSet members) + { + if (data.Length < 89 || new Guid(data[..16]) != PlacedLibraryClass || !data[39..].StartsWith(PlacedLibraryFrame) || + new Guid(data.Slice(51, 16)) != GridLibraryFamily || new Guid(data.Slice(67, 16)) == Guid.Empty || + !TryReadDeclaredRelations(data, out int end, out var relations) || end < 89) return null; + Guid owner = ReadGridRelation(relations, ObjectLibraryRelation, 0x12); + if (!members.Contains(owner)) return null; + Guid table = ReadGridRelation(relations, LibraryParameterRelation, 0x11); + return table != Guid.Empty ? new(owner, table) : null; + } + + private static Guid ReadGridRelation(ReadOnlySpan relations, Guid role, byte expectedTag) + { + Guid result = Guid.Empty; + while (relations is not [0]) + { + if (!TryReadGeometryRelation(ref relations, out byte tag, out Guid key, out Guid target)) return Guid.Empty; + if (key != role) continue; + if (tag != expectedTag || target == Guid.Empty || result != Guid.Empty) return Guid.Empty; + result = target; + } + return result; + } + + private static GridParameters? ReadGridParameters(ReadOnlySpan data) + { + if (!TryReadLibraryParameterFrame(data, out var rows, out var table, out var relations)) return null; + double? length = null, radius = null, angle = null, segmentLength = null; + int? geometryType = null, lineVisibility = null; + string? label = null; + for (int i = 0; i < rows.Length; i += LibraryParameterRowSize) + { + var row = rows.Slice(i, LibraryParameterRowSize); + var name = ReadLibraryParameterName(row); + if (name.SequenceEqual("AC_Type_i"u8)) + { + if (geometryType.HasValue || !IsScalarNumber(row, 0)) return null; + geometryType = BinaryPrimitives.ReadInt32LittleEndian(row[24..]); + } + else if (name.SequenceEqual("AC_LineVisibility_i"u8)) + { + if (lineVisibility.HasValue || !IsScalarNumber(row, 0)) return null; + lineVisibility = BinaryPrimitives.ReadInt32LittleEndian(row[24..]); + } + else if (name.SequenceEqual("AC_Length"u8)) + { + if (!ReadGridNumber(row, 2, ref length)) return null; + } + else if (name.SequenceEqual("AC_Radius"u8)) + { + if (!ReadGridNumber(row, 2, ref radius)) return null; + } + else if (name.SequenceEqual("AC_Angle"u8)) + { + if (!ReadGridNumber(row, 3, ref angle)) return null; + } + else if (name.SequenceEqual("AC_VisLength"u8)) + { + if (!ReadGridNumber(row, 2, ref segmentLength)) return null; + } + else if (name.SequenceEqual("AC_MarkerText_1"u8)) + { + if (label is not null || ReadGridLabel(row, table, 8 + rows.Length) is not { } text) return null; + label = text; + } + } + if (label is null || lineVisibility is not (1 or 2 or 3) || + (lineVisibility == 2 && (segmentLength is not >= 0 || !double.IsFinite(segmentLength.Value))) || + ReadLibraryParameterOwners(relations) is not { } owners) return null; + + double? visibleLength = lineVisibility == 2 ? segmentLength : null; + bool isHidden = lineVisibility == 3; + if (geometryType == 1 && length is > 0 and { } extent && double.IsFinite(extent)) + return new(new(label, extent, 0, visibleLength, isHidden), owners); + if (geometryType == 2 && radius is > 0 and { } r && double.IsFinite(r) && angle is > 0 and <= 360 and { } degrees) + { + double sweep = degrees == 360 ? Math.Tau : degrees * (Math.PI / 180); + if (sweep > 0) return new(new(label, r, sweep, visibleLength, isHidden), owners); + } + return null; + } + + private static bool ReadGridNumber(ReadOnlySpan row, ushort type, ref double? value) + { + if (value.HasValue) return false; + value = IsScalarNumber(row, type) ? ReadDouble(row, 24) : double.NaN; + return true; + } + + private static string? ReadGridLabel(ReadOnlySpan row, ReadOnlySpan table, int valuesStart) + { + uint offset = BinaryPrimitives.ReadUInt32LittleEndian(row[64..]); + uint length = BinaryPrimitives.ReadUInt32LittleEndian(row[68..]); + if (BinaryPrimitives.ReadUInt16LittleEndian(row[8..]) != 12 || BinaryPrimitives.ReadUInt64LittleEndian(row[12..]) != 0 || + (offset & 1) != 0 || (length & 1) != 0 || length < 2 || offset < valuesStart || + offset > table.Length || length > table.Length - offset) return null; + + var value = table.Slice((int)offset, (int)length); + for (int index = 0; index < value.Length; index += 2) + { + if (BinaryPrimitives.ReadUInt16LittleEndian(value[index..]) != 0) continue; + if (value[index..].IndexOfAnyExcept((byte)0) >= 0) return null; + try { return Utf16.GetString(value[..index]); } + catch (DecoderFallbackException) { return null; } + } + return null; + } +} diff --git a/src/PlaIO/Internal/ElementReader.Junctions.cs b/src/PlaIO/Internal/ElementReader.Junctions.cs index 766c832..eeb3364 100644 --- a/src/PlaIO/Internal/ElementReader.Junctions.cs +++ b/src/PlaIO/Internal/ElementReader.Junctions.cs @@ -45,7 +45,7 @@ private static bool IsJunctionGeometryClass(Guid id) => id == ComplexSectionClass || id == ProfileShapeClass || id == SlabClass || id == WallClass || id == WallProfileClass || id == WallWallJunctionClass || id == WallSlabJunctionClass || id == WallBeamJunctionClass || id == WallPlanContourClass || id == WallJunctionPointClass || id == BeamBeamJunctionClass || id == BeamSlabJunctionClass || - id == SlabLevelDimensionClass || id == OpeningClass || id == OpeningCutClass || id == DoorClass || id == DoorLibraryClass || + id == SlabLevelDimensionClass || id == OpeningClass || id == OpeningCutClass || id == DoorClass || id == PlacedLibraryClass || id == ElementAssemblyClass || id == ElementAssemblyMemberClass || id == AttachedAnnotationClass || id == AngularDimensionClass || id == ZoneClass || id == ZoneBoundaryCalculationClass || id == PropertyOverrideClass; diff --git a/src/PlaIO/Internal/ElementReader.cs b/src/PlaIO/Internal/ElementReader.cs index ca79895..3837ece 100644 --- a/src/PlaIO/Internal/ElementReader.cs +++ b/src/PlaIO/Internal/ElementReader.cs @@ -508,18 +508,23 @@ private static void AddElement(Dictionary elements, Guid i throw new InvalidDataException($"Object {id:D} has conflicting classes in the directories."); } - private static HashSet? ReadGridElements(PlaDocument document, IReadOnlyList classes) + private static HashSet? ReadGridElements(PlaDocument document, IReadOnlyList classes) => + ReadGridStores(document, classes)?.Values.SelectMany(ids => ids).ToHashSet(); + + private static Dictionary>? ReadGridStores(PlaDocument document, IReadOnlyList classes) { var classNumbers = classes.Where(c => c.Guid == GridStoreClass).Select(c => c.Number).ToHashSet(); - var grids = new HashSet(); + var stores = new Dictionary>(); foreach (var block in document.Blocks) { if (block.Tag != "BL" || !classNumbers.Contains(block.Kind)) continue; + Guid store = block.Guid ?? Guid.Empty; + if (!stores.TryGetValue(store, out var grids)) stores.Add(store, grids = []); if (block.Version != 1 || block.Mode != PlaBlockMode.Raw || !ReadRelationshipElements(document.ReadPayload(block), GridStoreClass, GridElementList, grids)) return null; } - return grids; + return stores; } private static byte[]? ReadIndexedPayload(ReadOnlySpan pool, ObjectDirectoryRecord record) diff --git a/src/PlaIO/Model/PlaGridAxis.cs b/src/PlaIO/Model/PlaGridAxis.cs new file mode 100644 index 0000000..59b4533 --- /dev/null +++ b/src/PlaIO/Model/PlaGridAxis.cs @@ -0,0 +1,65 @@ +using System.Text.Json.Serialization; + +namespace PlaIO.Model; + +/// A saved straight or circular grid axis in project plan coordinates. +/// The GUID of the placed grid object. +/// The saved label of the start marker. +/// The start point in project XY coordinates, in metres. +/// The end point in project XY coordinates, in metres. +/// The signed home story index when available. +public sealed record PlaGridAxis(Guid Guid, string Label, PlaPlanPoint Start, PlaPlanPoint End, int? HomeStoryIndex) +{ + /// The saved elevation offset from the home story in metres, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? ElevationToHomeStory { get; internal init; } + + /// The elevation relative to project zero in metres, when the home story elevation is known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? ElevationToProjectZero { get; internal init; } + + /// The circular geometry, when the axis follows an arc. Start and end follow its counterclockwise order. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public PlaGridArc? Arc { get; internal init; } + + /// The configured floor plan segment length in metres when the line is shown in segments. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? FloorPlanSegmentLength { get; internal init; } + + /// Whether the saved floor plan display hides the axis line. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool IsFloorPlanLineHidden { get; internal init; } + + /// Samples the full reference axis as a polyline, with a maximum arc-to-chord error in metres. + /// The positive, finite maximum error in metres. + /// Points in order, or null if more than 65,536 points are needed or a point is not representable. + /// is nonfinite or not positive. + public IReadOnlyList? Tessellate(double maxError) + { + if (!double.IsFinite(maxError) || maxError <= 0) throw new ArgumentOutOfRangeException(nameof(maxError)); + if (Arc is not { } arc) return [Start, End]; + + double maxStep = 4 * Math.Asin(Math.Sqrt(Math.Min(0.5, maxError / arc.Radius / 2))); + double count = Math.Ceiling(arc.SweepRadians / Math.Min(Math.PI / 2, maxStep)); + if (!(count >= 1 && count < 65_536)) return null; + + double startAngle = Math.Atan2(Start.Y - arc.Center.Y, Start.X - arc.Center.X); + var points = new PlaPlanPoint[(int)count + 1]; + points[0] = Start; + for (int i = 1; i < points.Length - 1; i++) + { + var (sin, cos) = Math.SinCos(startAngle + arc.SweepRadians * i / count); + var point = new PlaPlanPoint(arc.Center.X + arc.Radius * cos, arc.Center.Y + arc.Radius * sin); + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y)) return null; + points[i] = point; + } + points[^1] = End; + return Array.AsReadOnly(points); + } +} + +/// The analytic geometry of a circular grid axis. +/// The center in project XY coordinates, in metres. +/// The radius in metres. +/// The positive counterclockwise sweep in radians. +public readonly record struct PlaGridArc(PlaPlanPoint Center, double Radius, double SweepRadians); diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 3e8f51e..82babaf 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -304,6 +304,12 @@ public PlaEmbeddedLibraryCatalog ReadEmbeddedLibraryCatalog() /// The object class table or a recognized story table is invalid. public IReadOnlyList ReadStories() => ElementReader.ReadStoryCatalog(this, ReadObjectClasses()); + /// Reads supported straight and circular grid axes in GUID order. + /// Returns the full reference geometry from verified model placements, including axes drawn in segments or hidden on the floor plan. + /// The class table, grid store or a recognized story table is invalid, + /// or a pool cannot be decoded. + public IReadOnlyList ReadGridAxes() => ElementReader.ReadGridAxes(this, ReadObjectClasses()); + /// Reads the identifiable saved project layers in ascending layer index order. /// The object class table is invalid or layer records conflict. public IReadOnlyList ReadLayers() => ElementReader.ReadLayerCatalog(this, ReadObjectClasses()); diff --git a/tests/PlaIO.Tests/ElementReaderTests.Grids.cs b/tests/PlaIO.Tests/ElementReaderTests.Grids.cs new file mode 100644 index 0000000..5f2f095 --- /dev/null +++ b/tests/PlaIO.Tests/ElementReaderTests.Grids.cs @@ -0,0 +1,229 @@ +using System.Buffers.Binary; +using System.Text; +using PlaIO.Model; +using Xunit; + +namespace PlaIO.Tests; + +public partial class ElementReaderTests +{ + private const string GridFixtureLabel = "Ось-12"; + + [Theory] + [InlineData("verified")] + [InlineData("shared parameter table")] + [InlineData("implicit unit scale")] + [InlineData("mirrored axis")] + [InlineData("unsupported scale")] + [InlineData("drawing copy")] + [InlineData("missing membership")] + [InlineData("wrong grid store")] + [InlineData("wrong library family")] + [InlineData("wrong library owner")] + [InlineData("wrong parameter owner")] + [InlineData("curved axis")] + [InlineData("hidden arc")] + [InlineData("mirrored arc")] + [InlineData("full circle")] + [InlineData("invalid arc angle")] + [InlineData("invalid arc radius")] + [InlineData("shortened line")] + [InlineData("nonfinite segment length")] + [InlineData("nonfinite length")] + [InlineData("truncated marker")] + public void ReadsGridAxesWithReciprocalPlacementAndParameterLinks(string variant) + { + var (file, id) = GridAxisFixture(variant); + using var doc = PlaDocument.Open(new MemoryStream(file)); + bool segmented = variant is "shortened line" or "nonfinite segment length"; + double angle = variant switch { "mirrored arc" => 90, "full circle" => 360, _ => 270 }; + + if (variant is "verified" or "shared parameter table" or "implicit unit scale" or "mirrored axis" or "shortened line") + { + var axis = Assert.Single(doc.ReadGridAxes()); + Assert.Equal(id, axis.Guid); + Assert.Equal(GridFixtureLabel, axis.Label); + Assert.Equal(-2, axis.HomeStoryIndex); + Assert.Equal(2.5, axis.ElevationToHomeStory); + Assert.Null(axis.ElevationToProjectZero); + Assert.Equal(new PlaPlanPoint(-2, 3), axis.Start); + double endX = variant == "mirrored axis" ? -2 - 6.25 * Math.Sqrt(3) / 2 : -2; + double endY = variant == "mirrored axis" ? -0.125 : 9.25; + Assert.Equal(endX, axis.End.X, precision: 12); + Assert.Equal(endY, axis.End.Y, precision: 12); + Assert.Null(axis.Arc); + Assert.Equal(segmented ? 1.25 : (double?)null, axis.FloorPlanSegmentLength); + Assert.False(axis.IsFloorPlanLineHidden); + } + else if (variant is "curved axis" or "mirrored arc" or "hidden arc" or "full circle") + { + var axis = Assert.Single(doc.ReadGridAxes()); + Assert.Equal(id, axis.Guid); + Assert.Equal(GridFixtureLabel, axis.Label); + Assert.Equal(-2, axis.HomeStoryIndex); + Assert.Null(axis.FloorPlanSegmentLength); + Assert.Equal(variant == "hidden arc", axis.IsFloorPlanLineHidden); + var center = new PlaPlanPoint(-2, 3); + var arc = Assert.IsType(axis.Arc); + Assert.Equal(new PlaGridArc(center, 2.75, angle * Math.PI / 180), arc); + var expectedStart = variant == "mirrored arc" ? new PlaPlanPoint(-4.75, 3) : new PlaPlanPoint(-2, 5.75); + var expectedEnd = variant switch + { + "mirrored arc" => new PlaPlanPoint(-2, 0.25), + "full circle" => expectedStart, + _ => new PlaPlanPoint(0.75, 3), + }; + Assert.Equal(expectedStart.X, axis.Start.X, precision: 12); + Assert.Equal(expectedStart.Y, axis.Start.Y, precision: 12); + Assert.Equal(expectedEnd.X, axis.End.X, precision: 12); + Assert.Equal(expectedEnd.Y, axis.End.Y, precision: 12); + + const double maxError = 0.001; + var points = Assert.IsAssignableFrom>(axis.Tessellate(maxError)); + Assert.Equal(axis.Start, points[0]); + Assert.Equal(axis.End, points[^1]); + foreach (var (first, second) in points.Zip(points.Skip(1))) + { + double midpointRadius = double.Hypot((first.X + second.X) / 2 - center.X, (first.Y + second.Y) / 2 - center.Y); + Assert.InRange(arc.Radius - midpointRadius, 0, maxError); + } + Assert.Null(axis.Tessellate(double.Epsilon)); + Assert.Throws(() => axis.Tessellate(0)); + } + else Assert.Empty(doc.ReadGridAxes()); + } + + internal static (byte[] File, Guid Id) GridAxisFixture(string variant, bool withStory = false) + { + Guid gridList = new("d940e8f4-4d66-4faa-86a1-6bf94c703228"); + Guid partitionRole = new("79b61203-ae84-4d88-a9c6-20ead705e0bc"); + Guid objectLibraryRole = new("189f453e-ea2e-4e38-afe9-660d1d25afc6"); + Guid libraryClass = new("2bfca33d-bd38-49e3-bf6d-52ac8b850b9f"); + Guid tableClass = new("11db227d-dbe4-45af-88b6-6fddea993f71"); + Guid tableRole = new("76ebf0a4-c2ef-483f-a1a8-28d3adde99a0"); + Guid id = Guid.NewGuid(), store = Guid.NewGuid(), descriptor = Guid.NewGuid(), table = Guid.NewGuid(); + + // The model grid has a project partition; the drawing representation does not. + var placementLinks = new List + { + GeometryRelation(0x12, gridList, variant == "wrong grid store" ? Guid.NewGuid() : store), + GeometryRelation(0x11, objectLibraryRole, descriptor), + }; + if (variant != "drawing copy") placementLinks.Add(GeometryRelation(0x12, partitionRole, Guid.NewGuid())); + + byte[] objectData = Synthetic.Concat(new byte[49], FramedElementId(ObjectClass, 289, "Grid")); + ObjectClass.TryWriteBytes(objectData); + var placement = objectData.AsSpan(49); + WriteLocation(placement[169..], 3, -2); + BinaryPrimitives.WriteDoubleLittleEndian(placement[206..], -2); + BinaryPrimitives.WriteDoubleLittleEndian(placement[214..], 3); + BinaryPrimitives.WriteDoubleLittleEndian(placement[222..], Math.PI / 2); + if (variant == "mirrored arc") placement[201] = 1; + BinaryPrimitives.WriteDoubleLittleEndian(placement[230..], variant == "nonfinite elevation" ? double.NaN : 2.5); + if (variant != "implicit unit scale") + { + BinaryPrimitives.WriteUInt16LittleEndian(placement[204..], 2); + BinaryPrimitives.WriteDoubleLittleEndian(placement[238..], variant == "unsupported scale" ? 0.75 : 1); + BinaryPrimitives.WriteDoubleLittleEndian(placement[246..], 1); + } + if (variant == "mirrored axis") + { + placement[201] = 1; + BinaryPrimitives.WriteDoubleLittleEndian(placement[222..], Math.PI / 6); + } + + byte[] descriptorData = new byte[89]; + libraryClass.TryWriteBytes(descriptorData); + new byte[] { 1, 0, 0x83, 0, 3, 0, 0, 0, 1, 0, 2, 0 }.CopyTo(descriptorData, 39); + Guid family = variant == "wrong library family" ? Guid.NewGuid() : new("b286e7ff-8856-42d5-b293-6084b1784db2"); + family.TryWriteBytes(descriptorData.AsSpan(51)); + Guid.NewGuid().TryWriteBytes(descriptorData.AsSpan(67)); + + byte[] marker = Encoding.Unicode.GetBytes(GridFixtureLabel + "\0\0"); + bool curved = variant is "curved axis" or "mirrored arc" or "hidden arc" or "full circle" or + "invalid arc angle" or "invalid arc radius" or "excessive samples"; + bool segmented = variant is "shortened line" or "nonfinite segment length"; + const int stringOffset = 8 + 7 * 72; + int tableSize = stringOffset + marker.Length; + byte[] tableData = new byte[57 + tableSize + 24]; + tableClass.TryWriteBytes(tableData); + new byte[] { 1, 0, 8, 0, 0x83, 0, 3, 0, 0, 0, 1, 0, 1, 0 }.CopyTo(tableData, 39); + BinaryPrimitives.WriteUInt32LittleEndian(tableData.AsSpan(53), (uint)tableSize); + BinaryPrimitives.WriteUInt32LittleEndian(tableData.AsSpan(57), 7); + WriteInteger(tableData.AsSpan(65, 72), "AC_Type_i"u8, curved ? 2 : 1); + int visibility = variant == "hidden arc" ? 3 : segmented ? 2 : 1; + WriteInteger(tableData.AsSpan(137, 72), "AC_LineVisibility_i"u8, visibility); + WriteLengthParameter(tableData.AsSpan(209, 72), "AC_Length"u8, variant == "nonfinite length" ? double.PositiveInfinity : 6.25); + double radius = variant switch { "invalid arc radius" => 0, "excessive samples" => 1e9, _ => 2.75 }; + WriteLengthParameter(tableData.AsSpan(281, 72), "AC_Radius"u8, radius); + var angleRow = tableData.AsSpan(353, 72); + double angle = variant switch { "mirrored arc" => 90, "full circle" => 360, "invalid arc angle" => 361, _ => 270 }; + WriteLengthParameter(angleRow, "AC_Angle"u8, angle); + BinaryPrimitives.WriteUInt16LittleEndian(angleRow[8..], 3); + WriteLengthParameter(tableData.AsSpan(425, 72), "AC_VisLength"u8, + variant == "nonfinite segment length" ? double.NaN : 1.25); + var labelRow = tableData.AsSpan(497, 72); + BinaryPrimitives.WriteUInt16LittleEndian(labelRow[8..], 12); + "AC_MarkerText_1"u8.CopyTo(labelRow[32..]); + BinaryPrimitives.WriteUInt32LittleEndian(labelRow[64..], stringOffset); + BinaryPrimitives.WriteUInt32LittleEndian(labelRow[68..], (uint)(variant == "truncated marker" ? marker.Length + 2 : marker.Length)); + marker.CopyTo(tableData, 57 + stringOffset); + + byte[] placementPool = new byte[2048], parameterPool = new byte[1024]; + var tableOwner = variant == "shared parameter table" ? GeometryRelationList(2, tableRole, Guid.NewGuid(), descriptor) : + GeometryRelation(0x12, tableRole, variant == "wrong parameter owner" ? Guid.NewGuid() : descriptor); + Add(parameterPool, 0, 4, table, tableData, tableOwner); + Add(placementPool, 0, 1, id, objectData, placementLinks.ToArray()); + Add(placementPool, 1024, 3, descriptor, descriptorData, + GeometryRelation(0x12, objectLibraryRole, variant == "wrong library owner" ? Guid.NewGuid() : id), + GeometryRelation(0x11, tableRole, table)); + + var gridStore = Relationship(GridStoreClass, 59, gridList, variant == "missing membership" ? Guid.NewGuid() : id); + var tableDirectory = new byte[40]; + BinaryPrimitives.WriteUInt64LittleEndian(tableDirectory, 64); + new Guid("34d77468-1d98-45b9-958d-1eea37423cb5").TryWriteBytes(tableDirectory.AsSpan(24)); + Guid storyClass = new("2fa7b8cb-ee33-48d6-8daa-8a3fe02bddea"); + var parts = new List + { + ClassTable((1, ObjectClass), (2, GridStoreClass), (3, libraryClass), (4, tableClass), (5, storyClass)), + OwnedDirectory(false, Guid.Empty, 128, new(1, 0, 64, id), new(3, 64, 64, descriptor)), + Synthetic.Block(PlaBlockMode.Raw, + Synthetic.Concat(tableDirectory, Synthetic.Record(new(4, 0, 64, table))), ver: 1), + Synthetic.Block(PlaBlockMode.Raw, gridStore, ver: 1, kind: 2, guid: store), + Pool(parameterPool), + Pool(placementPool), + }; + if (withStory) + { + byte[] stories = StoryTable(storyClass); + BinaryPrimitives.WriteInt16LittleEndian(stories.AsSpan(stories.Length - 6), -2); + BinaryPrimitives.WriteInt32LittleEndian(stories.AsSpan(stories.Length - 4), -1); + parts.Add(Synthetic.Block(PlaBlockMode.Raw, stories, ver: 1, kind: 5)); + } + return (Synthetic.Fdb(parts.ToArray()), id); + + static void Add(byte[] pool, int offset, ushort kind, Guid guid, byte[] data, params byte[][] links) + { + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(35), (uint)(data.Length - 39)); + Synthetic.Block(PlaBlockMode.Raw, WithGeometryRelations(data, links), ver: 1, guid: guid, extra: 1, kind: kind) + .CopyTo(pool, offset); + } + + static void WriteInteger(Span row, ReadOnlySpan name, int value) + { + BinaryPrimitives.WriteInt32LittleEndian(row[24..], value); + name.CopyTo(row[32..]); + BinaryPrimitives.WriteUInt32LittleEndian(row[68..], sizeof(double)); + } + } + + [Fact] + public void RejectsTruncatedGridStoreMembership() + { + var gridList = Relationship(GridStoreClass, 59, new Guid("d940e8f4-4d66-4faa-86a1-6bf94c703228"), Guid.NewGuid()); + BinaryPrimitives.WriteUInt32LittleEndian(gridList.AsSpan(82), 2); + using var doc = Open(ClassTable((2, GridStoreClass)), + Synthetic.Block(PlaBlockMode.Raw, gridList, ver: 1, kind: 2, guid: Guid.NewGuid())); + Assert.Throws(doc.ReadGridAxes); + } +} diff --git a/tests/PlaIO.Tests/PlaSceneReaderTests.cs b/tests/PlaIO.Tests/PlaSceneReaderTests.cs index 1aa79e9..e051902 100644 --- a/tests/PlaIO.Tests/PlaSceneReaderTests.cs +++ b/tests/PlaIO.Tests/PlaSceneReaderTests.cs @@ -94,6 +94,75 @@ public void RejectsAMalformedClassTable() Assert.Throws(() => PlaSceneReader.Read(scope.Path)); } + [Theory] + [InlineData("shortened line", false)] + [InlineData("hidden arc", true)] + public void GridOnlyScenePreservesFullAxesAndProjectElevations(string variant, bool curved) + { + var (file, id) = ElementReaderTests.GridAxisFixture(variant, withStory: true); + using var scope = TempContainer("grids.pln", file); + using var source = PlaDocument.Open(scope.Path); + var axis = Assert.Single(source.ReadGridAxes()); + Assert.Equal(id, axis.Guid); + Assert.Equal(-2, axis.HomeStoryIndex); + Assert.Equal(2.5, axis.ElevationToHomeStory); + Assert.Equal(-1.5, axis.ElevationToProjectZero); + + var result = PlaSceneReader.Read(scope.Path); + Assert.Empty(result.Diagnostics); + var scene = SceneJson.Read(SceneJson.Write(result.Document)); + Assert.Empty(scene.Validate()); + Assert.Empty(scene.Elements); + var grid = Assert.Single(scene.Grids); + Assert.Equal(Assert.Single(scene.Models).Id, grid.ModelId); + const double z = -1.5; + if (curved) + { + Assert.Empty(grid.Lines); + var path = Assert.Single(grid.Paths!); + Assert.Equal(axis.Label, path.Name); + Assert.Equal(new Vector3d(axis.Start.X, axis.Start.Y, z), path.Points[0]); + Assert.Equal(new Vector3d(axis.End.X, axis.End.Y, z), path.Points[^1]); + Assert.All(path.Points, point => Assert.Equal(z, point.Z)); + Assert.True(path.Points.Count > 2); + foreach (var (first, second) in path.Points.Zip(path.Points.Skip(1))) + { + double midpointRadius = double.Hypot((first.X + second.X) / 2 + 2, (first.Y + second.Y) / 2 - 3); + Assert.InRange(2.75 - midpointRadius, 0, 0.001); + } + } + else + { + Assert.Null(grid.Paths); + var line = Assert.Single(grid.Lines); + Assert.Equal(axis.Label, line.Name); + Assert.Equal(z, line.Elevation); + Assert.Equal(new Vector3d(axis.Start.X, axis.Start.Y, z), line.Start); + Assert.Equal(new Vector3d(axis.End.X, axis.End.Y, z), line.End); + } + } + + [Theory] + [InlineData("verified", false, 2.5, null, "grid-elevation-unavailable")] + [InlineData("nonfinite elevation", true, null, null, "grid-elevation-unavailable")] + [InlineData("excessive samples", true, 2.5, -1.5, "grid-tessellation-unavailable")] + public void ReportsGridAxesThatCannotBePlacedInScene(string variant, bool withStory, double? offset, + double? elevation, string diagnosticCode) + { + var (file, _) = ElementReaderTests.GridAxisFixture(variant, withStory); + using var scope = TempContainer("grids.pln", file); + using var source = PlaDocument.Open(scope.Path); + var axis = Assert.Single(source.ReadGridAxes()); + Assert.Equal(offset, axis.ElevationToHomeStory); + Assert.Equal(elevation, axis.ElevationToProjectZero); + + var result = PlaSceneReader.Read(scope.Path); + Assert.Empty(result.Document.Grids); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal(SceneSeverity.Info, diagnostic.Severity); + Assert.Equal(diagnosticCode, diagnostic.Code); + } + [Theory] [InlineData(true, 1, true)] [InlineData(true, 2, false)]