diff --git a/CHANGELOG.md b/CHANGELOG.md index 7676353e..61754cf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,252 @@ API between minor releases. ## [Unreleased] +### Fixed + +- A railing repeats every bar in its element and in the nested symbol it places; the copies project within a + millimetre of each other, so both were inked and the sheet carried a doubled line. The elevation now groups the + horizontal railing bars within a one-millimetre tolerance and keeps the copy nearest the viewer, leaving a + second bar more than 20 mm behind as its own line. Measured: raster line score A001 recall 98.6% → 98.7%, + A103 95.8% → 95.9% with precision 93.4% → 93.5%; A101, A102, A104 and A105 unchanged. New test: + `Collect_KeepsOneOfTwoCoincidentRailingBars`. +- Clip projected wall and railing uprights behind opaque slab sides in fine sections. +- Mask projected geometry behind closed floor cuts in fine section callouts. + +- Omit RPC planting cut by an active 3D section box plane using the placed type outline. +- Draw and light both sides of RPC planting meshes in shaded views. +- Print the saved daily and hourly boundaries of multi-day solar studies with their geometric horizon times. +- Shade the exposed solar band from the saved sunlight intensity over the model and paper background. +- Opaque model geometry can hide the solar compass markings behind it on the saved ground plane. +- Shaded solar-study views use the saved sunlight intensity and active sun direction to tint vertical terrain cuts. +- Orthographic shaded views print the saved soil cut hatch and colour on the section box's terrain faces. +- Evaluated schedule rows with a supported uniform Arial style print with their Revit row pitch and text baseline. +- Elevations and sections print supported drafting patterns on saved planar wall paint regions. +- Fine section callouts include screen-space ambient shadows from glazed curtain panels onto visible walls. +- Fine section callouts retain the contour of closed furniture meshes with saved cylindrical facets. +- Opaque fine section callouts clip upright wall and railing strokes behind nearer slab sides facing the view. +- Elevations use the topography cut pen on the soil side of a building pad's cut contour. +- Elevations clip projected wall and foundation edges behind opaque faces after the ground cut trims them, including + upright edges in building pad excavations. +- Opaque building sections clip window jambs and opening marks behind nearer furniture and preserve the dash phase. +- Elevation soil cuts use the saved outline to exclude RPC plants that lie wholly in front of the view. +- Regular fine sections use projected ambient shadows on aligned inner finishes of exterior walls with unattached tops. +- Regular fine sections with ambient shadows use the saved graphics colour of opaque fixture finishes. +- Section views shade upright, view-aligned risers of cut stairs using occluders with a visible projection. +- Plans print view-owned horizontal detail circles and preserve the outline of thin projected generic-model facets. +- Opaque plans print the projection and cut outlines of closed generic-model instances within the saved view range. +- Lit elevations retain shadows from fully clipped RPC plants on visible RPC foliage. +- Opaque fine sections tone projected single-layer exterior structural walls above their saved base level. + Below that level, ambient occlusion also samples more distant geometry within the section's crop and depth. +- Glazed curtain panels in opaque fine sections cover surfaces behind them and use the saved ambient intensity. +- Cropped plan grid ends use the paper-space crop margin when annotation cropping is off. +- Solar studies shade the exposed side of the solar band that faces away from the saved active sun. +- Shaded 3D views honor saved model category visibility and clip ground-plane shadows at the section box. +- Hidden-line site views print visible roof glazing inside the saved skylight openings. +- Site views keep cast shadows on their receiving roof surfaces and cast shadows from opaque skylight frames. +- Site views project visible horizontal stair treads and landings with their cast shadows. +- Site views draw visible top rail outlines and project shadows from their planar faces. +- Site views draw visible horizontal floor slabs and preserve skylight glazing over them. +- Elevations hide covered skylight frame edges when the glazing is seen edge-on. +- Elevations project shadows from opaque skylight frames onto their sloped host roofs. +- Elevations project cast shadows onto oblique vertical wall faces using the saved light direction. +- Elevations project shadows from explicitly opaque model faces onto planar mesh facets of structural foundations. +- Cropped sections trim projected edges where a nearer cut stroke covers them. +- Fine sections soften distant ambient shadows on exposed finishes of exterior walls with attached tops. +- Fine sections use the saved top attachment to exclude the joined roof from ambient shading on the exterior finish. +- In elevations, planar opaque faces of placed structural columns cast shadows using the saved light direction. +- Cropped detail views clip model edges added by layer boundaries and roof-wall joins to the saved viewport. +- Overview sections trim sloping railing lines behind nearer opaque wall faces. +- Fine section callouts with ambient shadows use the saved graphics colour of supported wall finish layers. +- Visible slab sides in opaque details shade from samples outside the nearer cut caps. +- Opaque detail cuts use the projection pen on the shared boundary between touching roof and wall profiles. +- Opaque fine section details preserve the visible spans of railing posts and curtain-wall mullions behind nearer model faces. +- Elevations retain distinct railing profile edges when the same visible face separates them by more than the projection pen width. +- Fine sections mask backing geometry at closed stair cuts and correct self-shadowing on verified convex stair solids. +- Sheet schedules localize evaluated Yes/No cells for the Russian print UI culture. +- Floor-plan room tags print the square-metre symbol in Cyrillic for the Russian print UI culture. +- Floor plans place continuous section marks from their saved view-specific extents, including filled heads and tails on jogged traces. +- Cropped section details shade oblique wall faces using their view angle and preserve the transmitted tone through nearer glazing. +- Unshaded floor plans print supported wall tops below the cut with their saved outline and projection pen. +- Fixture outlines in floor plans keep closed components that reference an identical deduplicated face. +- Floor plans smooth curved fixture outlines using the native arcs of the placed horizontal faces. +- Floor plans print closed sections of placed curtain panels and mullions with their saved category cut pens. + Horizontal mullions below the cut project their saved top faces within the plan range. +- Descending sketched stairs project their attached top rails and clip nosings by the saved rail faces. +- Regular fine sections cover surfaces behind simple closed wall cuts with the wall's cut face. +- Fine hidden-line sections shade white structural slab sides using nearby geometry and the distance to the section plane. +- Cropped construction details draw the stored layer interfaces of rectangular ceiling cuts. +- Overlapping cut contours in opaque construction details preserve their saved pen widths along each span. +- Nearer opaque faces clip round flue outlines in elevations and preserve the spans visible through decoded openings. +- Continuous drafting lines on supported fine section surfaces keep their saved positions through PDF rendering. +- Cropped opaque overview sections shade crossed planting panels from the saved solar position and ambient and sunlight intensities. +- Opaque overview sections keep intersected crossed entourage figures whole and resolve their visible panel outlines. +- Opaque overview sections print the visible outline of supported revolved assemblies behind the cut. +- Regular fine sections print the visible silhouette of placed specialty equipment built from closed revolved meshes. +- Fine model sections preserve visible door jambs at their original depths and print saved finishes on opaque doors. +- Regular fine sections shade the open areas of supported glass panes using nearby model geometry. +- Site plans print saved electrical and site equipment symbols, including photovoltaic panels and wind turbines. +- Visible site equipment with supported symbols casts shadows using the saved site lighting. +- Site plans size RPC planting marks from the saved plant height and draw the common radial profile. + +- Site plans respect the saved visibility of terrain, planting and entourage categories. A view that hides Property Lines + prints neither the property boundaries nor their segment tags. +- Floor plans leave out the leaf, glass, frame outline and mark of a door or window that the view hides, by element or + category, and keep its opening in the wall. Saved opening marks of hidden hosts are not printed, and the view's own + saved marks still stand in for the generated ones. Hidden stairs, railings and their top rails draw no outline. +- Upper floor plans draw the descending arrow of supported sketched stairs along their saved centre paths. +- Upper hidden-line plans draw saved nosings and mask room colour across the opening of a supported sketched stair run with a view-owned path. +- Patterned overview elevations print the visible axes of verified horizontal and inclined railing tubes whose diameter is narrower than the projection pen. +- Patterned overview elevations retain visible nearer copies of stair edges when a coincident farther projection was hidden. +- In lit elevations, RPC planting inserted in front of the view plane retains its terrain shadows and is excluded from the shadow pass on visible model and planting surfaces. +- Lit elevations use the saved light to shade the visible unlit faces of crossed-plane entourage, with depth clipping against the model and planting. +- Elevations outline crossed-plane entourage display meshes without printing their triangulation diagonals. +- Soil cut shadows in cropped elevations use the foreground planting facets that face the view plane. +- Section callouts keep projected face indices paired with their depths until sloping wall edge clipping is complete. +- Opaque plans draw saved top-view region edges, masks and symbolic curves for supported plumbing and furniture families at medium detail. +- Opaque plan furniture respects saved geometry exclusions for the top view. +- Opaque plans draw visible solid outlines and top opening rims of supported multi-solid fixtures. +- Plan viewports omit projected roof-opening outlines outside their saved vertical range and for hidden inserts. +- Patterned overview elevations restore verified round flue outlines and shade them using the saved light. +- Cropped opaque section details use the projected depth of planar walls, slabs and stairs, preserve visible coincident stair edges, and retain silhouettes of placed site objects. +- Cropped section details with saved ambient shadows show the backing through supported transparent glazing. +- In cropped section details with saved ambient shadows, transparent mass surfaces preserve the backing visible through them. +- Opaque cropped section details honor the view's saved hidden categories when projecting and cutting geometry. +- Fine sections with ambient shadows apply the saved glazing tone where a pane has no opaque backing. +- Regular cropped fine sections respect saved category visibility and keep the exposed spans of sloping wall edges. +- Fine sections project verified round structural columns with their material patterns and mask their projection at closed pad cuts. +- Opaque overview sections draw verified round column silhouettes with their surface patterns and use the exact element table for placed columns and casework. +- Opaque overview sections also use the exact element table for furniture, plumbing fixtures, speciality equipment and structural foundations. Placed terrain clips projected building pads behind it. +- Opaque overview sections at fine detail draw the saved floor layers and thin drafting hatches inside supported closed cuts. +- Cropped opaque overview sections trim projected wall edges inside overlapping coplanar faces of the same wall type and material. +- Patterned elevations and overview sections draw the open edges of placed planting meshes with their category pen, clipping them behind nearer geometry and the ground cut. +- Fine sections omit internal handrail seams shared by coplanar faces, including repeated faces from embedded rail components. +- Opaque fine sections use exact ownership to omit family definition geometry and retain exposed sloping wall edges in callouts. +- Regular cropped fine sections exclude embedded family geometry when the project table is exact, clip edges behind round shafts, and mask projections behind closed floor cuts. +- Regular cropped fine sections include placed terrain and verified planar facets in ambient occlusion. +- Fine sections shade thin frames missed by the regular sampling grid and retain both edges of thin rails where visible around nearer posts. +- Elevations clip shadows on convex terrain facets against the closer terrain. +- Cropped elevations with cast terrain shadows hide supported planar faces and projection edges behind nearer placed terrain. +- Cropped overview sections hide the projected wall edges and structural foundation faces and edges behind nearer placed terrain. +- Cropped overview sections fill the placed terrain behind the section plane, including small facets between the larger polygons. +- Overview sections keep the visible stair treads and compare nearby wall depth at the projected stair and railing edges. +- Overview sections compare oblique stair risers at the projected tread position within the same native stair assembly. +- Elevations with cast terrain shadows draw the saved ground colour below the horizon and clip cut terrain at the view plane. +- Cropped elevations project foreground planting shadows onto the soil cut at the saved view plane. +- Elevations respect authored shading colours on supported grouped electrical equipment and keep its transparent covers unfilled. +- Straight section traces in plans print the supported filled head and tail, with the viewport detail and sheet numbers. +- Plans use the saved cut height, material pattern and category pen for closed column profiles. +- Elevations and sections omit discovered light-source construction faces. Regular fine sections with + saved ambient shadows shade supported opaque surfaces from nearby model geometry. +- Fine section callouts use the saved glass tint over their opaque background. +- Fine sections retain visible lighting fixture outlines and thin suspension geometry. +- Fine section ambient shadows use the saved ambient and direct light levels. Occluded sample points + contribute to the tonal gradient across the exposed parts of the same face. +- Unshaded sheet plans keep native wall ends and jambs when a closed model section preserves the saved hosted openings. +- Unshaded sheet plans retain wall mitres from closed model cuts at the saved cut height. +- Floor plan wall fills use a white base when the saved view uses unshaded hidden lines. +- Axis-aligned floor plans on sheets draw saved circular elevation markers with one attached view and its sheet reference. +- Supported level heads print names and elevations with their saved family label positions, sizes and backgrounds. +- Elevation and section levels with model extents use their saved leader positions. The East elevation + on A105 aligns straight levels with the saved head column of the jogged levels. +- Detail callout boundaries use round caps on their fitted dash segments. +- Cropped hidden-line construction sections hide internal cut edges where walls of the same material + overlap in a closed profile. +- Closed wall, floor, foundation and pad cuts in cropped hidden-line construction sections print a white + base behind their material hatches. Projected surfaces retain their view shading. +- Construction sections with a saved crop print the terrain cut and its material hatch. The ground strip + is visible at the bottom of Typ. Wall Section on A104. +- Fine sections clip door and window outlines at nearer railing faces. On A105 the visible jamb + segments in Stair Section and Main Stair Detail remain between the rails. +- Title block revision tables with supported regular Arial styles use the saved header and body text sizes + for the heading and row heights. A hidden title section preserves the visible column header and its styles. +- Sections use the cut depths and jog positions of the saved front-cut trace. On A104 the deeper span + of Building Section reveals the terrace, floor and living room. Coincident projected outlines + underneath the cut strokes are clipped to their uncovered spans. +- Cropped section details ink the original face edges while keeping the cropped polygons for fills and occlusion. +- Sections draw saved right-only level heads and leaders with the model extent at the other end. +- Elevations and sections draw visible window and door opening symbols from the saved direction filters, + including families whose opening marks apply at every detail level. +- Elevations and sections ink coincident site mesh strokes once after clipping. On A104 this removes + repeated entourage strokes from West and Building Section and restores the outline of the figure + seen from behind using its saved mesh. + +- Elevations and sections respect saved hidden element lists. Fine section projections trim edges where they + pass behind the face of a stair tread or riser. + +- Elevations and sections omit viewport annotation geometry and meshes attached to discovered material, + constraint and reference plane records. + Fine sections preserve the distinct edges of cut stairs, runs and treads. + +- Fine sections show saved glazing patterns where recovered curtain panels cover the fallback faces of an + incomplete curtain assembly. + +- Fine sections keep coincident skylight frame edges at their model depths until hidden lines are resolved. + Transparent glazing leaves the visible edges of the frame behind it. + +- Fine sections clip placed site geometry at the section plane and omit unplaced site and planting symbols. + Regular fine sections with annotation cropping disabled use the saved full envelope for default grid heads. + +- Planting on elevations with cast shadows keeps its visible silhouette and shade in front of distant model + faces. Geometry closer to the viewer masks the covered portion of the planting. + +- Title-block text uses the family's font sizes and alignment. Labels wrap at their stored widths, and the scale + field shows a shared scale or the localized "As indicated" caption for mixed scales. + +- Site viewports draw saved terrain contours, roof footprints, cast shadows from model faces for supported view lighting, and + planting tags with their saved leaders. The north marker uses its family curves and saved placement. + Sloped terrain receives shadows and casts them beyond its edge onto the authored ground plane. + Primary and secondary terrain contours use their Object Styles pens. Supported roof patterns use the + saved face placement and leave skylight openings clear. Contour labels use their stored positions and directions. + Property boundaries fit the saved dash pattern to both ends. Supported segment tags show the bearing and + distance, including chord distances on arcs. + +- Fine sections print supported projected material patterns, including the stair views' timber cladding. + The Stair Section draws the saved callout for Main Stair Detail. Round railing tubes retain their + cylindrical silhouettes in fine sections. Cropped stair details use the saved annotation crop for default + grid and level ends. Straight top rails retain their native contours in fine sections, including when + the front and back faces project to the same outline. + Fine cropped stair sections use the saved cut patterns of their wall and floor layers. + Elevations and sections draw supported roof seam grids from the saved face placement and skylight openings. + +- Supported circular generic annotations print from the saved family fill, border and text. Sheet viewports + use the separate annotation crop, including on rotated site plans. + +- Opaque hidden-line sections with both shadow modes off use white model surfaces with their existing cut pens + and material patterns. + +- Supported viewport titles use their saved annotation-family geometry, font sizes, wrapping and display settings. + The extension line uses its stored placement and length. + +- Floor-plan door and window tags use their saved view anchors, annotation-family outlines, and instance or + type marks specified by the family labels. + +- Floor-plan room tags use their saved placement, supported leaders, and annotation family labels and frames. Area labels + use the project's display units. + +- Furniture and fixtures follow the saved floor plan range, including lowered levels. Opaque hidden-line + views mask room fills with the projected face boundaries, including holes. Hidden section marks stay hidden. + +- Cropped plans print supported linear dimension chains at their saved positions, with their witnesses, ticks + and project units. Horizontal text notes use their saved frames and leader geometry. + +- Cropped plan viewports print supported grid bubbles and leaders beyond the model crop from their saved datum + settings. Plan room fills and legend swatches use solid background colours saved in the view's room-name scheme. + +- Draw title-block PNGs from their saved placements and evaluate supported itemized schedule rows from stored + instance parameters. Render merged schedule text within its band. + +- Print rendered views at their saved paper size, project authored property boundaries onto the cropped site plan, + print rooms with curved boundaries, place room legends at their saved anchors, and include the building context + inside the stair section crop. + +- Cropped construction details draw stored straight callouts, batt insulation and computed break masks. Exact + wall and slab cuts can use the drafting cut patterns of their decoded layers. + +- Printing places cropped construction details by the stored viewport offset whenever the mapped crop + intersects the sheet. Details use their active annotation crop for default datum endpoints and print the + supported level and grid heads at their saved sizes. The four construction details on the Revit sample + sheet A104 now align with the reference export. + ### Changed - The printing docs say what is still not drawn (the plane of a section, the detail views without linework, the graphic @@ -15,6 +261,13 @@ API between minor releases. ### Added +- Use `--viewport-image ID X Y WIDTH HEIGHT JPEG` when printing sheets to include native rendered graphics for a + specific viewport, including the solar study. Bounds are measured in sheet millimetres. The option needs `--sheet` or + `--all-sheets`. An image that cannot be read exits with code 2; a repeated ID, a blank path and bounds that cannot be + drawn exit with code 1 and the usage text, and a file that is not a JPEG, a file over 64 MiB and a viewport that is + not on the printed sheets exit with code 1 and a message that names the viewport by its ID. + `SheetComposer.RenderSheets` throws `ArgumentException` for the same invalid `ViewportImages` entries. + - CLI and API: `rvtio sheets` lists sheet parameters and filters sheets by them, ported from rvt-prt's `list --params/--where` (Unreleased after 0.1.0). `SheetRecord.Parameters` carries the text and whole-number project/shared parameters of each sheet as display strings (numbers with units stay out until their units are read); Yes/No parameters (`Appears In Sheet List` and project/shared parameters of Yes/No kind, named in `SheetRecord.YesNoParameters`) read as `Yes`/`No`. `rvtio sheets --where NAME=VALUE` (also `!=` and `~` for contains, `*`/`?` wildcards, repeatable, case-insensitive) keeps only matching sheets; on a Yes/No parameter `true/false/1/0` mean `Yes`/`No`, every other field compares literally. A misspelt name or an empty match exits with code 1. `--params` lists each kept sheet's parameters on standard error, `--csv` writes them as CSV, `--json` keeps the default JSON. New API: `SheetFilter.TryParse/Matches`, `SheetCatalog.FromFiltered`, `SheetFilter.AvailableNames`. New tests: `SheetFilterTests`. - CLI: `rvtio print --where NAME=VALUE` (also `!=` and `~`, wildcards, repeatable) prints or lists only the sheets whose parameters match, as in `rvtio sheets --where`; it needs `--sheet`, `--all-sheets` or `--list-sheets`, and with `--sheet` a sheet prints when it is one of those numbered and matches the filters. New tests: `PrintCommandTests` filter cases. @@ -272,7 +525,27 @@ The text of a sheet prints too: a text note's RTF string (class 0x0F83 block) is - Windows and doors ink through their host wall: a window sits inside its wall, whose face decodes with no opening, so the wall face up to half a metre in front of a window or door edge no longer hides it — before, the whole window vanished behind its own wall (the West elevation drew no windows at all in the sampled bay). A genuinely separate mass further in front still hides them. The sampled bay now draws the four window frames with their sashes where the reference draws them (its dashed diagonals are family symbolism with no decoded source — the types carry only degenerate points). Measured: raster line score recall 34.6% -> 35.7% (A104), 42.5% -> 42.8% (A103), 36.3% -> 36.8% (A105) with precision 56.3% -> 56.5%, 73.3% -> 73.0%, 73.5% -> 73.1%; `rvt_prt compare` recall up on A103-A105 (92.0%, 78.5%, 88.4%) with lower vector-only precision on the raster-backed pages. New test: `OccludeEdges_KeepsWindowsSetIntoTheirWall`. Full print suites 138/138 green on net8.0+net10.0. - Documented dead end: filling each subdivided layer span with its decoded cut pattern (Sand, Diagonal up 1.5 mm and the like resolve for the thin skins, while the structural core has none) added ~190 in of vector ink with zero recall gain on A104 (measured `rvt_prt` 79.1% / 64.1% -> 79.1% / 60.2% with the hatch, raster flat at 35.7% / 56.5%). The decoded patterns do not match what the reference draws inside these strips, so only the layer boundaries ink. No code ships for this; the ground hatch has no source either (the file holds no terrain mesh, the pad type has no material, no pattern is referenced by any ground element). +- Plan fittings keep their inner loop: the bathtub's basin is an inner loop of its top face, and the face-union silhouette inks only the outer rim. The plan now draws each top face's inner loops after the silhouette (the reference shows the basin rim and the drain). Measured: raster line score A102 recall 93.86% -> 94.00%, precision unchanged 96.91%; other sheets unchanged. Test updated: `SampleFile_Level1FurnitureIsASilhouette` (over 90% of the lines are 5 mm grid edges, the rest are inner loops). Print test classes 593/593 green on net8.0+net10.0. + + Documented dead end: filling each subdivided layer span with its decoded cut pattern (Sand, Diagonal up 1.5 mm and the like resolve for the thin skins, while the structural core has none) added ~190 in of vector ink with zero recall gain on A104 (measured `rvt_prt` 79.1% / 64.1% -> 79.1% / 60.2% with the hatch, raster flat at 35.7% / 56.5%). The decoded patterns do not match what the reference draws inside these strips, so only the layer boundaries ink. + +- Occlusion on elevations and sections uses the stored host wall ID for windows and doors. A deeply inset window or door stays visible through its own wall. A skylight can show through the decoded opening of its host roof face, while other faces of the roof can still hide it. Separate foreground elements use the standard depth tolerance, and faces within the insert keep their existing clearance for inset frame detail. + +- Coarse elevations and sections at 1:100 or smaller keep the shared jamb of adjacent windows on the same host. Faces that project across the jamb retain the usual occlusion rule. + +- Overview sections at 1:100 and coarser print the grade from the intersection with the decoded topography. Projected building faces and solid building-pad footprints clip out concealed spans before PDF export. + +- Overview elevations print the decoded grade at the stored view plane where it crosses a solid building pad. The pad footprint and model faces in front of the plane clip the grade line. + +- Overview elevations hatch the ground below the visible grade and building pad from the project's site cut material and poche base. Drafting grids use the view origin and the hatch is clipped to the viewport. + +- Overview sections use the same site cut material below the cut terrain and pads. Projected model faces clip the hatch strokes before PDF export. + +- Ground hatch rows join overlapping and touching terrain spans before placing the drafting dashes. + +- Elevations and sections print supported round datum heads at their saved positions. Levels use the view's stored endpoints and leaders. Grid heads use their family dimensions and authored vertical extents. + +- The model crop clips terrain and planting fills before the datum annotation strip. ## [0.4.0] - 2026-11-13 diff --git a/docs/printing.md b/docs/printing.md index 53aaccec..f98178d7 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -47,34 +47,147 @@ left out until its renderer exists. The library API is `RvtIO.Print.PlanPrinter`: `Levels(document)` returns the printable levels, and `Render(document, levelId, scale, options)` returns a `PdfDocument` with one page. +Axis-aligned floor plans on sheets print the supported circular elevation marker with one attached view. +The marker's position and body and pointer families come from the RVT. The pointer follows the view direction, +and the labels read its detail and sheet numbers from the placed viewport. The saved crop, cut height, +coarsest scale and hidden elements determine which markers appear. +On sheets, walls in a plan with a saved unshaded hidden-line style use a white base under their outlines. +At the saved cut height, closed wall sections use the model faces and their opening loops. The cut retains +mitred ends, jambs and shared-wall joins. Saved hosted opening spans remain clear even where the model section +has a solid face above or below the opening. Such cases use the wall-axis outline with its saved gaps. +A wall below the cut and within the saved plan range uses its horizontal top face when that face covers the +wall's plan projection. The outline uses the Walls projection pen. +Opaque plans also retain the visible outlines of supported closed fixture components below the cut, even +when the same saved face belongs to more than one component. A rigid instance placement carries the +saved circular arcs into the view. Matching runs on horizontal face boundaries use the arc samples for +projection and occlusion. +Opaque plans clip supported closed generic-model instances between the saved bottom and cut planes. +The visible projection has a white mask, and the closed section uses the category's cut pen. Shared +projection spans use the cut pen once. Open geometry and nested cut rings are outside this path. +The projected outline keeps distinct edges of thin facets before testing them for coverage. +Plans also print closed horizontal detail circles with the default line style from the owning +view, using their stored centre and radius, view visibility and the Lines projection pen. +Plans cut supported closed curtain panels and mullions at the saved cut height and use their category cut pens. +Horizontal mullions below the cut and within the saved plan range project their top face with the projection pen. +Curtain outlines respect the viewport crop, category visibility, and hidden components and hosts. +Plans use closed column sections at the saved cut height, with the column category's cut pen and the +material's supported drafting hatch. A matching vertical cylinder in the placed symbol supplies a +circular outline. The bounding footprint provides the fallback when the cut is unavailable. +A straight section trace in an axis-aligned plan can print the supported filled head and tail. The view +type supplies the symbols, their bounds fix the size on paper, and the placed viewport supplies +the detail and sheet numbers. + ## Images The title block family's logo is read from the file: Revit keeps the placed image files in the partition streams, so the -reader decodes the PNG it finds there (8 bits per channel, RGB, RGBA or palette) to an RGB raster and the PDF writer -embeds it as an image object with Flate compression. The logo is fitted into the logo area of the title block strip with -its aspect preserved. The API is `PdfRasterImage` and `PdfPage.DrawImage`. +reader decodes the PNG to an RGB raster and the PDF writer embeds it with Flate compression. The renderer follows the +title block symbol's GImage to its ImageSymbol and image holder, and uses the stored origin, dimensions and scale +for axis-aligned placements. The constructed title block strip keeps its existing logo fallback. ## 3D views -A 3D view placed on a sheet (a rendering that has no image, a solar analysis) prints as an isometric projection of the -model from above the south west corner, white faces with their outlines: it is the massing the view would show, not the -shaded picture Revit renders. +A regular 3D view prints as an isometric projection of the model with white faces and outlines. An analysis view +with a decoded orthographic camera and an active model section box prints the model at its saved sheet position +and scale, using the RVT material colours. The view's saved category visibility controls which model geometry +appears and casts shadows. The section box clips the geometry in model space. With patterns enabled, +its vertical terrain cuts use the soil material's drafting hatch and colour. The camera foreshortens +the saved paper-sized grid on each cut plane. The grid starts from the model origin projected onto +that plane. +RPC planting appears and casts shadows when its saved outline fits the active section box. Oblique +planes use the type outline in its saved instance placement when it reproduces the saved world outline. +Both sides of its polygon meshes draw and cast shadows. In the supported shaded lighting mode, an +unassigned mesh material uses a neutral gray shaded by the active sun and the visible side's normal. +In the supported shaded lighting mode with zero configured ambient light, the cut faces use a diffuse tint based +on the active sun direction, the saved sunlight setting and each face's normal. The hatch keeps its material colour. +For a multi-day study with fixed hours, the saved study settings supply the compass size, ground level, dates, +time range and active frame. The compass follows true north from the active project location. The latitude, +longitude and time zone drive the solar band and dates. Hourly studies show the active sun and its time, +and shade the exposed side of the solar band that faces away from the active sun. +The start and end dates mark the daily guides. The saved clock times and the geometric horizon form the +time boundaries of the study area. The active date supplies its geometric sunrise and sunset labels. +Opaque model geometry hides the compass ring and ticks where they lie behind the model on the saved ground plane. +In the supported shaded lighting mode, the exposed single layer of the solar band blends its sunlit tint +with the model or paper background using the same transmission. +When the view enables lighting and cast shadows, opaque geometry casts shadows on model faces, terrain and the +saved ground plane at the active hour using the saved shadow intensity. The section box also clips shadows on +the saved ground plane. The solar annotation can be hidden independently. +Graphics transparency is composited at each pixel in depth order over the lit geometry behind the panes. Surfaces +facing away from the active sun use the saved shadow strength as an approximation for their light level. +The view's surface-pattern switch controls continuous and dashed model grids anchored to their saved face placement. +The edge switch adds saved planar boundary loops. These markings follow the painted faces, so openings, foreground +geometry and the model section box hide the corresponding parts. +To include Revit's full rendered study, export and crop the viewport image above its title, then supply the image +and its sheet bounds to the composer. + +```text +rvtio print model.rvt sheets.pdf --all-sheets --viewport-image ID X Y WIDTH HEIGHT image.jpg +``` + +`ID` is the placed viewport's element id. X and Y measure from the lower-left corner of the output sheet in millimetres. +The width and height use the same units. The API is `SheetComposeOptions.ViewportImages`. The supplied image +replaces the generated model image. The analysis viewport title comes from the RVT in both cases. + +The option may repeat for different viewports. It needs `--sheet` or `--all-sheets`, and it is refused with +`--all-views` and the listing options. The ID must be unique, the width and height positive, the coordinates finite +numbers and the path not blank; a violation exits with code 1 and the usage text after a message about the option's +arguments. The file must be a JPEG of at most 64 MiB, and the viewport must be on one of the printed sheets; a violation +exits with code 1 and a message that names the viewport by its ID. All of these are reported before any page is +composed. A file that cannot be read exits with code 2 and `Cannot read viewport image `. The PDF output path +must not be one of the images. ## Rendering views A rendering view (a 3D view Revit rendered) prints its image: Revit stores the JPEG in the block of the image symbol's type (class 0x0890), the reader finds it among the partition streams and the PDF writer embeds it with the DCTDecode -filter without decoding the picture. A sheet places it at the offset of its viewport, keeping clear of the title block -strip. +filter without decoding the picture. On sheets, a rendering is centred at its stored viewport offset and sized by +the image symbol's paper dimensions and the placed instance's scale. The default size and title block clearance +apply when the file's dimensions are unavailable. ## Printing a site plan -A view named "Site" or "Site Plan" draws only the planting tags and the north arrow over the paper: the reference -site plan shows no building, terrain, contours, planting graphics or entourage, only the tags with their leaders -(the fall of the ground reads from its spot elevations, the planting from its schedule). Each kind of plant is -tagged the way the planting schedule tags it (T1, T2, ... with the real type marks) on a leader line from the -plant, a north arrow stands at the lower right of the site, and a planting schedule under the plan lists -every kind of plant with its count. +A view named "Site" or "Site Plan" draws the terrain, contours, building outline, plants, entourage and the +authored straight and circular property boundary segments. The segments follow the same rotated view basis and crop +as the terrain and keep their full extent when surrounding terrain is discarded. Plant tags use the schedule type +marks (T1, T2, ...). The sheet includes the north arrow and planting schedule. +Placed terrain, planting and entourage respect the site view's saved element and category visibility. + +Cropped site viewports use the saved crop for the extent of the model. They draw stored primary and secondary +contours from placed terrain surfaces with their Object Styles pens. Supported contour labels use the stored +anchor, direction, text size and project length format. Planting instances use their saved insertion points. +RPC planting with a saved model height uses a circular plan mark with a radius of 27.5% of that height. +The 16 spokes use the shared profile measured on the Revit sample export and follow the saved view basis. +Planting without RPC metadata retains the bounds-based mark. +In lit elevations the saved RPC insertion point determines whether a plant casts shadows onto visible +geometry. An insertion point in front of the view plane keeps the terrain shadow contribution. An RPC that lies +entirely in front of that plane can also shade visible RPC foliage whose insertion point is inside the view. +Cast shadows follow the plane of a vertical wall face when it is oblique to the view and faces the light. +Planar mesh facets of placed structural foundations receive model shadows from surfaces whose saved +graphics appearance explicitly specifies opacity. +Supported planting tags use the family frame and label, the type mark, and the saved head and leader offsets. +Supported line-and-arc annotations such as the north marker use their family curves, pens and saved placement. +Coarse and medium site plans draw supported electrical and site equipment from saved top-view symbol curves +and masks. Masks cover terrain contours, and the saved lighting still shades the equipment. Visible site +equipment with a supported symbol can also cast shadows from its placed model faces. + +Property boundaries fit their line pattern between the segment ends, with equal terminal dashes. Supported +segment tags use the saved anchor and family label offsets. Quadrant bearings in degrees, minutes and seconds +use the active project location. The displayed distance of a curved segment is its chord length, and its label +follows the tangent at the saved anchor. Distance labels use their family's explicit unit format. +A site view that hides the Property Lines category, the segments' own category or a segment prints neither the +boundaries nor their tags. + +Opaque hidden-line site views print roofs within their saved view range. The boundary and skylight openings +come from the model face loops. The view projects planar glazing of visible hosted windows and clips the +white hidden-line fill to the roof openings. Where the view shows surface patterns, continuous model grids +use the face's saved pattern placement, with the face loops clipping the ink around openings. With relative lighting and a level +ground plane enabled, the saved sun angles project the roof shadow onto that plane at the view's shadow intensity. +The site view also projects horizontal treads and landings from visible placed stairs within the saved view +range. Nearer model and terrain faces clip the projection at their local depth. The visible stair surfaces +retain their cast shadows and use the saved projection pen for their outlines. +Visible horizontal slab tops use the same depth and shadow projection. The hidden-line glazing of roof +openings masks surfaces below the panes. +Placed top rails use planar faces from the visible railing's native geometry. The projected outline joins +the top faces, and their solid faces cast shadows onto the visible model and terrain. ## Printing an elevation @@ -86,19 +199,342 @@ other edge is drawn once, and an edge whose midpoint hides behind nearer mass is collapses to one line: parallel edges within 50 mm at the same depth and of the same length (a railing family drawing one board four times, a window jamb doubled by its frame) ink once, keeping the nearest; a short edge on a long one stays, lines at different depths stay, and staggered layers stay, so distinct linework is never lost. -Windowed details skip this and keep every fine construction line. A face counts as nearer +Windowed details skip this and keep every fine construction line. Fine sections retain separated +projection edges from the same visible door frame face and add them after model-edge selection. +A face counts as nearer by its nearest corner (a wall end turned away from the view still covers what stands behind it), and a midpoint on the boundary of the nearer face counts as inside (half a millimetre): stacked wall layers and window frames project -onto the silhouette of the mass in front, and the reference draws that silhouette once. Plants, topography and +onto the silhouette of the mass in front, and the reference draws that silhouette once. A window or door edge +can show through the wall identified by the insert's stored host ID. A skylight can show through the +decoded opening of its host roof face. For the host roof, depth is measured on the face at the projected +edge midpoint, so a nearer corner elsewhere on the slope cannot hide the window frame. Other roof faces +can still hide it. Fine sections and elevations that see the skylight glazing edge-on keep coincident skylight edges +at their model depths through occlusion. +Opaque frame faces hide farther edges and transparent glazing leaves them visible. The visible edges are +then merged in projection. Other inserts use a 500 mm clearance for their own faces to keep inset frame +details visible. Faces of other elements use the standard depth tolerance. At 1:100 and coarser, adjacent windows on the same host keep +their vertical junction when the incident faces project to opposite sides of it. Actual overlapping faces +still occlude. Elevations and sections omit viewport annotation geometry and skip discovered material, +constraint and reference plane meshes before projection. Native model elements that share the material +category are retained. Fine sections preserve +the distinct edges of cut stairs, runs and treads when consolidating coincident projections. In fine sections with +surface patterns enabled, an incomplete curtain assembly clears its fallback faces only over the corresponding, +face-on rectangular glass panes with decoded model fill patterns. Other cells keep the fallback geometry. Elevations and sections use the view's saved hidden element lists +before projecting model elements, datums and break lines. Fine sections clip projections at the closed, +face-on stair surfaces at their model depths and preserve the visible portions of partially covered edges. +The model crop limits fills and occlusion. Cropped section edges retain their original face boundaries, so +the crop rectangle adds no model strokes. +Plants, topography and site surfaces are left out of the building itself: they print as light shapes without outlines behind it, the faded context the reference export shows around an elevation (their faces of a few square metres, so the ground mesh does -not bury the building). Where the viewport decoded an axis-aligned crop box, the drawing is filtered to its rectangle +not bury the building). Overview sections and regular fine sections with a usable model crop intersect the upper +terrain faces with the saved cutting plane and print the visible grade line. Projected model faces and the +footprints of solid building pads hide the grade they cover. At 1:100 and coarser, elevations print the +terrain profile at the stored view plane. The foreground portions of elements that reach the view plane +can hide this profile. Elements wholly outside the view leave the grade and hatch visible. +Closed intersections through walls, floors, foundations and pads draw their cut contours at the elevation plane +and leave their interiors clear of the soil hatch. In elevations that show surface patterns, supported drafting +grids from the cut material fill the closed profiles. Rectangular cuts through layered walls and floors use +each layer's material. The view origin anchors the patterns in paper units. +These elevations and sections hatch the ground between the profile and the stored poche base. The project +`TrueNorth` record supplies the base elevation and cut material. The material's cut pattern uses its decoded +drafting grids, anchored to the view origin. On elevations, the hatch follows the visible terrain spans and continues under the +pad at its stored elevation. In sections, the fill follows the cut terrain and pad profiles. Projected model +faces clip individual hatch strokes before PDF export. Overlapping and touching parts on the same hatch row +print as a single interval. The grade stroke is drawn over the hatch. +Where the viewport decoded an axis-aligned crop box, the drawing is filtered to its rectangle at generation time (the scorer counts vectors, not the page clip), and levels, grids and the outline follow it. The stored rectangle is origin-relative view feet (rvt-prt's viewer_frames), while the collected content runs in absolute projected millimetres, so the filter offsets it by the view origin's projection; without the offset the frame lands right but the wrong slice of the model is drawn (the stair viewport missed by 146 mm, the 1:20 detail by 365 mm). -The level lines are thin and dashed (3 mm on, 1.5 mm off on the reference). Each spans its decoded datum +Sections with an orthogonal jog in the saved front-cut polyline project each horizontal span from its +own cut plane and join the spans at the saved jog. The end planes extend to the crop beyond the plan +symbol's end marks. At a shifted cut plane, the printer clips the parts of projected strokes that +coincide with cut strokes. Levels, grids and view-owned annotations draw once across the viewport. + +For the supported round datum heads, elevations and sections use the head symbol's saved dimensions. +Level names and elevations use the label style and position saved in the head family, including opaque backgrounds. +On Windows, regular 12 pt Arial labels use device text metrics for the text box. Other supported layouts use +the embedded font's metrics. +Levels use the view's stored datum ends and leader points where supported. A right-only level override keeps +the saved model extent at the left. A level with model extents uses its saved leader elbow and anchor. +When those anchors agree for levels of the same type and projected envelope, straight levels of that type +with the same envelope use the shared head column. Grids use the saved vertical bounds or that +view's own endpoint overrides. Authored annotations can extend outside the model crop, and their dash +patterns balance the two ends. For sections with an active section annotation crop, +default datum ends are clipped using its stored paper offsets around the model crop. The supported level +heads and top grid bubbles use their saved family sizes at the resulting endpoints. +Other heads and views without usable records use the existing fallback. + +A cropped construction detail can show a child callout on the same sheet. Its child crop supplies the rounded +boundary with round-ended dashes. The saved parent-view head point places the straight leader and tag. +The viewport supplies the detail number. In the roof connection, the view-owned batt insulation supplies its +axis and width, and the computed break-line symbols supply the stretched break path and masking side. The mask clips the covered model +and insulation strokes before they reach the PDF. Perpendicular wall cuts and horizontal floor and ceiling cuts use +stored drafting patterns in the matching material bands when both sides and the exact layer stack are available. +In opaque cropped details those bands also place the layer boundaries, including layers without a cut pattern. +Where closed wall and roof cuts share a boundary with material on opposite sides, the shared span uses the projection pen. +When solid cut edges with different object-style pens overlap, the wider pen inks only the span contributed +by its source cut. The narrower edge keeps its own pen outside that span. +Sections at 1:50 or larger with a usable model crop use the same cut patterns through the regular section +projection path, including cropped stair sections. The site context in fine sections uses placed elements +and is clipped at the same section plane. +Cropped construction sections also cut and hatch the site through their saved section plane. +The printed grade stays inside the model crop. The hatch uses the site material and clips around cut foundations. +Its stroke width comes from the Topography Surface cut pen at the printed view scale. +In opaque hidden-line construction sections, closed wall, floor, foundation, pad and layered roof cut +profiles use a white base. The base covers projected surfaces and clips the spans of model edges behind the cut. +Material patterns and cut edges print above it. Faces with decoded openings preserve the projection through +the opening when the cut rings close. In aligned opaque fine sections, wall material hatches follow +those rings around junctions and openings. A perpendicular cut shows the stored roof layer boundaries +when the opposing faces match the total layer thickness. Two slopes that share a ridge join at the +intersection of their offset planes. The verified roof section supplies the white base and the bounds +of each layer's drafting cut pattern. A saved Fine view with an aligned model crop also enables these +roof layers at smaller print scales. Roof layer boundaries print after the model edges have been resolved. Valleys, nested rings and incomplete +geometry use the fallback. In aligned fine sections, a stair with one decoded face material and closed +cut profiles uses that material's drafting cut pattern. The stair body's profiles supply the hatch once +even when a modeled landing shares part of the cut. +When two walls have the same single face material, a simple closed cut of one wall clips the interior spans +of the other's cut edges. The outlines and layer lines print at their own boundaries. +In opaque cropped details, view-parallel wall faces without openings clip horizontal wall projection edges +at their actual outlines when the whole face is nearer. The remaining spans use the verified source plane +to calculate depth at the new midpoint. An overlapping wall on the same plane then keeps the shared outline visible. +In cropped sections, the cut stroke covers coincident spans of farther projected lines when its pen is at least +as wide. Uncovered spans and lines with a saved view line style stay visible. +Overview sections and regular fine sections with a usable model crop use white base surfaces for a saved +opaque hidden-line display. Other fine sections use white surfaces when both saved shadow modes are off. +In regular fine hidden-line sections, upright projected sides of structural floors use a white base. +For supported opaque floors, ambient shading combines nearby blockers with distance-weighted visibility +from the floor side to the section plane. Projected single-layer exterior structural walls use the saved ambient intensity +to approximate their tone above their saved base level. For samples below that level, the section crop +and the depth to the cut plane bound the ray reach for ambient occlusion. +A regular fine section also paints a white cut face for a closed wall solid where the section plane yields +a single closed ring. A fine section callout uses the same rule for closed floor solids. The cut face +covers the projected surfaces and edges behind that ring. +Section cut pens, model edges and material patterns are handled independently of the surface colour. +Fine sections with opaque hidden-line display and surface patterns enabled print supported drafting grids on the +faces that name their material. In a cropped model section, each continuous line uses the saved spacing and +view origin, and the face clips the combined vector fill. This keeps line positions independent of the PDF +reader's repeated-cell placement. Dense patterns and detail windows use a reusable PDF tile. Regular fine +sections use the saved widths for supported surface pattern pen categories at the view scale. +Nearer faces cover patterns behind them. The sample's Stair Section and Main Stair Detail use the +wood cladding's 3 mm vertical grid. On an otherwise unpatterned planar wall face, a saved paint region +can carry its own continuous drafting grid. Its boundary and the face openings trim that grid, while the +full parent face supplies the solid geometry. The Stair Section also draws its nested Main Stair Detail callout using +the saved boundary, head and sheet reference. +Elevations and sections that show surface patterns also project a supported roof's continuous model grid +using its saved face axes and origin. Skylight holes interrupt the grid. Parallel opposite faces of a closed +roof shell use their relative plane depth to keep the interior skin behind the patterned exterior. +A curtain assembly with every native panel resolved prints the placed panels, doors and mullions. +Openings from the inner loops of walls and elevation frames apply to both fill and edge visibility. Glass faces use their +saved model pattern placement and material's dash grid, with the same instance transform as the face. +In regular fine sections with the saved opaque display and ambient shadows enabled, curtain panels cover +geometry behind their glazing. Their printed tone uses the pane material and the view's saved ambient intensity +with local ambient shadow sampling. Other supported glazing blends visible backing surfaces in model depth order +within the pane. +Regular cropped fine sections with the saved opaque display exclude model geometry in categories hidden in that view. +When the project element table has been read exactly, these sections leave geometry discovered outside the table out of the projection. +Opaque fine sections with an exact element table project placed family instances and skip geometry directly owned by a family definition. +Fill pattern definitions supply material graphics for faces and are excluded from the model geometry pass. +A sloping wall edge at constant view depth keeps the spans outside closer opaque planar faces in +regular sections and callouts. Visibility is resolved in model face order before painting the +fills from far to near. +Round structural column shafts wholly behind the cut use the analytic cylinder of the placed symbol when its facets match. +The silhouette carries supported drafting surface patterns. Fine sections also use the saved material colour. +Opaque overview sections with surface patterns use the same silhouette. When the project element table is exact, +these sections use placed structural columns, casework, furniture, plumbing fixtures, speciality equipment and +structural foundations. In cropped overview sections, nearer placed terrain clips projected building pad and structural foundation faces +and the projected edges of building pads, walls and structural foundations behind the cut. +The printed terrain uses the same placed facets clipped at the section plane. Small facets inside the crop +fill gaps in the background, and the cut profile and hatch still draw over the projection. +Overview sections retain coincident stair edges at their original depths until visibility is resolved. +Stair and railing projections compare their depth with the depth of a planar wall at the sampled point +on each edge. +Horizontal tread edges also use the sampled depth of oblique vertical stair faces in the same native +assembly. The serialized owner connects the parent stair with its placed runs and tread components. +Opaque overview sections draw the projected silhouette of supported placed assemblies with one native revolved +mesh and closed solids wholly behind the cutting plane. Nearer opaque faces and cut masks clip the silhouette. +Regular fine sections outline placed specialty equipment made of multiple native revolved meshes when the +decoded shells are closed and lie behind the cutting plane. Edge-on auxiliary faces are allowed. Nearer faces +clip the outline, and the individual facets of the equipment do not add seams. +At fine detail, these overview sections draw the layer boundaries and saved material cut patterns of supported +closed floor sections. Rectangular compound cuts follow the layer thicknesses from the floor type. +View-aligned wall faces at the same depth with matching type and material mask projected edges through their +interiors. The section checks the trimmed spans against closer geometry. +Nearer opaque wall faces aligned with the view also mask the covered lengths of sloping railing edges +parallel to the view plane. +Edges at constant depth behind the whole shaft are clipped at its silhouette. +Closed floor, building pad and supported stair cuts cover projected surfaces and edges behind the cut. +In fine section callouts with ambient shadows, a view-aligned wall face uses its saved graphics colour +when its opaque material matches an explicit finish layer of the wall type and render appearance is disabled. +Core materials and category defaults use the usual wall base. +In a fine section callout, the saved parent view identifies the detail. Its panes composite the +material tint over the opaque view base, with surface marks and model edges drawn above them. +Opaque fine section callouts with ambient shadows also account for entirely glazed curtain panels +in a screen-space depth pass clipped to the saved crop. The pass adds the contribution of visible +panes to view-aligned walls with the default surface fill. The sampling extent follows the paper +scale and the added tone uses the remaining ambient light after the model-space shadow pass. +In the sample project's Hidden Line Main Stair Detail, the reference panel 977507 also changes the tone of +the retaining wall outside its projected outline. In the tested view, this tone is independent of the panel +material's graphics colour and transparency. The screen-space pass is an approximation of this effect. +In Revit, ambient shadows operate on the rendered view's image buffers. [Autodesk Revit API Developer's Guide](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API/files/Revit_API_Developers_Guide/Basic_Interaction_with_Revit_Elements/Views/Revit_API_Revit_API_Developers_Guide_Basic_Interaction_with_Revit_Elements_Views_Displaying_Graphics_with_DirectContext3D_html.html) +In controlled exports of the same wall and rectangular solid, the wall receives less darkening at +1:30 and 1:40 than at 1:20. At a fixed view scale, PDF export settings from 72 to 600 dpi preserve +the dimensions of the embedded shadow tile and the sampled wall's median tones. +Regular fine sections also approximate ambient shadows on supported planar opaque surfaces. Nearby +placed geometry reduces the ambient light at sampled points. Regular cropped sections include placed terrain +and other verified planar facets. An opaque hit inside the local sampling radius blocks its ray completely. +For an aligned inner finish of an exterior wall with an explicitly unattached top, only blockers with a +projected face contribute to its ambient shadow. +On a view-aligned exterior finish of a wall with its top attached, the occlusion contribution decreases +with the ray's distance to the blocker. +When the wall's saved top-attachment steps identify a roof, its faces are excluded from ambient +shading on that exposed finish. +Ambient rays from stair surfaces enter closed convex stair solids through their verified outward-facing boundaries. +Where the section plane intersects a stair, ambient shadow samples on its upright view-aligned risers use blockers with a projected face. +The saved ambient and direct light +levels determine how much of the surface illumination can be blocked this way. Samples behind +nearer faces contribute to interpolation on the visible part of the same surface. When the regular sample +grid misses a thin face entirely, its nearest boundaries supply the sample positions. The tone is clipped +to the surface and its openings, with hatches and edges printed above it. In opaque cropped details, +slab sides use visible samples at cut caps. The nearest visible sample supplies the texture tone behind the cap. +Cropped section details with +saved ambient shadows composite supported view-aligned glazed panels and transparent mass surfaces over +their projected backing. The surface facing the view applies the material transmission once, with its +model pattern and edges printed above it. On opaque walls in cropped details, the direct component +decreases with the angle of incidence. The ambient tone visible through nearer glazing follows the pane +boundary and its inner loops. +In opaque cropped details, planar walls, slabs and stairs occlude projected edges at +the depth of the overlap. Saved hidden categories contribute neither projected geometry nor cut outlines. +Coincident stair edges keep their individual depths until visibility is resolved. +Placed site objects print clipped silhouettes behind the model. Cropped opaque overview sections with surface +patterns, ambient shadows and a supported still solar setting shade crossed planting panels using the saved +date, location, project orientation and ambient and sunlight intensities. The diffuse tone uses either side of +each panel. Projected depth determines which parts of the panels receive the tone where they overlap. The +planting outlines print above the fills. +Discovered light-source construction faces are omitted from elevations and sections. +Regular fine sections with ambient shadows use the saved graphics colour for opaque planar fixture finishes when render appearance is disabled. +Fine sections retain small planar faces of placed lighting fixtures, including the facets of thin +suspensions. Coincident projections remain separate by depth until visibility is resolved. +Fully nearer solid faces without openings clip the covered spans of constant-depth fixture edges. +Elevations and sections print supported window and door opening symbols from the placed family's saved +lines. Paired direction filters select the visible side. A saved detail-level condition applies where present. +The graphics style supplies the width, colour and paper dash lengths. The symbol lines go through visibility +before they are added to the model edges. +When a saved elevation shows surface patterns, front-facing walls print supported drafting grids in paper +units from the view origin. Continuous grids leave decoded wall openings clear. Dashed grids print on +faces without openings. +Opaque hidden-line elevations with supported view-relative lighting project cast shadows from planar walls, +roofs, floors, stairs and placed railings, and from planting mesh facets, onto front-facing surfaces parallel +to the view. Opaque skylight frames cast shadows onto the sloped face of their saved host roof when that face +has decoded openings. +Placed structural columns cast shadows from their planar faces when the face material does not declare transparency. +The saved intensity controls the fill. Face openings and the visible terrain cut clip it, and model edges +and surface patterns print over it. +Patterned overview elevations draw the outline of a placed vertical cylinder, such as a flue, when its +paired native cylindrical faces match the placed facets and both rims span the projected tangents. +Wholly nearer opaque faces clip the covered lengths of the flue outline. Their decoded openings leave the +exposed edges visible. The saved light direction sets the edge of the cylinder's own shadow. Cast shadows +use the plane through the two projected tangents. +The saved view plane also clips the casters for shadows on model surfaces and plants. +The same lighting projects building and placed site mesh shadows onto sloping topography. Closer terrain facets +mask shadows on the terrain behind them. In cropped elevations, placed terrain also clips planar building faces, +their patterns and cast shadows, and the portions of projected edges known to lie behind the terrain. +A common vector fill joins the shadows across visible facets. In a cropped elevation the saved view plane also +receives shadows from planting facets in front of it that face into the view or are edge-on. RPC plants +whose saved element outline lies entirely in front of the plane are excluded from this cut shadow. +The ground cut retains the eligible shadows under its hatch and clips them to the soil profile and the +closed cut contours. +Opaque site plans with supported lighting project shadows from planar roof, wall, floor, stair, terrain and pad faces. +Opaque planar frame faces of visible hosted skylights in the saved view range also cast shadows. +The closest visible receiving surface above the authored ground plane receives the shadow, including sloping terrain. +Terrain edges also cast onto the ground plane outside the terrain mesh. The PDF joins the shadow facets in a single fill. +Roof shadows retain their receiving face and print above that face's fill and below its surface pattern. +Supported dashed drafting grids in the ground hatch use reusable PDF tiling patterns. The saved dash lengths, +row spacing, shift and origin define the tile lattice. In elevations the opaque hatched cut hides projected +faces and model edges behind the grade and pad profile. The topography cut pen adds ink on the soil side of a +closed building pad cut. The pad keeps its own cut pen along the full contour. Nearer opaque faces clip the +remaining spans of walls and foundations after the grade trims them. They also clip upright edges that project +into a building pad excavation. +Openings in the covering faces preserve the visible parts of those edges. In sections that show the cut terrain, +closed intersections of walls, floors, foundations and pads mask this ground layer at the cut plane. The layer covers +projected surfaces behind the ground, so a distant wall cannot hide the grade at the cut. Model projection +edges behind the cut are clipped to the visible side of the ground. When the section shows surface patterns, +supported dashed drafting grids on wall faces use the same PDF tiles and retain the projected face outline. +In opaque hidden-line elevations with a saved gradient background, the PDF shades from the sky colour at +the model crop's top to the horizon colour at model elevation zero. Where the cropped elevation uses terrain +receivers for cast shadows, the saved ground colour fills the crop below the horizon. The saved view plane +clips the terrain surface in elevations that cut the ground. Projected terrain and model faces cover the background inside the +model crop. Elevations at 1:100 and coarser clip projected model geometry and its openings at the saved +view plane. +Elevations and building sections at 1:100 or coarser with a saved view plane draw placed planting and +entourage from their projected mesh facets. +In opaque building sections at these scales, nearer planar furniture faces clip the covered spans of +window and door opening marks and constant-depth window jambs. Opening marks retain the dash pattern +and phase of the full family line. +When the view shows surface patterns, the planting pen also draws the open boundaries of triangulated +planting meshes. Shared triangle edges and edges created by the view cut stay hidden. The printed spans +are clipped behind closer planting and model faces and below the visible ground cut. +The view plane clips the mesh, the model crop clips its projection, and a joined fill retains the silhouette +through small facets without printing the internal triangle edges. An RPC planting whose saved element +outline reaches the view plane keeps its projected silhouette and visible edges when its entire display +mesh lies in front of that plane. +With supported cast lighting, the triangulated site meshes also receive shadows. Ray projection uses the +facets behind the saved view plane, and the closer plant facets mask coverage on plants behind them. +In those elevations, opaque model faces and site objects clip planting fills and their shadows according to +the depth at each intersection. Model face openings leave the planting behind them visible. +Placed site families retain the exterior boundaries of small mesh facets, including rotor blades. +Materialless entourage display meshes made of two perpendicular upright planes print their joined +silhouette. The printer recognizes the saved triangles, including an optional flat base. With saved +cast lighting, their visible faces use the shadow tone where the light reaches the opposite side. +Their fills and shadows are clipped behind closer geometry, including foreground planting. Other +materialless entourage meshes retain the edges of their visible triangles. At a section plane the +printer trims the original edges without adding a cut edge across a triangle. Site edges with the +same pen and projected endpoints are inked once after visibility and crop clipping. For a mesh +that lies fully behind the cut plane with only back-facing or edge-on triangles, the printer also +outlines the projected silhouette, without adding its triangulation diagonals. +In opaque vertical overview sections, a crossed entourage figure that intersects the cutting plane +prints whole. The nearer upright panel masks the farther panel where they overlap, and the figure +occludes projected model lines behind it. +Placed grouped electrical equipment in an elevation retains the visible outlines of its sloping planar +faces. The edge visibility pass measures depth at the edge and reads the nested material transparency +and the frame openings, so glazed arrays can show the geometry behind the cover. +The elevation uses the equipment material's authored shading colour when the RVT selects it instead of +the appearance asset. Transparent covers keep their edges without an opaque face fill. +Sections draw the silhouettes of supported round railing tubes from their placed cylindrical faces. +The tube profiles share the section cut, view crop and hidden-line pass used by the rest of the model. +In patterned overview elevations, verified horizontal and inclined tubes no wider than the projection pen print once along +their placed analytic axis. The view plane, nearer model faces and foreground terrain determine visibility. +The tube strokes join the drawing after projected mesh edges are resolved. +If the first projected copy of a stair edge is hidden, a coincident nearer edge can supply the visible stroke +after it passes the model and terrain visibility checks. +Fine sections trim projected door and window outlines only along the portions covered by a wholly +nearer railing face. The remaining jamb segments stay visible between the rails. +Fine model sections keep the physical depths of door edges through that visibility pass. Identical +visible spans ink once after the viewport crop. With ambient shadows enabled, doors without +transparent panels use the authored grayscale shading colour on opaque faces that select it. +Nearer railing faces and separately stored balusters clip the covered spans of projected rail edges. +In opaque fine sections, nearer slab sides facing the view clip the spans of upright wall and railing +profiles that they cover. +Closed furniture meshes with saved cylindrical facets print their projected contour in fine section callouts. +The projection skips edge-on faces with openings because they cover zero area. +In fine opaque cropped details, coincident vertical railing and curtain-wall mullion edges retain their native depths through clipping. +A nearer solid can mask the middle of a post while its upper and lower spans remain visible. +Fine sections retain separately visible edges of the same thin rail profile when consolidating +coincident strokes. +When several railing faces share a projected edge, a fine section checks their actual endpoint depths. +An edge shared by coplanar faces on both sides at every depth is an internal seam, including when the +railing and its embedded components repeat those faces. +In coarse sections and elevations with a saved view plane, coincident rail projections keep their distinct +depths until the visibility pass. Coarse elevations apply the same rule to walls, windows and doors. Nearer planting facets clip +the surviving segments. In elevations with a saved view plane, horizontal and vertical boundaries of the same visible railing +face remain distinct when their separation on the sheet exceeds the projection pen width. +For a single prismatic top rail viewed square-on, the printer checks the original face boundaries for +visibility before removing duplicate projected outlines. The view crop trims the source edges without +adding a cap where the rail crosses the crop boundary. + +Fallback level lines are thin and dashed (3 mm on, 1.5 mm off on the reference). Each spans its decoded datum envelope while the datum stays near the crop; where the datum runs far past a narrow crop (the stair at 1:50), the line is clipped to the crop plus a label-strip margin on each side, as the reference ends its lines at the markers just past the frame. Each line ends in the marker the reference export uses: @@ -123,10 +559,10 @@ annotation pen table (pen 1 is 0.1 mm at every scale on the reference), not the A detail section (1:10 to 1:50) is printed when its plane is decoded: the cut is drawn inside the view's own file crop frame (the detail's true extent: a roof detail's crop sits at roof height), clipped to it at -generation time. Without a usable crop the cut falls back to a window of about 3.0 x 2.2 metres around the -point of the plane. A detail the file parks against the border or outside the page is still printed: Revit lays -such callouts out in a bottom row above their own titles (A104's four details), so the frame is anchored on the -decoded title label instead of the file offset. A stair detail (1:20) instead takes +generation time. The stored viewport offset locates the view origin, which can lie outside the page while +its crop is on the page. The mapped crop keeps its stored position whenever it intersects the sheet. +If the whole crop falls outside the sheet, the title provides the fallback anchor. Without a usable crop +the cut falls back to a window of about 3.0 x 2.2 metres around the point of the plane. A stair detail (1:20) takes the file's own crop frame, the way the reference places it next to the stair section; it keeps its grid bubbles and the level lines whose height falls in its crop (Level 1, Ceiling, Level 2: the three bands the reference draws at the same heights; the bands run to the label margin past the crop, while the reference ends each at its own @@ -137,9 +573,9 @@ one moves to the free place of the top row. A view of the section class whose na Stair Detail") is printed as a section too. The plane of a view is looked for in every chunk of the file, and the block layout (class 0x3F8) takes precedence over the older signature, so the details are found as well as the building sections. A viewport whose view is not printed (a wall section at 1:20, a schedule) is -neither drawn nor titled, so a sheet shows only the views the printer can stand behind. A stair section (a view whose name holds "stair", 1:20 to 1:50) -projects only the stairs, their railings, supports, lines, treads and risers, so the page shows the stair rather than -the whole building; the tread/riser boards are the mass the occlusion pass needs, otherwise the stair-body projection +neither drawn nor titled, so a sheet shows only the views the printer can stand behind. A stair section with a usable +crop includes the surrounding building cut within the crop. The stair-only fallback for a small-scale stair section +applies when its crop is unavailable. The tread/riser boards are the mass the occlusion pass needs, otherwise the stair-body projection edges stay inked where the reference hides them (483 faces and 35 stair edges with them, 440 and 121 without). Measured on the Revit sample project: the South view prints the two-storey facade with its balcony rail, columns and roof on sheet A103. @@ -155,9 +591,25 @@ reference draws the sunken living room's carpet as a `Sand` hatch inside the roo the dashes to the room polygon the same way. A stair belongs to both plans of its flight: the base level draws it going up and the top level draws the flight -arriving there (`STAIRS_BASE_LEVEL_PARAM` / `STAIRS_TOP_LEVEL_PARAM`). Its plan linework is the outlines of its -horizontal faces (tread and landing tops) seen from above, so the Level 2 plan carries the tread courses the -reference shows between the stair's sides. +arriving there (`STAIRS_BASE_LEVEL_PARAM` / `STAIRS_TOP_LEVEL_PARAM`). In a hidden-line view whose cut plane +crosses a single run with decoded linear boundaries, the printer uses the saved tread fronts and side paths. +The cut line goes through the last tread at or below the view's cut elevation, using the stair type's saved +angle and symbol size. The part below the line masks the room fill in white. The part above it uses the +stairs' above-cut projection styles and leaves the room fill visible. A straight run with both side paths +fully inside the visible range below the cut uses the saved tread fronts and a white mask across the run. +For a sketched run arriving at the plan's level below its cut, a stair path owned by the view identifies +the descending projection. The saved nosings and both side paths draw the run through its opening, +including treads below the plan's ordinary bottom clip. The joined side paths mask the room colour. +The attached top rail projects through the same opening when it lies below the plan cut plane. Its saved +top faces mask the parts of each nosing they cover at that nosing's elevation. +Other views and run layouts use the horizontal faces of the treads and landings. +An owned top rail with a decoded projection follows the host stair's cut line. The printer fills its +projected faces below the cut and inks the exposed boundary with the rail's projection styles. +On an upper floor plan, the view's own `StairsPathElement` places the automatic descending arrow for a +single straight flight below the cut. For a sketched flight crossing the lower clip, the saved centre +path runs from the last physical nosing to the first nosing at or above the view's cut offset measured +from the base level. The linked arrowhead type sets the open tip for both paths. A straight vertical +descending path can display its saved horizontal Arial label and text offset. A plan also draws the elements below its level that its view range shows. `PlanViewRange2` is a nested object of the view's block (not an element record): five offsets in feet (cut plane, top clip, bottom clip, view depth and a @@ -171,7 +623,9 @@ the roof below Level 2 — reaches the Level 2 plan as the double line along the title block spans (a composed sheet keeps that paper whatever `--paper` says; the option applies to plans and views) (the extent of the title block instance's type, snapped to A4 to A0), every placed viewport draws its view at the offset the file stores for it (the viewport record also stores the reciprocal of the view scale, used when the view's own scale parameter is missing), each view is titled as Revit titles it: the circled viewport number, the view name, its scale and the extension line under the title, drawn from the viewport record's own label origin and length (m_labelOrigin, m_labelLength) in the annotation pen, and the sheet's own text notes -are written at their positions. +use the saved note frame for supported horizontal notes. The top of the frame and the font ascent give the +first baseline. The stored frame height determines the spacing of multiple lines. In rectangular model-cropped +plans with annotation cropping off, the grid envelope is clipped at the model crop plus a fixed paper-space margin. Measured on the Revit sample project (rac_basic_sample_project.rvt, six sheets A001 and A101 to A105): all six pages are 841 x 594 mm (A1, the size of the "A1 metric" title block), and sheet A102 draws "Level 1" at (180, 453) mm and @@ -181,6 +635,10 @@ project name and its number come from the project information element when the p them), plus: a logo area, the project area, a revision table (No. / Description / Date) and the sheet information (name, number, issue date, drawn by, checked by)). +Title-block notes use their RTF font size and stored alignment. Labels use the linked font's cap height, their +stored alignment and rotation, and the saved text width when wrapping is enabled. The scale field uses the +sheet's override when present or reports the printed scale. Sheets with multiple scales show "As indicated". + ## Printing a sheet ```sh @@ -224,12 +682,44 @@ stays empty. | Columns | the stored bounding box footprint, as a filled rectangle | | Grids | the stored location lines, clipped to the extent of the level (a grid line can run far beyond the building), drawn dashed with the file's center-segment pattern like elevation grids, with a white bubble and the grid name at both ends | | Floors | the sketch loops of the floors of the level, light under the walls | -| Rooms | the floor face of the room's decoded boundary, filled with the colour the reference plan uses for that kind of room (master bedroom blue violet, master bath magenta, bedroom cyan, linen teal, hall blue, entry hall yellow, living light green, kitchen tan, laundry brown, mech green, bath green) and tagged with the room number and the area in m² in a rounded white box at the middle of the room, as the reference plan tags it (the legend carries the names) | +| Rooms | the largest horizontal face of the room's decoded boundary, including the boundary cache for curved walls, filled with the room colour and tagged with number and area. The printer derives area from that face when the room has no area parameter | | Doors | the leaf at one jamb, perpendicular to the wall on the side the door opens into, and the quarter arc it sweeps | | Furniture | the horizontal faces of the furniture, casework, plumbing fixtures, specialty equipment, stairs and railings of the level, seen from above as light outlines (a stair names its base level, STAIRS_BASE_LEVEL_PARAM, not a level) | | Door and window marks | a door's Mark in a circle beside the opening, a window's type mark in a hexagon, each on a leader line from the opening | | Dimensions | a chain between neighbouring grid lines on all four sides of the building, with the distance in millimetres, as the reference plan dimensions it | -| Room legend | below the plan: a colour swatch and the name of every kind of room on it | +| Room legend | the stored room legend instance anchors the first swatch, and its type sets the swatch dimensions. The printer sets text spacing relative to that size. Plans without a decoded legend keep the swatches below the plan | + +Doors draw saved leaf lines and circular swing arcs using the computed family variant and its +instance placement. The plan's cut height selects the symbol's saved range. For direction-only +symbols, including doors in curtain walls, the cut must cross the placed door's vertical bounds. +Wall openings come from the family's cut loop. The swing approximation covers cut-loop openings +without a matching symbol. +A door or window that the view hides, by element or by category, prints no leaf, glass, frame outline, symbol or mark, but its +opening stays in the wall. The saved opening marks of hidden hosts are not printed, and a view that has saved marks of +its own gets no generated mark for the openings left untagged. Hidden stairs and railings, by element or category, +draw no tread or top-rail outline, and a top rail is hidden with its railing. +Projected roof-opening outlines follow the plan's hidden-element list and saved vertical range. +The printer checks the height of the loop after applying the instance transform, so a skylight above +the range leaves the floor plan clear. + +In opaque plans, furniture silhouettes and their fills respect saved view-direction exclusions +along the family's vertical axis when the placement keeps it vertical. If the filter leaves no +projected model face, the printer keeps the model silhouette until it can read the substitute symbol. + +Plumbing fixtures represented by saved 2D family geometry draw the visible symbol lines in their +saved graphics styles, placed by the instance transform. Opaque views also draw decoded background +masks from closed face loops. Both follow the plan view range and hidden-element list. At medium +detail, supported plumbing families whose model body is excluded from the top view draw their +saved top-view regions, masking surfaces and symbolic lines, arcs and ellipses. Furniture uses +the same projection where a convex saved mask covers the model faces that remain visible from +above. + +Generic model families whose body lies below the plan cut use the projected silhouette of their +model faces, with the same visibility rules as furniture. +In an opaque plan, supported plumbing fixtures and generic families made of closed solids can also +show individual solid silhouettes and the rims of top openings. Surfaces above a line hide the +covered spans. Native surface tessellation supplies the outline when a folded polygon cannot be +triangulated in its local projection. A plan viewport whose view decoded an axis-aligned crop frame draws only that rectangle at generation time, the way elevations do (the scorer counts vectors, not the page clip): walls, furniture and opening frames outside it are dropped, their crossing edges cut without inking the crop boundary, like the reference cuts linework at the viewport frame. Grids keep running past the crop to their bubbles, as the reference draws them to the bubble row. @@ -240,52 +730,67 @@ holds no Cyrillic. Elements are selected by their level (`LEVEL_PARAM`); a wall without a location line or a column without a footprint is left out and counted by neither selection nor drawing. +Circular generic annotations with one solid filled region, a solid circular border and one horizontal text run +print on their owning sheet or viewport. Geometry, colours, pen weight, text placement and instance transforms +come from the RVT family and view. The annotation crop uses the saved paper offsets. This covers the sample's +41 help symbols, including the four on the rotated Site view. + ## What is still not drawn - **The crop region of a view**: a plan or elevation viewport whose view decoded a crop box draws the crop at the view's own scale (the frame is the crop rectangle, placed by the viewport offset); the axes the view was collected with must match the crop basis. A detail section (1:10 to 1:50) is drawn from its own file crop frame the same way, and a view without a decoded crop, with the crop region off or with a rotated basis keeps the whole-model frame. - **The four details of A104**: the "Typical Wall Roof Connection", "Typical Floor Wall Connection", "Typical Foundation Detail" and "Typ. Wall Section" viewports are placed outside the page by the file, so they are laid out in a bottom row above their own decoded title labels, the way Revit places such callouts. -- **A schedule's body rows**: the block of a schedule view stores its visible columns (the "How do I" schedule of the sample +- **Viewport titles**: supported horizontal families supply the marker curves, label anchors, font sizes and wrapping. + The viewport type controls title and extension-line visibility, and the viewport supplies the line placement. +- **Schedule evaluation**: the block of a schedule view stores its visible columns (the "How do I" schedule of the sample stores Level, Topic, What view, Reviewed?; the revision schedule No., Description, Date; the planting schedule Type Mark, Common Name, Count), its shown sections with the title height, the merged title bands and the body rows - with their stored texts, but not evaluated body cells: Revit evaluates them from the model when it draws the schedule. + with their stored texts. For itemized instance schedules with flat sorting, text, integer and Yes/No parameters, + and integer equality or inequality filters, RvtIO evaluates the body from the stored instance values. This covers + the sample's 40 rows in "How do I". Unsupported schedules retain their stored body grid. + The Russian print UI culture renders evaluated Yes/No cells as «Да» and «Нет». Text cells keep their stored values. + The title, merged instruction bands and ordinary column headings use supported saved cell styles. The styles + store cap height in logical pixels at 96 dpi. The printer uses the embedded font's cap height to convert to + half-point sizes and applies the stored horizontal and vertical alignment. + Evaluated rows use a column's horizontal alignment when all of its stored data rows agree. The regular Arial + 12-pixel body style retains its print row pitch and baseline when the saved cells share that style, including + schedules that fill otherwise empty stored cells from evaluated values. Every per-sheet schedule instance prints at its instance origin with its decoded columns, show flags, grid and outline pens (the negative category ids they name, resolved against the Object Styles), title bands and body grid; revision - rows come from the model revisions explicitly present on that sheet (the sample lists none, like the reference), - padded with empty rows to the decoded fixed height (ScheduleSegmentRec: 21 rows at the measured 16.30 pt pitch - on the sample) the way Revit fills the table to its height; and planting rows group the placed instances by - their resolved type (type mark with the T{n} fallback, common name from the type), with the stored leading - empty rows and a header that wraps into its columns like the reference. + rows come from the model revisions explicitly present on that sheet and pad to the fixed height stored in + ScheduleSegmentRec. For supported regular Arial revision styles, the saved header and body text cap heights + determine the row heights using the measured Revit ratio of 23/12. The heading uses its saved cell style, + including when the title section is hidden. The sample has 21 empty body rows at a 16.299 pt pitch. + Planting rows group the placed instances by their resolved type (type mark with the T{n} fallback, common + name from the type), with the stored leading empty rows and a header that wraps into its columns. - **The table grids of the title block family**: the linework, fixed texts and labels of the symbol are drawn, and the per-sheet schedule instances (revision tables, planting schedule, How-do-I table) print from their decoded view blocks; the symbol-embedded schedule template itself (the cached revision grid with GINFO_NOT_PRINTED) is left out. -- **Property and setback lines**: the site plan prints the topography, the contours, the planting and the entourage, but - the property and setback lines (OST_SitePropertyLineSegment) carry no geometry the reader decodes. -- **Images other than the logo and the renderings**: material textures and the sun-path of a solar analysis are not - pictures the writer can place; an analysis view (Solar, Lighting, Energy, Sun Path) prints no vector massing, - like the reference, which shows no such linework. -- **Annotation elements**: grid names, dimensions, room tags and the section marks are generated by the printer from - the decoded elements, not read from the file's own annotation elements; a section mark prints only where its +- **Setbacks**: setback lines remain outside the supported property graphics. Supported property segment tags print their saved bearings and distances. +- **Analysis shading**: the generated analysis viewport uses graphics colours, graphics transparency, approximate + dome shading and shadows from opaque model geometry. The supplied rendered image preserves Revit's rendering + of appearance assets and full lighting. +- **Annotation elements**: plans print supported grids, dimensions, room tags and text notes from the owning view's + decoded annotation data. Room-tag leaders support vertical attachments to a single centred label. Room area labels + use the project area format and print the square-metre symbol as Cyrillic м² in the Russian print UI culture. + A section mark prints only where its section answers to no view or to a plan at a scale no coarser than its own (wall-section callouts and fine - details stay in their parent views, undecodable views mark nothing), only when the file gives it an extent - record (the Architectural Section has none, so it marks nothing instead of inventing a trace); a decoded - front-cut polyline draws its jogs (the Building Section turns at its jog instead of running the full frame - height) while a mark without decoded points stays a straight ray; the trace, its ticks and its bubbles ink - with the Sections projection pen (pen 1 annotates 0.1 mm on the reference, where the old hardcoded 0.22 mm - inked every trace heavy); the trace is clipped to the viewport frame at generation; the view reference - marks of a plan stay undrawn. One measured exception: the Longitudinal Section's mark is drawn 3,090 mm along - +X from its decoded front cut, because the reference places it there while the Building Section's sits exactly on - its own cut (control: both at x = 592.1 pt) and no stored field explains the difference (`m_pntForViewData` is the - first front-cut point, `m_rotOffset.x` half the cut length, the view origin 3,280 mm — 190 mm away, nine times the - measurement error). + details stay in their parent views), and a decoded front-cut polyline places the jogs. On an axis-aligned plan + with annotation cropping disabled, the plan's `ExtentElem` supplies the continuous trace's endpoints as + distances from the section's saved trace origin. The endpoints move along the first and last legs, and the + trace can extend past the model crop. A trace without supported plan extents uses the stored front cut and + clips to the model frame. A trace with no decoded points uses the available straight ray, and views without + a section extent record leave no mark. The ink uses the Sections projection pen. Supported filled heads + and tails use the section type's symbols and the placed viewport's detail and sheet numbers. + Segmented section traces and view reference marks are outside the supported subset. ## Next steps -1. Decode the crop region of a rotated view and of a crop region switched off with live bounds, and the annotation crop that keeps titles and labels outside the model crop. Decode the record that places a viewport the file puts off the page. Assign section-mark ends per viewport (the Longitudinal trace matches the reference length but sits ~88 pt left of it with Y exact and walls aligned, so the shift is trace-specific with no file rule found yet; the reference puts a numbered callout bubble "3/A103" at its start while ours centers letter bubbles on the ends; Level 2 shows only a 171 pt stub near the stair where the file extent predicts 599 pt; the short callout bubbles with sheet references). -2. Evaluate the body rows of element schedules from the model (the How-do-I reference body is computed, not stored). -3. Decode the geometry of the property lines (with their bearing/distance labels) and the spot elevations, the solar-analysis diagram of a site sheet, and the file's own tag positions with leaders. -4. Decode per-view placement of viewports and datum annotation: our stair/detail frames follow the file offset while the reference resolves overlapping viewports side by side, and the reference lines its level marks up on the crop edge and ends each line at its own marker while ours run datum spans (clipped only past a label margin). Restore the long footing/grade model edges the file's footing instances never decode into geometry. The stair railing boards the reference omits in its stair views, and the interior edges behind a section cut (A103's 207 in of extras), are **not** a hide record: `m_oHiddenElementsViewSettings` (2160), `m_pHideElementsMgr` (2163) and `m_explicitlyHiddenElements` are null/empty on every view, no `HiddenElementsViewSettings` block exists in the model (the 2160 class tags in the view bodies are null-pointer annotations, each preceded by an `FF FF FF FF` token), and the railing ids (567887, 665711, 490129, 566588) appear in no view body. Both differences are Revit's coarse-detail model representation (all views here are detail level Coarse), which the file does not store as data — a printer rule would be a guess, so neither is implemented. +1. Decode the crop region of a rotated view and of a crop region switched off with live bounds, and the annotation crop that keeps titles and labels outside the model crop. Decode the record that places a viewport the file puts off the page. Decode the view-specific section extents, including the jogged Building Section and the short Level 2 stub. +2. Extend schedule evaluation to grouping, additional filters and computed fields. +3. Decode setbacks, spot elevations, and property tag leaders. +4. Extend datum support to left and dual level heads and additional head families. Resolve overlapping stair and detail viewports from their layout records. Recover the remaining footing and grade geometry and investigate residual interior edges and stair railing pieces. 5. Widen the same printing to the releases the reader supports in its own schema. ## Comparison with the reference export @@ -302,11 +807,98 @@ a partial layer. A rule accepted on that score alone is measuring an export arti the horizontal-edge, buried-work and railing-diagonal removals were reverted for exactly that reason. Judging those pages needs a raster-aware comparison (or a vector-only export of the reference). +**Raster score and residual attribution.** Rendering both PDFs at 100 dpi and scoring thin strokes with a 2 px +match radius gives, page by page (A001, A101–A105): recall 98.6, 94.2, 94.0, 95.8, 96.3, 92.6% and precision +99.1, 93.2, 96.9, 93.4, 95.6, 93.6%; tone correlation 0.96–1.00 over the inked blocks. The residual is not +missing geometry in most places: + +- A105 scores 97.6/97.7% at 200 dpi and 98.8/99.7% at 300 dpi. Its largest gaps at the 100 dpi grid are thin + lines that alias between pixel centres when our vector output is resampled, while the reference keeps them in + its embedded raster. Nothing in the drawing is absent. +- On A101 the worst blocks (recall 4–37%) lie inside the Solar Analysis study. Each candidate source was + measured and rejected: the decoded site contours ink there only as scattered lines (recall +0.00%, precision + −0.26%), the pad faces project elsewhere in the view, and the terrain mesh boundary and its creases add ink + the reference does not carry (recall +0.01% with precision −1.08% for the boundary, recall +0.1% with + precision −1.2% for breaks above 60°). The remaining gap is the reference's own resampled raster: the + anti-aliased edge of its 3D model, the model's stipple and tonal shading, and thin annotation lines. +- On A103 one block at the lower left (0% recall) is the topography's cut cap: a 13 m × 0.21 m section polygon + at the section plane (world X −13.6…−12.3 m, Y −2.18 m, Z 0.83…1.04 m), drawn by us as an unhatched face while + the reference fills it with a fine hatch. Its pitch does not match any decoded cut pattern (the site cut pattern + is a 6.35 mm brick, the concrete cut pattern 6–11 mm, both sub-pixel at 1:100), so the pattern itself is still + undecoded. The larger A103 gaps sit in the South elevation, where the guardrail's five horizontal bars are + decoded (100 mm pitch, view depth −18200) but the occlusion pass drops them. Instrumenting the pass with the + decoded polygons shows what actually covers each bar: only the railing itself (element 566588, faces 3 mm nearer + at −18203) and its nested symbol (566589, 14 mm nearer at −18214). The clad wall (427092, "Wall - Timber Clad") + does not reach the bars: its two faces span x = 13.06–13.26 m and z = −1.2…2.7 m, while the bars run at + x = 7.06–13.06 m. The floor slab (550255, "Generic 150mm") spans the bars' x but sits at z = −0.70…−0.55 m, + below them, and grazes only the bottom rail at z = −550. Exempting faces of the railing assembly + (categories −2000126/−2000127 within 15–20 mm of the bar) restores the bars: A103 recall 95.8% → 96.1% and + A001 98.6% → 98.7%, but A104 precision falls 95.6% → 93.8% for +0.3% recall and A105 falls 92.6% → 92.3% at + 93.6% → 93.3%, so the net score drops. Restricting the exemption to horizontal bars keeps A103 at 96.1/93.4% + and A105 at 92.9/93.3%, yet A104 still pays 95.6% → 93.7% precision for the same +0.3% recall: the extra ink + is the same bars drawn where the reference hides them (e.g. around 540–620 × 324–350 pt in the West elevation, + where the bars of a lower railing coincide with a wall face). The occlusion stands. The duplicate copies are + handled instead: the elevation merges the horizontal railing bars that project within a millimetre of each + other and keeps the nearest copy, which lifts A001 98.6% → 98.7% and A103 95.8/93.4% → 95.9/93.5% without + touching the other sheets (see the changelog). + +- Why the reference shows the A103 bars but not their A104 counterparts. Instrumenting both views shows the + added ink splits the same way: on A103 the un-hidden bars are 2171 pixels on the reference and 2173 off it, on + A104 1149 against 1456; A104's off-reference ink is concentrated on the **bottom rails**, which the reference + hides behind the solid base band while the thinner bars between the posts stay visible. The railing's materials + are opaque — "Stainless Steel 1" and "Iron Gray" both decode transparency 0, so no glass pane is involved and + the see-through rule cannot separate the cases. An extent-based exemption (the covering face must match the + bar's own projected rectangle within 2 mm) leaves A103 at 95.9/93.5% and loses A001 0.1%: the covering face is + a panel taller than the bar, not the bar's own strip. The reference draws railing rails as symbolic elevation + lines, which is why its bars survive their own solid; reproducing that needs a railing-specific display rule + rather than an occlusion exemption. + +- The railing carries no symbolic elevation data to decode. Its type (490129, `StairsRailingAttr "SH_1100mm"`) + stores no family and no geometry, and both railing elements (`566588 BaseRailing`, `566589 BaseRailingSym`) + report zero `ViewFacingLines` and zero `Edges` while their 100–106 faces are the modelled rails. 118 other + elements in the same file do carry view-facing lines (doors, planting), so the decoder is not the limit: the + railing simply has none. The rails exist as faces. What hides them in the South elevation is the midpoint test: + the bar runs from x = 7.06 to 13.06 m with its midpoint at 10.06 m, exactly behind the post at 10.05–10.07 m, + so the whole bar is dropped. Clipping the bar around the railing faces it crosses restores it between the posts + (the sheet now matches the reference's segmented bars) and measures A103 96.0/93.2% for the clip alone and + 96.2/93.2% with a 2 mm filter that drops clipped spans running alongside another rail. Both variants still cost + A104 1.8–2.0% precision (96.6–96.7% recall against 95.6%) and A105 0.3%, because the bars that land beside a + solid rail (A104's mid-rail) are not within the 2 mm filter either. The net score drops, so the clipping is + reverted; a faithful fix has to clip per span against the real 3D occluders of each bar copy, not against the + assembly's projected faces. + +- Per-span clipping against every nearer face (the step above) measures A103 96.4/92.6%, A104 96.6/93.7% and + A105 92.8/93.0% against the baseline 95.9/93.5, 96.3/95.5 and 92.6/93.6: recall gains 1.0 point in total and + precision loses 3.3, so it is reverted too. The spans the reference omits are the bars that sit inside a solid + rail — their projection is covered but their ends, which stick out a millimetre, survive a polygon clip. Only a + point-in-solid test against the railing's B-rep shells can drop them; the decoder has no such test today, and + the projected-polygon approximation cannot separate a bar inside the rail from a bar beside it. + +- The point-in-solid test was built and answers the question. Ray casting (Möller–Trumbore, one oblique fixed + direction, parity counted per shell so overlapping shells cannot cancel) over the railing's B-rep shells works: + a shell's centre tests inside, a point 30 m away outside, and the 15 + 14 closed shells of `566588`/`566589` + reduce to 379 triangles. Wired into the span clip it drops **nothing**: over the whole document not one railing + bar span has its samples inside a railing shell, and the score equals the plain span clip (A103 96.4/92.6%, + A104 96.6/93.7%, A105 92.8/93.0% against the baseline 95.9/93.5%, 96.3/95.5%, 92.6/93.6%). The bars the + reference omits are therefore not buried in the railing's own mass — they are separate geometry the reference + hides by some other rule, so a solid test cannot separate them. The feature is reverted; the remaining lead is + to find which element those bars belong to and why the reference drops that element in the West elevation. + +- The extra A104 bars belong to element 933840, `BaseRailing "SH_1100mm"` (category −2000126), one of the four + railings of that type in the model. Instrumenting the drawn edges in the band 930–1180 × 315–380 pt names it + directly: six horizontal edges at page y = 464…469 mm, one per 100 mm rail, all at the same view depth. The + element is neither hidden nor filtered: `ViewHiddenElements` for view 8237 ("West") is empty, its created phase + 86961 is the view's phase, its demolished phase is −1, and the view crop is active and contains the bars. So + the reference omits some of the railing's rails through hidden-line geometry, not through visibility settings, + and the "hidden element" lead is a dead end. The railing is a legitimate, visible element; the difference is + the same self-occlusion the earlier rules attacked. + + | Sheet | Printed | Still different | |---|---|---| -| A001 Title Sheet | the title texts, the five renderings from the file, the logo, the "How do I" table with its title, long-text band, header and body grid at its instance origin, and every revision table with its header and empty body grid to its fixed height | the evaluated body text of the "How do I" table (computed by Revit, not stored) | -| A101 Site Plan | the terrain wash with its outer edge, the contour lines (every fifth one heavier), the planting symbols with their crosshairs and the entourage outlines, the building filled dark from the rooms of its level under the wall outlines, the planting tags T1... with their leaders, the north arrow, the planting schedule with Type Mark / Common Name / Count in a ruled table at its instance origin, and the Solar Analysis viewport's title line and label (the study itself is a raster, so the viewport has no vector frame; its title is sheet annotation the reference prints); the site graphics are projected on the view's own axes (the Site view's crop basis is a −37° turn: `right = (0.7986, −0.6018)`) and placed through the crop frame at the view's scale, so the plan prints turned and sized as the reference, while the planting tags and the north arrow stay upright | the property and setback lines (no decoded geometry yet), the spot elevations, the solar-analysis diagram, the file's own tag positions | -| A102 Plans | both plans with the room colours of the reference, the room fills' floor surface patterns (`Sand` in the living room, from the carpet material of the sunken floor type's top compound layer, decoded to its line families and printed as drafting-pattern dashes), furniture as the plan silhouette (the boundary of the union of its faces on a 5 mm grid, so a chair keeps its back and the gap between its legs), stairs on both plans of a flight (the tread courses of its horizontal faces: base level going up, top level arriving), the observation deck's top rails from the view range (the rails stand on the roof below Level 2; the decoded PlanViewRange2 top and bottom clips decide which are visible), door and window tags, the room legend, the room tags, the grids dashed, and the section marks of the viewports they belong to (cut to the viewport frame at generation); one dimension chain above the building, 780 mm beyond the outer wall face as the reference draws it (measured 22.1 pt at 1:100), placed from the walls the viewport actually draws so off-crop retaining walls cannot push it off the page | the view reference marks (annotation elements whose positions the reader does not decode); the Building Section trace repeats in the Level 2 plan, whose own mark the file hides elsewhere; the short per-element dimensions of the other three sides; the Level 2 chain sits 24 pt below the reference's (22 pt above its face on Level 1 but 46 pt on Level 2 - a user-placed offset with no decoded rule) | -| A103 Elevations/Sections | South elevation and the Longitudinal Section cut at its true plane (feet-to-mm), level markers, the faded site; stacked wall layers hide on the silhouette, coincident modeling inks once, coplanar triangulation diagonals not inked, crop-filtered at generation; every visible edge inks, horizontals included — the wall top, the slab and roof outlines, the sills and the ground line all print, as the reference page shows (its drawing on this sheet travels as a raster image, so the vector layer alone lacks those horizontals and must not be used as the target); a section keeps both its cut profile (the roof slab at z=6898/7178) and the projected horizontals behind the plane, and carves the cross-section out of every solid the plane passes through (wall ends, slab edges, jambs); work below the lowest decoded level prints too (the foundation walls and their hatch down to z=-6302); level lines follow their datum envelopes near the crop with a label-margin cap for narrow viewports, and the grids dash coarsely ([36 9 9 9] pt from the grid type's line pattern), as the reference does | per-view level ends and markers (not decoded) and the long footing/grade model edges (footing instances lack decoded geometry). The 207 in of 0.283 extras are the interior seen behind the cut, attributed per category on the Longitudinal Section (model inches: walls 4,290, roofs 2,303, floors 2,043, building pad 1,904, casework 1,737) — Revit's coarse-detail representation, which the file does not store (see next step 4); the pairs 3.4 pt apart are the two faces of one wall, which coarse mode draws as a single line | -| A104 Elev/Sec/Det | West elevation and the Building Section cut at its plane, the four detail sections drawn from their own file crop frames in a bottom row above their titles, each with the annotation curves the view itself owns (`OST_Lines`, `OST_InsulationLines`, `OST_SketchLines` whose `OwnerViewId` is the view; clipped to the crop so a hidden line past its edge neither prints nor stretches the frame); cut-created edges ink heavy, projection edges thin | the fine placement of the four details (laid out from the decoded title labels with a 20 mm gap while the reference varies); the remaining in-detail 2D linework, which is not stored as view-owned curves (`OST_DetailComponents` holds 264 geometry-less attribute records, and the generic `OST_Lines`/`OST_SketchLines` curves name no owner) | -| A105 Elev/Stair Sections | Stair Section cut at its true plane with restored level lines, Main Stair Detail on the file's own crop frame with grid bubbles and the three in-crop level bands at the reference heights, East elevation, hidden lines removed; a railing's continuous rails print as the long diagonals they project across the stair, as the reference page shows, and its balusters stay; the crop filter runs in the true slice (origin-relative rectangle offset by the view origin); cut edges ink with their own category's pen; treads and risers included (they are `OST_StairsTrisers` and their mass hides the stair-body projection edges the reference hides) | the fine stair-profile linework the reference draws as coarse-detail graphics (this page's drawing is raster, so the vector comparison cannot judge it) and the level-line ends at the reference's own markers (bubble positions not decoded) | \ No newline at end of file +| A001 Title Sheet | the title text in its stored frame, the five renderings at their stored sizes, the title-block logo, the "How do I" table with its saved title and instruction-band styles, inline help marker, header and 40 evaluated rows at its instance origin, and every revision table with its header and empty body grid to its fixed height | remaining font and baseline differences in schedule text | +| A101 Site Plan | saved primary and secondary terrain contours and labels, property boundaries with fitted dashes and segment tags, roof surfaces with their saved standing seams and skylight openings, cast shadows on the visible terrain and the saved ground plane for supported lighting, planting at saved instance positions, planting tags with their family frames and leaders, the native north marker, the planting schedule at its instance origin and the Solar Analysis viewport title and the model projected with its saved camera and section box, or the complete rendered study when supplied with `--viewport-image`. The site is projected onto the stored rotated view basis and clipped at its saved crop. | detailed planting symbols, other roof surface patterns, setbacks and spot elevations | +| A102 Plans | both plans with solid background room colours from each view's RVT room-name scheme, the room fills' floor surface patterns (`Sand` in the living room, from the carpet material of the sunken floor type's top compound layer, decoded to its line families and printed as drafting-pattern dashes), furniture and fixtures within the saved view range, including the sunken living room, with white hidden-line surfaces from the projected face rings and a silhouette stroke on a 5 mm grid, saved stair treads, cut marks, owned top-rail projections and supported descending paths, plus horizontal tread outlines where the saved plan shape is unavailable, the observation deck's top rails from the view range (the rails stand on the roof below Level 2; the decoded PlanViewRange2 top and bottom clips decide which are visible), horizontal local door and window tags without leaders from their saved anchors and annotation families, the room legend, horizontal local room tags with saved positions, family labels and line frames, and supported single-label leaders, dashed grid centrelines with their stored bubble visibility and leaders, and the visible section marks and the saved circular elevation markers with their sheet references; four continuous dimension chains from the saved linear dimension curves and witness points, using the project length format; seven horizontal text notes with their saved frames and curved leaders | other styles of view references; furniture family symbolic curves and interior edges of overlapping projected geometry; other dimension styles and rotated or rich-text note layouts are outside the supported subset | +| A103 Elevations/Sections | South elevation and the Longitudinal Section cut at its stored plane, including the six saved level heads and their leaders on the section and the faded site; stacked wall layers hide on the silhouette, coincident modeling inks once, coplanar triangulation diagonals not inked, crop-filtered at generation; every visible edge inks, horizontals included — the wall top, the slab and roof outlines, the sills and the ground line all print, as the reference page shows (its drawing on this sheet travels as a raster image, so the vector layer alone lacks those horizontals and must not be used as the target); a section keeps both its cut profile (the roof slab at z=6898/7178) and the projected horizontals behind the plane, and carves the cross-section out of every solid the plane passes through (wall ends, slab edges, jambs); work below the lowest decoded level prints too (the foundation walls and their hatch down to z=-6302); level lines follow their datum envelopes near the crop with a label-margin cap for narrow viewports, and the grids dash coarsely ([36 9 9 9] pt from the grid type's line pattern), as the reference does | remaining footing and grade edges and detail-specific representations. Some projected interior edges and site shading still differ from the reference | +| A104 Elev/Sec/Det | West and Building Section, four construction details at their stored viewport positions, level and grid heads, nested callout boundaries and sheet references, roof batt insulation with authored breaks and masks, drafting hatch in matching cut material layers | other annotation families, some cut and projected material graphics, and the remaining in-detail 2D geometry | +| A105 Elev/Stair Sections | Stair Section including the surrounding building cut at its stored plane and crop with restored level lines, Main Stair Detail on the file's own crop frame with grid bubbles and the three in-crop level bands at the reference heights, Stair Section grid heads from their full saved envelope with annotation crop disabled, East elevation, hidden lines removed; a railing's continuous rails print as the long diagonals they project across the stair, as the reference page shows, and its balusters stay; the crop filter runs in the true slice (origin-relative rectangle offset by the view origin); cut edges ink with their own category's pen; treads and risers included (they are `OST_StairsTrisers` and their mass hides the stair-body projection edges the reference hides) | the fine stair-profile linework the reference draws as coarse-detail graphics (this page's drawing is raster, so the vector comparison cannot judge it) and the level-line ends at the reference's own markers (bubble positions not decoded) | diff --git a/docs/public-api.md b/docs/public-api.md index 563324ee..f5f6269c 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -84,7 +84,8 @@ See [sheets and viewports](sheets.md) for what is decoded, what the limits are a | `ElevationPrinter` | `Views(document)` lists the elevations and the building sections (North, South, East, West, Section, Stair Section) with their scale; `Collect(document, direction, stairsOnly, planeView)` projects the model faces on the plane of the view when the reader decoded it (a section is cut at that plane: the geometry in front of it is removed and the crossing polygons are clipped) or on the plane of the direction taken from the name; a stair section projects the stairs alone. `DrawContent` writes them. | | `ElevationView` | An elevation view: id, name, direction (north, south, east, west, section, iso) and scale. | | `SheetComposer` | `Sheets(document)` lists the numbered sheets with the page their title block spans; `Render(document, sheetId, options)` and `RenderSheets` compose pages: each placed viewport draws its plan at the stored offset and view scale, labelled with the view name and scale, and the sheet's own text notes are written. | -| `SheetComposeOptions` | `PaperSize` (null takes the title block extent, snapped to A4-A0), `DrawViewLabels`, `ViewMarginMillimetres`. | +| `SheetComposeOptions` | `PaperSize` (null takes the title block extent, snapped to A4-A0), `DrawViewLabels`, `DrawRoomLegend` (the room legend under a plan), `ViewMarginMillimetres`, `DrawPageFrame` (the page border and the sheet number and name at its lower right), `ViewportImages` (optional rendered images keyed by viewport element id). | +| `SheetViewportImage` | An `IPdfImage` and its bounds in millimetres from the sheet's lower left. The viewport must belong to a selected sheet. Coordinates and dimensions must be finite, and both dimensions must be positive. `SheetComposer.RenderSheets` throws `ArgumentException` for an entry that is not a viewport of the selected sheets, has no image, or breaks the bounds rules. | | `ComposedSheet` | A composed sheet: id, number, name, page, placed viewport count, text count. | | `SheetPrinter` | `Sheets(document)` lists the sheets with page-sized decoded linework; `Render(document, sheetId, options)` and `RenderSheets` print one page per sheet from the lines the sheet owns, on the paper the linework spans. | | `SheetPrintOptions` | `PaperSize` (null uses the linework extent, snapped to A4-A0), `MarginMillimetres`, `PaperToleranceMillimetres`, `DrawSheetFields`. | diff --git a/src/RvtIO.Cli/PrintCommand.cs b/src/RvtIO.Cli/PrintCommand.cs index 04370655..c80bd4fb 100644 --- a/src/RvtIO.Cli/PrintCommand.cs +++ b/src/RvtIO.Cli/PrintCommand.cs @@ -23,6 +23,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) var viewTexts = new List(); var sheetTexts = new List(); var whereTexts = new List(); + var imageFiles = new Dictionary(); int scale = 100; PdfPageSize? paper = null; bool listLevels = false, listViews = false, listSheets = false, allViews = false, allSheets = false; @@ -64,6 +65,16 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (i + 1 >= args.Length) return Usage(error, "--where needs a filter: NAME=VALUE, NAME!=VALUE or NAME~TEXT."); whereTexts.Add(args[++i]); break; + case "--viewport-image": + if (i + 6 >= args.Length + || !int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out int viewportId) + || viewportId <= 0 || !Coordinate(i + 2, out double x) || !Coordinate(i + 3, out double y) + || !Coordinate(i + 4, out double width) || width <= 0 + || !Coordinate(i + 5, out double height) || height <= 0 || string.IsNullOrWhiteSpace(args[i + 6]) + || !imageFiles.TryAdd(viewportId, (x, y, width, height, args[i + 6]))) + return Usage(error, "--viewport-image requires a unique viewport ID, X Y WIDTH HEIGHT in mm, and a JPEG path."); + i += 6; + break; default: if (arg.StartsWith("--where=", StringComparison.Ordinal)) { @@ -77,6 +88,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) break; } } + bool Coordinate(int index, out double value) => + double.TryParse(args[index], NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value); if (file == null) return Usage(error, "print requires the file."); var whereFilters = new List(); foreach (string text in whereTexts) @@ -88,6 +101,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (whereFilters.Count > 0 && sheetTexts.Count == 0 && !allSheets && !listSheets) return Usage(error, "--where selects sheets; it needs --sheet, --all-sheets or --list-sheets."); bool listing = listLevels || listViews || listSheets; + if (imageFiles.Count > 0 && (listing || (!allSheets && sheetTexts.Count == 0) || allViews)) + return Usage(error, "--viewport-image requires --sheet or --all-sheets."); if (!listing && outputPath == null) return Usage(error, "print requires the output PDF path."); // The comparison is the file's identity, not the spelling of the paths: an output path that is a hard link, // symbolic link or junction to the input PDF would truncate the model. ExportReport.SameFile guards the other @@ -98,6 +113,38 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return RvtExitCodes.Usage; } + var composeOptions = new SheetComposeOptions { PaperSize = paper }; + if (imageFiles.Count > 0) + { + var images = new Dictionary(); + foreach (var (id, input) in imageFiles) + { + if (ExportReport.SameFile(outputPath!, input.Path)) + return Usage(error, "The PDF output path is a viewport image input."); + try + { + using var stream = File.OpenRead(input.Path); + if (stream.Length is < 4 or > 64 * 1024 * 1024) + return Usage(error, $"Viewport image {id} must be a JPEG no larger than 64 MiB."); + var bytes = new byte[(int)stream.Length]; + stream.ReadExactly(bytes); + // The header is read here so that a file that is not a JPEG is reported by name, without the + // parameter name of the constructor. + var (jpegWidth, jpegHeight, _) = PdfJpegImage.ReadHeader(bytes); + if (jpegWidth <= 0 || jpegHeight <= 0) + return Usage(error, $"Viewport image {id} ({input.Path}) is not a JPEG."); + images.Add(id, new SheetViewportImage(new PdfJpegImage(bytes), + input.X, input.Y, input.Width, input.Height)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + error.WriteLine($"Cannot read viewport image {input.Path}: {exception.Message}"); + return RvtExitCodes.InputError; + } + } + composeOptions.ViewportImages = images; + } + RvtDocument document; try { @@ -204,8 +251,10 @@ IReadOnlyList ListedComposed() => error.WriteLine("No numbered sheet was found; nothing to compose."); return RvtExitCodes.DecodeError; } - pdf = SheetComposer.RenderSheets(document, toCompose.Select(sheet => sheet.SheetId).ToList(), - new SheetComposeOptions { PaperSize = paper }); + var composeIds = toCompose.Select(sheet => sheet.SheetId).ToList(); + if (SheetComposer.ViewportImageProblem(document, composeIds, composeOptions.ViewportImages) is { } problem) + return Usage(error, problem); + pdf = SheetComposer.RenderSheets(document, composeIds, composeOptions); } else if (allViews) { @@ -239,8 +288,12 @@ IReadOnlyList ListedComposed() => } var sheetIds = selection.SheetIds; var composedIds = selection.ComposedIds; + if (composeOptions.ViewportImages != null && sheetIds.Count > 0) + return Usage(error, "Viewport images require sheets with decoded viewports."); + if (SheetComposer.ViewportImageProblem(document, composedIds, composeOptions.ViewportImages) is { } imageProblem) + return Usage(error, imageProblem); pdf = sheetIds.Count == 0 - ? SheetComposer.RenderSheets(document, composedIds, new SheetComposeOptions { PaperSize = paper }) + ? SheetComposer.RenderSheets(document, composedIds, composeOptions) : SheetPrinter.RenderSheets(document, sheetIds, new SheetPrintOptions { PaperSize = paper }); } else if (viewTexts.Count > 0) @@ -412,7 +465,7 @@ private static int Usage(TextWriter error, string problem) error.WriteLine(problem); error.WriteLine("Usage: rvtio print [--level ] [--view ] [--sheet ] " + "[--where FILTER] [--all-views] [--all-sheets] [--scale ] [--paper A4|A3|A2|A1|A0] " - + "[--list-levels] [--list-views] [--list-sheets]"); + + "[--viewport-image ID X Y WIDTH HEIGHT JPEG] [--list-levels] [--list-views] [--list-sheets]"); return RvtExitCodes.Usage; } } diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 1a83eaf2..b597e326 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -66,6 +66,7 @@ Report options (read the file and print or write a report instead of exporting): write the sheet catalog (sheets, viewports, parameters, limits not decoded) as JSON print [--level ] [--view ] [--sheet ] [--where FILTER] [--scale ] [--all-views] [--all-sheets] [--paper A4|A3|A2|A1|A0] + [--viewport-image ID X Y WIDTH HEIGHT JPEG] [--list-levels] [--list-views] [--list-sheets] render the plan of one level, one or more views (plans and elevations) or all of them, or one or more sheets, to PDF diff --git a/src/RvtIO/Internal/GRepData.cs b/src/RvtIO/Internal/GRepData.cs index 73d8fe47..12b97009 100644 --- a/src/RvtIO/Internal/GRepData.cs +++ b/src/RvtIO/Internal/GRepData.cs @@ -1,5 +1,14 @@ namespace RvtIO.Internal; +internal sealed record DoorPlanSymbol((double Lo, double Hi)? CutRange, + IReadOnlyList Curves); + +internal sealed record StyledModelLine(double[] Start, double[] End, int StyleId); +internal sealed record PlanFixtureGraphics(List Lines, List> Masks, + PlanFixtureProjection? MediumProjection = null, PlanFixtureProjection? CoarseProjection = null); + +internal sealed record PlanFixtureProjection(List Lines, List> Masks); + internal record GRepData { public int GStyleElemId { get; set; } @@ -65,6 +74,10 @@ internal record GRepData /// symbols contain many independent mapped children; retaining only one loses solids. public List Instances { get; set; } = new(); + /// Authored projection strokes with view filters, in the representation's own frame. + public List? ViewFacingLines { get; set; } + public IReadOnlyList? DoorPlanSymbols { get; set; } + /// For a FamilySymbol complex cutter, the authored dummy-host closure plane /// in family-local coordinates. Replacing the symmetric dummy-host slab delimited by /// this plane with the real host slab preserves every authored reveal/protrusion. @@ -108,10 +121,22 @@ internal record GRepInstance public long NodeOrder { get; set; } } +internal sealed record ModelFacePattern(int PatternId, double[] Origin, double[] U, double[] V); + +internal sealed record ViewFacingLine(double[] Start, double[] End, double[] Axis, int StyleId, + (int Comparison, int Level)? DetailCondition = null); + +internal sealed record SurfaceMaterialRegion(int MaterialId, List Outer, List> Holes); + internal record GRepFace { + public List? SurfaceRegions { get; set; } + + public bool ExcludedFromTopPlan { get; init; } + /// GFace.m_renderStyleId: the material element of the face; absent when not read. public int? RenderStyleId { get; init; } + public ModelFacePattern? ModelPattern { get; init; } public double[] Envelope { get; set; } = Array.Empty(); public bool Orient { get; set; } @@ -160,6 +185,7 @@ internal record GRepFace /// True for a tessellated patch of a non-planar surface (cylinder, cone, revolution, ruled, Hermite). public bool CurvedSurface { get; init; } + public bool PolygonMesh { get; init; } /// The face lies on a plane surface of the file (GSurface class Plane). When every face of a closed shell lies /// on a plane, all its edges are straight lines and the shell is a polyhedron whose volume is exact. diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index acb03837..334c7385 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -157,6 +157,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan public Dictionary> ElemBipInts { get; set; } = new(); public Dictionary ElemBaseFields { get; set; } = new(); public Dictionary GrepBlocks { get; set; } = new(); + public Dictionary PlanFixtureGraphicsBySymbol { get; } = new(); internal Dictionary RailingQuantityInputs { get; } = new(); /// While set, the symbols placed from are taken at the Coarse detail level. @@ -281,7 +282,12 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Material element id -> the cut and surface fill pattern ids of its Material record (-1 when the /// material has no pattern of that kind), for the blocks that decoded exactly once. - public Dictionary MaterialPatterns { get; } = new(); + public Dictionary MaterialPatterns { get; } = new(); + + public (double BaseFeet, int MaterialId)? SiteCutGraphics { get; set; } + public int SiteCutGraphicsCount { get; set; } + public (int Method, int Units)? PropertyBearingFormat { get; set; } + public int PropertyBearingFormatCount { get; set; } /// GStyleElem (class 2050) -> GStyle.m_materialElemId and the style's category; MaterialId is null when the /// block did not decode. A repeated block clears it. @@ -342,7 +348,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Own wall-root (SWall/ArcWall) top-attachment source: every root counts; /// an unreadable root records null. Duplicates clear the value. - public Dictionary WallJoinedToTop { get; } = new(); + public Dictionary WallJoinedToTop { get; } = new(); /// Control joins of each wall's own driver /// (); null when the block is @@ -428,6 +434,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// GeoSite (class 2071) latitude and longitude in radians by element id; the last block wins. internal Dictionary GeoSites { get; } = new(); + internal Dictionary GeoSiteTimeZones { get; } = new(); /// GeoSite (class 2071) m_placeName by element id; the last block wins. internal Dictionary GeoSitePlaceNames { get; } = new(); @@ -452,6 +459,9 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Null when the block did not decode; a repeated block clears it. public Dictionary LevelDatums { get; } = new(); + public Dictionary DatumExtents { get; } = new(); + public Dictionary DatumHeads { get; } = new(); + /// GridAttributes block (class 2109) -> the center-segment category id whose projection /// graphics style inks the grid's center line. Null when the block did not decode; a repeated /// block clears it. @@ -470,7 +480,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Curve line style + length from the full CurveElem schema walk (handles /// detail arcs the GInfoBlob pattern scan can't reach). - public Dictionary CurveGeometry { get; set; } = new(); + public Dictionary CurveGeometry { get; set; } = new(); /// Native parameter stores per element, deserialized from the Element base /// class m_pParamValueSet* containers (schema-driven). diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index cbf14eba..3da461c2 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -307,6 +307,27 @@ public class Element [JsonIgnore] public ViewCropFrame? ViewCrop { get; set; } + internal ViewModelBounds? OrthographicModelBounds { get; set; } + internal ViewSolarStudy? SolarStudy { get; set; } + + internal bool? ViewAnnotationCropActive { get; set; } + + // Annotation crop offsets are in paper feet, relative to the model crop. + internal (double Left, double Right, double Top, double Bottom)? ViewAnnotationCrop { get; set; } + + internal (int ParentId, double[] Head)? SectionCallout { get; set; } + + internal (double Width, double Scale, bool Mirrored)? DetailInsulation { get; set; } + internal Parsing.TfBlockDeserializer.BreakLineProfile? DetailBreak { get; set; } + internal (double X, double Y, double Radius)? DetailCircle { get; set; } + internal (double Width, double Height)? ImagePaperSize { get; set; } + internal int? ImageHolderId { get; set; } + internal (double X, double Y)? RoomLegendOrigin { get; set; } + internal (double Width, double Height)? ColorLegendSwatch { get; set; } + internal (double Width, double Height)? ImageInstanceScale { get; set; } + internal IReadOnlyList<(double X, double Y)>? SitePropertyCurve { get; set; } + internal (double X, double Y)? SitePropertyArcCenter { get; set; } + /// Exact BaseRailing.m_baseRailingSymbolId stored by this occurrence. [JsonIgnore] internal int? SerializedBaseRailingSymbolId { get; set; } @@ -326,6 +347,8 @@ public class Element /// only a unique, non-inplace family with no nested instances is admitted. [JsonIgnore] internal (int SymbolId, int HostId, double[] Transform, FamilyCutLoopData Loop)? OwnSingleFamilyCutout { get; set; } + internal (IReadOnlyList Symbols, double[] Transform)? OwnDoorPlanSymbols { get; set; } + internal RvtIO.Internal.PlanFixtureGraphics? PlacedPlanFixtureGraphics { get; set; } /// Own phase-4 cutout instance IDs in source order, not inferred inverse hosts. [JsonIgnore] @@ -498,6 +521,10 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal double? SerializedMaterialTransparency { get; set; } + /// Whether the material uses the appearance asset in place of its stored shading colour. + [JsonIgnore] + internal bool? SerializedMaterialUsesRenderAppearance { get; set; } + /// The lowest and highest elevation (feet) at which a Grid is shown in plan views /// (the V envelope of its DatumPlane surface). [JsonIgnore] @@ -639,6 +666,9 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal bool? SerializedWallJoinedToTop { get; set; } + /// Targets from this wall's verified native top-attachment geometry steps. + internal int[]? SerializedWallTopAttachmentTargets { get; set; } + /// The export id of the element: its episode GUID with the last /// 32 bits XORed with the original element id (Global/History and Global/ElemTable); /// null when either table is not read exactly. diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index 4bf5036f..77d8f666 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -38,6 +38,8 @@ internal bool HasCurvedFace(IReadOnlyCollection? nodes = null) => MeshNodes /// List of edges with 3D coordinates. public List? Edges { get; set; } + internal List? ViewFacingLines { get; set; } + /// Unique vertices [x, y, z] in feet, deduplicated across all faces. public List? Vertices { get; set; } @@ -116,9 +118,14 @@ public class GeoInstance /// A planar face defined by origin + two direction vectors. public class GeoFace { + // A saved direction filter excludes this face along the vertical axis of its current frame. + internal bool ExcludedFromTopPlan { get; set; } + /// GFace.m_renderStyleId: the material element id of the face (internal; not serialized). [System.Text.Json.Serialization.JsonIgnore] internal int? RenderStyleId { get; set; } + internal RvtIO.Internal.ModelFacePattern? ModelPattern { get; set; } + internal IReadOnlyList? SurfaceRegions { get; set; } /// Plane origin [x, y, z] in feet. public double[] Origin { get; set; } = new double[3]; @@ -172,6 +179,9 @@ public class GeoFace /// True for a tessellated patch of a non-planar surface. internal bool CurvedSurface { get; set; } + /// Triangle supplied directly by a serialized polygon mesh. + internal bool PolygonMesh { get; set; } + /// The face lies on a plane surface of the file (GRepFace.PlaneSurface); kept through placing and copying of /// the geometry. internal bool PlaneSurface { get; set; } diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index c6599fe8..c6a913dc 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -71,12 +71,20 @@ public class RevitFileInfo /// FamilySymbol id -> the fixed texts of a title block family symbol in symbol feet, for the /// symbols whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary>? TitleBlockTexts { get; set; } + internal IReadOnlyDictionary>? TitleBlockTexts { get; set; } - /// FamilySymbol id -> the labels of a title block family symbol in symbol feet, for the symbols + /// FamilySymbol id -> annotation labels in symbol feet, for the symbols /// whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary>? TitleBlockLabels { get; set; } + internal IReadOnlyDictionary>? TitleBlockLabels { get; set; } + internal IReadOnlyDictionary? TitleBlockCapHeightsFeet { get; set; } + internal IReadOnlySet? OpaqueSymbolLabelStyles { get; set; } + internal IReadOnlySet? RegularArialSymbolLabelStyles { get; set; } + internal IReadOnlyList? PlanElevationMarks { get; set; } + internal IReadOnlyDictionary? SectionMarkerSymbols { get; set; } + + internal sealed record PlanElevationMark(int Id, double X, double Y, int BodyId, double ArrowHalfAngle, bool Filled, + int ArrowId, int ViewId, int ArrowSymbolId, double CoarserScale); /// ScheduleInstance element id -> the DBViewSchedule it shows and its top-left origin in sheet /// feet, for the instances whose block decoded exactly once. @@ -86,7 +94,10 @@ public class RevitFileInfo /// DBViewSchedule id -> its table definition (visible columns, category, show flags, grid and /// outline line styles, title-area rows and body sections), for the views whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, int GridStyleId, int OutlineStyleId, double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, double FixedHeightFt)>? ScheduleTables { get; set; } + internal IReadOnlyDictionary? ScheduleTables { get; set; } + internal IReadOnlyDictionary>>? EvaluatedScheduleRows { get; set; } + + internal readonly record struct ScheduleCellValue(string Text, bool? Boolean = null); /// Sheet element id -> the revision ids explicitly present on it, for the sheets whose block /// decoded exactly once. @@ -98,10 +109,27 @@ public class RevitFileInfo [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? FrontCut)>? SectionViews { get; set; } + /// Project site graphics from TrueNorth: the base elevation in feet and cut material element id. + [System.Text.Json.Serialization.JsonIgnore] + internal (double BaseFeet, int MaterialId)? SiteCutGraphics { get; set; } + internal (int Method, int Units)? PropertyBearingFormat { get; set; } + internal IReadOnlyDictionary>? SiteContours { get; set; } + internal sealed record SiteContourLabel(int ElementId, int SurfaceId, double[] Position, double[] Direction, + double TextHeightFeet); + internal IReadOnlyDictionary>? SiteContourLabels { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + internal IReadOnlyDictionary? DatumExtents { get; set; } + internal IReadOnlyDictionary? SectionTraceOrigins { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + internal IReadOnlyDictionary? DatumHeads { get; set; } + /// Material element id -> its cut and surface fill pattern element ids (-1 when the material /// has no pattern of that kind), for the materials whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary? MaterialPatterns { get; set; } + internal IReadOnlyDictionary? MaterialPatterns { get; set; } + internal IReadOnlyDictionary? MaterialCutPatternColors { get; set; } /// Fill pattern element id -> its name and line families (angle, origin, shift/offset, dash list /// in the pattern's own feet), for the patterns whose block decoded exactly once. @@ -119,6 +147,75 @@ public class RevitFileInfo /// exactly once. [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? GridCenterCategories { get; set; } + internal IReadOnlyDictionary>? ViewRoomColors { get; set; } + internal IReadOnlyDictionary>? PlanDimensions { get; set; } + + internal sealed record PlanDimension(int StyleId, double[] Origin, double[] Direction, + IReadOnlyList References, IReadOnlyList Values); + internal IReadOnlyDictionary? PlanDimensionStyles { get; set; } + + internal sealed record PlanDimensionStyle(double TextHeightFeet, int LineCategory, int TickCategory, + double LineExtensionFeet, double WitnessExtensionFeet, double WitnessGapFeet, double TextGapFeet, + double TickSizeFeet); + + internal IReadOnlyDictionary>? CircularAnnotations { get; set; } + internal sealed record CircularAnnotation(double[] Transform, CircularAnnotationStyle Style); + internal sealed record CircularAnnotationStyle( + Parsing.TfBlockDeserializer.FamilyAnnotationArc Outline, int FillColor, int BorderColor, int BorderPen, + Parsing.TfBlockDeserializer.TitleBlockText Text, string Value, double FontPoints, int TextColor, bool Bold); + + internal IReadOnlyDictionary? ViewportTitles { get; set; } + internal IReadOnlyDictionary? ViewportTitleStyles { get; set; } + internal sealed record ViewportTitle(int SymbolId, bool ShowLabel, bool ShowExtensionLine, string? CustomScale); + internal sealed record ViewportTitleStyle( + IReadOnlyList<(Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints, bool Wrap)> Labels, + IReadOnlyList Lines, + IReadOnlyList Arcs); + + internal IReadOnlyDictionary>? PlanOpeningTags { get; set; } + internal IReadOnlyDictionary? PlanOpeningTagStyles { get; set; } + internal sealed record PlanOpeningTag(int ElementId, int SymbolId, double X, double Y); + internal IReadOnlyDictionary>? SitePlantingTags { get; set; } + internal IReadOnlyDictionary>? SitePropertyTags { get; set; } + internal IReadOnlyDictionary>? + SitePropertyTagStyles { get; set; } + internal IReadOnlyDictionary>? PlanOutlineAnnotations { get; set; } + internal sealed record PlanOutlineAnnotation(double[] Transform, + IReadOnlyList Lines, + IReadOnlyList Arcs); + internal sealed record SitePlantingTag(int ElementId, int SymbolId, double X, double Y, + (double X, double Y) Elbow, (double X, double Y) End); + internal sealed record PlanOpeningTagStyle( + Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints, + IReadOnlyList Lines, + IReadOnlyList Arcs); + + internal IReadOnlyDictionary>? PlanRoomTags { get; set; } + internal IReadOnlyDictionary? PlanRoomTagStyles { get; set; } + internal sealed record PlanRoomTag(int RoomId, int SymbolId, double X, double Y, + (double X, double Y)? LeaderAnchor, (double X, double Y)? LeaderEnd); + internal sealed record PlanRoomTagStyle( + IReadOnlyList<(Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints)> Labels, + IReadOnlyList Lines); + + internal IReadOnlyDictionary>? PlanNotes { get; set; } + internal IReadOnlyDictionary>? PlanStairPaths { get; set; } + internal sealed record PlanStairPath(int Id, int HostId, double ArrowSize, double ArrowAngle, + string? DownText, double CapHeight, double TextX, double TextY); + internal IReadOnlyDictionary>? ViewHiddenElements { get; set; } + internal IReadOnlyDictionary>? ViewHiddenCategories { get; set; } + internal IReadOnlySet? OpaquePlanViews { get; set; } + internal IReadOnlyDictionary? ViewSkyGradients { get; set; } + internal IReadOnlyDictionary? ViewGroundShadows { get; set; } + internal IReadOnlyDictionary? ViewStillSunDates { get; set; } + internal IReadOnlyDictionary? ViewAmbientLight { get; set; } + internal IReadOnlyDictionary? ViewAmbientFractions { get; set; } + internal IReadOnlySet? UnshadedHiddenLineViews { get; set; } + internal IReadOnlySet? OpaqueViewsWithSurfacePatterns { get; set; } + internal sealed record PlanNote(string Text, double FontPoints, double X, double Y, + double WidthFeet, double HeightFeet, bool Wrap, bool HasBorder, bool Opaque, double PaddingFeet, + int CategoryId, bool ArcLeaders, IReadOnlyList Leaders, + double ArrowSizeFeet, double ArrowAngle, int ElementId); /// CategoryElem id -> its name, for the category elements whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? CategoryNames { get; set; } @@ -192,6 +289,8 @@ public class RevitFileInfo /// See . public double? SiteLongitudeRadians { get; set; } + internal double? SiteTimeZoneHours { get; set; } + /// Elevation (feet) of the project base point in shared coordinates; 0 when unknown. public double SiteElevationFeet { get; set; } diff --git a/src/RvtIO/Model/ViewCropFrame.cs b/src/RvtIO/Model/ViewCropFrame.cs index ef3e8051..c1ffe007 100644 --- a/src/RvtIO/Model/ViewCropFrame.cs +++ b/src/RvtIO/Model/ViewCropFrame.cs @@ -27,3 +27,9 @@ public sealed record ViewCropFrame( double X1, double Y1, bool Active); + +internal sealed record ViewModelBounds(double[] Origin, double[][] Axes, double[] Offsets, bool[] Active); + +internal sealed record ViewSolarStudy(double[] Outline, int SizePercent, int GroundLevelId, int AnnotationId, + uint Start, uint End, int Interval, double ActiveFrame, int ShadowIntensity = 0, + bool ShowSurfacePatterns = false, bool ShowEdges = false, int? SunlightIntensity = null); diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index c96b67f7..c1d5459d 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -19,8 +19,13 @@ internal static void ApplyPendingGReps(ParsingState state, List pen { if (pending.Count == 0) return; var decoded = new Internal.GRepData?[pending.Count]; + var planFixtures = new PlanFixtureGraphics?[pending.Count]; Parallel.For(0, decoded.Length, new ParallelOptions(), index => - decoded[index] = GRepParserV2.Parse(pending[index].Chunk, pending[index].Start, pending[index].Size)); + { + var job = pending[index]; + decoded[index] = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, + collectPlanFixtures: job.IsFamilyCut ? null : graphics => planFixtures[index] = graphics); + }); for (int index = 0; index < decoded.Length; index++) { var job = pending[index]; @@ -30,7 +35,12 @@ internal static void ApplyPendingGReps(ParsingState state, List pen && decoded[index] is { } familyCut && IsAuthoredFamilyComplexCutter(familyCut)) state.FamilyCutGreps[job.Eid] = familyCut; } - else ApplyGRepBlock(state, job.Eid, decoded[index]); + else + { + if (planFixtures[index] is { } graphics) + state.PlanFixtureGraphicsBySymbol.TryAdd(job.Eid, graphics); + ApplyGRepBlock(state, job.Eid, decoded[index]); + } decoded[index] = null; } } diff --git a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs index 90263d35..00d34aa6 100644 --- a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs +++ b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs @@ -11,6 +11,7 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, foreach (var element in elements) { element.OwnSingleFamilyCutout = null; + element.OwnDoorPlanSymbols = null; element.OwnWallCutoutInstanceIds = null; element.OwnWallCutoutSteps = null; element.OwnWallAxisLine = null; @@ -43,8 +44,13 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, HostId: > 0, InsertOrientation: 0 } source } || source.HostId != element.SerializedHostId || source.SymbolId != symbolId || !IsUniqueRoot(symbolId, 1829) - || !counts.TryGetValue(symbolId, out int symbolCount) || symbolCount != 1 - || !state.OwnFamilyCutSymbols.TryGetValue((uint)symbolId, out var computed) + || !counts.TryGetValue(symbolId, out int symbolCount) || symbolCount != 1) continue; + + if (element.CategoryId == (int)RvtIO.BuiltIns.BuiltInCategory.OST_Doors + && state.GrepBlocks.GetValueOrDefault((uint)symbolId)?.DoorPlanSymbols is { Count: > 0 } planSymbols) + element.OwnDoorPlanSymbols = (planSymbols, source.Transform); + + if (!state.OwnFamilyCutSymbols.TryGetValue((uint)symbolId, out var computed) || computed is not { BlockCount: 1, Symbol: { Active: true }, Loops.Count: 1 } || !state.FamilyInstanceSymbolIds.TryGetValue((uint)element.Id, out var type) || type is not { BlockCount: 1, TypeId: > 0 } || !IsUniqueRoot(type.TypeId.Value, 1829) diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs b/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs new file mode 100644 index 00000000..e952b423 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs @@ -0,0 +1,83 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static void ReadPlanDimensions(RevitFileInfo info, ParsingState state) + { + var byView = new Dictionary>(); + var styles = new Dictionary(); + foreach (var (id, saved) in state.NativeParams) + { + if (saved is not { DimensionLine: { } line, DimensionReferences: { Count: >= 2 } references, + DimensionValues: { } values } + || saved.Fields.GetValueOrDefault("m_id") != (int)id + || saved.Fields.GetValueOrDefault("m_ownerDBViewId") is not > 0 + || saved.Fields.GetValueOrDefault("m_styleSymbolId") is not > 0 + || saved.Fields.GetValueOrDefault("160:m_flags") != 12 + || saved.Fields.GetValueOrDefault("160:m_useEqualityFormula") != 0 + || saved.Fields.GetValueOrDefault("160:m_showLabelGP") != 0 + || saved.Fields.GetValueOrDefault("159:m_multiReferenceAnnotationId") > 0 + || saved.CellClasses is { Count: > 0 } + || values.Count != references.Count - 1 || values.Any(value => !(value > 0 && double.IsFinite(value))) + || !line.Origin.All(value => Math.Abs(value) < 1_000_000) || !line.Direction.All(double.IsFinite) + || references.Any(point => point.Any(value => !(Math.Abs(value) < 1_000_000)))) continue; + int view = saved.Fields["m_ownerDBViewId"], style = saved.Fields["m_styleSymbolId"]; + if (!styles.ContainsKey(style)) + { + var decoded = ReadStyle(style); + if (decoded == null) continue; + styles.Add(style, decoded); + } + + if (!byView.TryGetValue(view, out var dimensions)) byView.Add(view, dimensions = new()); + dimensions.Add(new(style, line.Origin, line.Direction, references, values)); + } + info.PlanDimensions = byView; + info.PlanDimensionStyles = styles; + + RevitFileInfo.PlanDimensionStyle? ReadStyle(int id) + { + if (!state.NativeParams.TryGetValue((uint)id, out var style)) return null; + var fields = style.Fields; + int fontId = fields.GetValueOrDefault("625:m_fontId"); + int tickId = fields.GetValueOrDefault("174:m_arrowHeadStyleId"); + int category = fields.GetValueOrDefault("625:m_categoryId"); + int tickCategory = fields.GetValueOrDefault("174:m_tickCategoryId"); + // shortcut: continuous dimensions with one diagonal tick and the project length format. + if (fields.GetValueOrDefault("174:m_dimensionStyleType", -1) != 0 + || fields.GetValueOrDefault("174:m_linearDimType") != 1 + || fields.GetValueOrDefault("174:m_textAlignment") != 1 + || fields.GetValueOrDefault("174:m_textLoc", -1) != 0 + || fields.GetValueOrDefault("174:m_alternateUnits", -1) != 0 + || fields.GetValueOrDefault("174:m_dimWitnCntrlExtBelow", -1) != 0 + || fields.GetValueOrDefault("174:linearFormatUsesDefault") != 1 + || !string.IsNullOrEmpty(style.StringFields.GetValueOrDefault("174:m_prefix")) + || !string.IsNullOrEmpty(style.StringFields.GetValueOrDefault("174:m_suffix")) + || category <= 0 || tickCategory <= 0 || fontId <= 0 || tickId <= 0 + || fields.GetValueOrDefault("174:m_interiorTickMarkStyleId") != tickId + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || !state.NativeParams.TryGetValue((uint)tickId, out var tick) + || tick.Fields.GetValueOrDefault("2295:m_tickType", -1) != 0) return null; + double height = font.DoubleFields.GetValueOrDefault("1923:m_size"); + double size = PlanAnnotationDouble(tick, BuiltInParameter.ARROW_SIZE); + double extension = PlanAnnotationDouble(style, BuiltInParameter.DIM_LINE_EXTENSION); + double witness = PlanAnnotationDouble(style, BuiltInParameter.WITNS_LINE_EXTENSION); + double gap = PlanAnnotationDouble(style, BuiltInParameter.WITNS_LINE_GAP_TO_ELT); + double textGap = PlanAnnotationDouble(style, BuiltInParameter.TEXT_DIST_TO_LINE); + return height is > 0 and < 1 && size is > 0 and < 1 && extension is >= 0 and < 1 + && witness is >= 0 and < 1 && gap is >= 0 and < 1 && textGap is >= 0 and < 1 + ? new(height, category, tickCategory, extension, witness, gap, textGap, size) : null; + } + } + + private static double PlanAnnotationDouble(TfBlockDeserializer.NativeParams item, BuiltInParameter parameter) + { + foreach (var (id, value) in item.Doubles) + if (id == (int)parameter) return value; + return double.NaN; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs b/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs new file mode 100644 index 00000000..0dd64ea7 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs @@ -0,0 +1,51 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static List ReadPlanElevationMarks(ParsingState state) + { + var result = new List(); + foreach (var (markerId, marker) in state.NativeParams) + { + if (state.ElemClassIdx.GetValueOrDefault(markerId) != 2247 + || !marker.DoubleFields.TryGetValue("2247:m_pos@0", out double x) || !double.IsFinite(x) + || !marker.DoubleFields.TryGetValue("2247:m_pos@1", out double y) || !double.IsFinite(y) + || !state.NativeParams.TryGetValue((uint)marker.Fields.GetValueOrDefault("2247:m_symbolId"), out var type) + || !state.NativeParams.TryGetValue((uint)type.Fields.GetValueOrDefault("1020:m_elevatnAttrId"), out var style) + || style.Fields.GetValueOrDefault("2251:m_shape") != 1 + || style.DoubleFields.GetValueOrDefault("2251:m_ahAngleDouble") is not (> 0 and < Math.PI / 2 and var angle) + || style.Fields.GetValueOrDefault("2251:m_elevationSymbolId") is not (> 0 and var bodyId) + || !state.NativeParams.TryGetValue((uint)bodyId, out var body)) + continue; + + // shortcut: one target view per marker, until the shared body label for multiple targets is decoded. + int arrowIndex = -1; + for (int index = 0; index < 4; index++) + { + if (marker.Fields.GetValueOrDefault($"2247:m_arrowIds@{index}") <= 0) continue; + if (arrowIndex >= 0) + { + arrowIndex = -1; + break; + } + arrowIndex = index; + } + if (arrowIndex < 0 + || marker.Fields.GetValueOrDefault($"2247:m_arrowIds@{arrowIndex}") is not (> 0 and var arrowId) + || !state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + || arrow.Fields.GetValueOrDefault("2248:m_parentId") != (int)markerId + || arrow.Fields.GetValueOrDefault("621:m_dbViewId") is not (> 0 and var viewId) + || !arrow.DoubleFields.TryGetValue("2249:m_coarserScale", out double coarserScale) + || coarserScale is not (>= 0 and <= 1) + || !style.Fields.TryGetValue($"2251:m_orderedSubIndices@{arrowIndex}", out int child) + || body.Fields.GetValueOrDefault($"1829:m_subInstData@{child}") is not (> 0 and var symbolId)) + continue; + result.Add(new((int)markerId, x, y, bodyId, angle, style.Fields.GetValueOrDefault("2251:m_ahFilled") == 1, + arrowId, viewId, symbolId, coarserScale)); + } + return result; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs b/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs new file mode 100644 index 00000000..2c808e26 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs @@ -0,0 +1,56 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static Dictionary> ReadPlanNotes(ParsingState state) + { + var byView = new Dictionary>(); + foreach (var (id, note) in state.NativeParams) + { + var fields = note.Fields; + var numbers = note.DoubleFields; + // shortcut: the supported left-aligned horizontal note layout. + if (note.PlanNoteText is not { Text.Length: > 0, FontSizePoints: > 0 and <= 200 } text + || fields.GetValueOrDefault("m_id") != (int)id + || fields.GetValueOrDefault("m_ownerDBViewId") is not > 0 + || fields.GetValueOrDefault("3928:m_flags") != 8768 + || numbers.GetValueOrDefault("3928:m_baseVec@0") != 1 || numbers.GetValueOrDefault("3928:m_baseVec@1") != 0 + || numbers.GetValueOrDefault("3928:m_upVec@0") != 0 || numbers.GetValueOrDefault("3928:m_upVec@1") != 1 + || fields.GetValueOrDefault("3928:m_attrId") is not > 0 + || !state.NativeParams.TryGetValue((uint)fields["3928:m_attrId"], out var style)) continue; + double x = numbers.GetValueOrDefault("3928:m_orig@0", double.NaN); + double y = numbers.GetValueOrDefault("3928:m_orig@1", double.NaN); + double width = numbers.GetValueOrDefault("3928:m_lineWidth"); + double height = numbers.GetValueOrDefault("3928:m_height"); + double padding = style.DoubleFields.GetValueOrDefault("3931:m_leaderOffsetSheet", double.NaN); + int view = fields["m_ownerDBViewId"], category = style.Fields.GetValueOrDefault("625:m_categoryId"); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000) || !(width is > 0 and < 20) + || !(height is > 0 and < 20) || !(padding is >= 0 and < 1) || category <= 0) continue; + double arrowSize = 0, arrowAngle = 0; + var arrowId = style.ElementIds.Find(entry => entry.ParamId == (int)BuiltInParameter.LEADER_ARROWHEAD).Value; + if (arrowId > 0 && state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + && arrow.Fields.GetValueOrDefault("2295:m_tickType") == 8) + { + double size = PlanAnnotationDouble(arrow, BuiltInParameter.ARROW_SIZE); + double angle = PlanAnnotationDouble(arrow, BuiltInParameter.LEADER_ARROW_WIDTH); + if (size is > 0 and < 1 && angle is > 0 and < Math.PI) + { + arrowSize = size; + arrowAngle = angle; + } + } + if (!byView.TryGetValue(view, out var notes)) byView.Add(view, notes = new()); + notes.Add(new(text.Text, text.FontSizePoints!.Value, x, y, width, height, + fields.GetValueOrDefault("3928:m_bNoWrapping") == 0, + style.Fields.GetValueOrDefault("3931:m_textBoxVisibility") == 1, + style.Fields.GetValueOrDefault("625:m_background", -1) == 0, padding, category, + fields.GetValueOrDefault("3971:m_bArcLeaders") == 1, note.PlanNoteLeaders ?? [], + arrowSize, arrowAngle, (int)id)); + } + return byView; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs b/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs new file mode 100644 index 00000000..1b9c13f6 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs @@ -0,0 +1,66 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static Dictionary> ReadPlanStairPaths(ParsingState state) + { + var byView = new Dictionary>(); + foreach (var (id, path) in state.NativeParams) + { + var fields = path.Fields; + // shortcut: automatic direction with an open arrow at the riser and no start extension. + if (fields.GetValueOrDefault("3702:m_stairsLinkElementId") is not (> 0 and var host) + || id > int.MaxValue || fields.GetValueOrDefault("m_id") != (int)id + || fields.GetValueOrDefault("m_ownerDBViewId") is not (> 0 and var view) + || path.DoubleFields.GetValueOrDefault("3702:m_stairsPathOffset", double.NaN) != 0 + || fields.GetValueOrDefault("3702:m_typeId") is not (> 0 and var typeId) + || !state.NativeParams.TryGetValue((uint)typeId, out var type) + || type.Fields.GetValueOrDefault("3703:m_stairsPathDirection") != 1 + || type.Fields.GetValueOrDefault("3703:m_startFromRiser") != 1 + || type.Fields.GetValueOrDefault("3703:m_endAtRiser") != 1 + || type.Fields.GetValueOrDefault("3703:m_startSymbolTypeId") != -1 + || type.Fields.GetValueOrDefault("3703:m_fullStepArrow", -1) != 0 + || type.DoubleFields.GetValueOrDefault("3703:m_startExtension", double.NaN) != 0 + || type.Fields.GetValueOrDefault("3703:m_arrowheadTypeId") is not (> 0 and var arrowId) + || !state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + || arrow.Fields.GetValueOrDefault("2295:m_tickType") != 8 + || arrow.Fields.GetValueOrDefault("2295:m_arrowClosed", -1) != 0 + || arrow.Fields.GetValueOrDefault("2295:m_arrowFilled", -1) != 0) + continue; + + double size = PlanAnnotationDouble(arrow, BuiltInParameter.ARROW_SIZE); + double angle = PlanAnnotationDouble(arrow, BuiltInParameter.LEADER_ARROW_WIDTH); + if (!(size is > 0 and < 1 && angle is > 0 and < Math.PI)) continue; + string? text = null; + double cap = 0, textX = 0, textY = 0; + if (fields.GetValueOrDefault("3702:m_showDownText") == 1 + && fields.GetValueOrDefault("3702:m_textOrientation", -1) == 0 + && path.StringFields.GetValueOrDefault("3702:m_downText") is { Length: > 0 } label + && type.Fields.GetValueOrDefault("3703:m_textTypeId") is > 0 and var textId + && state.NativeParams.TryGetValue((uint)textId, out var textType) + && textType.Fields.GetValueOrDefault("625:m_fontId") is > 0 and var fontId + && textType.Fields.GetValueOrDefault("625:m_bBold", -1) == 0 + && textType.Fields.GetValueOrDefault("625:m_bItalic", -1) == 0 + && textType.Fields.GetValueOrDefault("625:m_bUnderline") == 0 + && state.NativeParams.TryGetValue((uint)fontId, out var font) + && string.Equals(font.StringFields.GetValueOrDefault("1923:m_name"), "Arial", StringComparison.OrdinalIgnoreCase) + && font.DoubleFields.GetValueOrDefault("1923:m_size") is > 0 and < 1 and var height) + { + textX = path.DoubleFields.GetValueOrDefault("3702:m_downTextOffset@0", double.NaN); + textY = path.DoubleFields.GetValueOrDefault("3702:m_downTextOffset@1", double.NaN); + if (double.IsFinite(textX) && double.IsFinite(textY)) + { + text = label; + cap = height; + } + } + if (!byView.TryGetValue(view, out var paths)) byView.Add(view, paths = []); + paths.Add(new((int)id, host, size, angle, text, cap, textX, textY)); + } + return byView; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs b/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs new file mode 100644 index 00000000..5508a9fb --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs @@ -0,0 +1,31 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static Dictionary> BuildViewRoomColors(RevitFileInfo info, + ParsingState state) + { + var result = new Dictionary>(); + if (info.FillPatterns == null) return result; + foreach (var (viewId, view) in state.NativeParams) + { + if (view.Fields.GetValueOrDefault("693:m_bBackground") != 1 + || !view.Fields.TryGetValue("693:m_roomColorScheme", out int schemeId) || schemeId <= 0 + || !state.NativeParams.TryGetValue((uint)schemeId, out var scheme) + || scheme.RoomColors is not { Count: > 0 } entries + || scheme.Fields.GetValueOrDefault("690:m_categoryId") != (int)BuiltInCategory.OST_Rooms + || scheme.Fields.GetValueOrDefault("690:m_paramId") != (int)BuiltInParameter.ROOM_NAME + || scheme.Fields.GetValueOrDefault("690:m_bByRange", -1) != 0) continue; + var colors = new Dictionary(StringComparer.Ordinal); + foreach (var entry in entries) + if (info.FillPatterns.TryGetValue(entry.PatternId, out var pattern) && pattern.Grids.Count == 0) + colors.TryAdd(entry.Name, entry.Color); + if (colors.Count > 0) result.Add((int)viewId, colors); + } + return result; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs b/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs new file mode 100644 index 00000000..eee65a07 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static TfBlockDeserializer.ScheduleTableDef ResolveRevisionTextTypes(ParsingState state, + TfBlockDeserializer.ScheduleTableDef table) + { + if (table.CategoryId != (int)BuiltInCategory.OST_Revisions + || CapHeight(table.TextTypeIds.Header) is not double header + || CapHeight(table.TextTypeIds.Body) is not double body) return table; + return table with { RevisionCapHeightsFt = (header, body) }; + + double? CapHeight(int id) + { + if (id <= 0 || !state.NativeParams.TryGetValue((uint)id, out var type) + || type.Fields.GetValueOrDefault("625:m_bBold") != 0 + || type.Fields.GetValueOrDefault("625:m_bItalic") != 0 + || type.Fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || !string.Equals(font.StringFields.GetValueOrDefault("1923:m_name"), "Arial", StringComparison.OrdinalIgnoreCase)) + return null; + double height = font.DoubleFields.GetValueOrDefault("1923:m_size"); + return height is > 0 and < 1 ? height : null; + } + } + + internal static Dictionary>> EvaluateScheduleRows(RevitFileInfo info, ParsingState state) + { + var result = new Dictionary>>(); + foreach (var (id, entry) in state.ScheduleTables) + { + if (entry is not { BlockCount: 1, Table: { } table } + || BuildScheduleRows(table, info.Elements, state) is not { } rows) continue; + result.Add((int)id, rows); + } + return result; + } + + internal static List>? BuildScheduleRows(TfBlockDeserializer.ScheduleTableDef table, + IEnumerable elements, ParsingState state) + { + // shortcut: itemized instance rows with flat sorting and integer filters, until other schedule expression types are evaluated. + if (table.RowBindings is not { Itemized: true, Unsupported: false } binding + || table.BodySections is not [{ } section] || binding.FieldIds.Count != binding.FieldObjects.Count) + return null; + var fields = new Dictionary(); + for (int i = 0; i < binding.FieldIds.Count; i++) + { + if (!binding.Fields.TryGetValue(binding.FieldObjects[i], out var field) || field.Source != 0 + || field.Parameter <= 0 || !state.NativeParams.TryGetValue((uint)field.Parameter, out var definition) + || !definition.Fields.TryGetValue("2870:m_pParamDef.class", out int kind) + || kind is not (606 or 2756 or 2866) + || !fields.TryAdd(binding.FieldIds[i], (field.Parameter, field.Hidden, kind))) return null; + } + + var columns = binding.FieldIds.Select(id => fields[id]).Where(f => !f.Hidden).ToArray(); + if (columns.Length != table.Columns.Count) return null; + var filters = new List<(int Parameter, int Type, int Value)>(); + foreach (int index in binding.FilterObjects) + { + if (!binding.Filters.TryGetValue(index, out var filter) || filter is not { Type: 2 or 3, Storage: 1 } + || !fields.TryGetValue(filter.Field, out var field) || field.Kind is not (2756 or 2866)) return null; + filters.Add((field.Parameter, filter.Type, filter.Value)); + } + + var sorts = new List<(int Parameter, int Kind, int Order)>(); + foreach (int index in binding.SortObjects) + { + if (!binding.Sorts.TryGetValue(index, out var sort) || sort is not { GroupFlags: 0, Order: 0 or 1 } + || !fields.TryGetValue(sort.Field, out var field)) return null; + sorts.Add((field.Parameter, field.Kind, sort.Order)); + } + + var items = new List<(int Id, Dictionary Values)>(); + foreach (var element in elements) + { + if (element.CategoryId != table.CategoryId || element.RootClassName != "FamilyInstance" + || !state.NativeParams.TryGetValue((uint)element.Id, out var native) || !native.TailWalkComplete) continue; + var values = new Dictionary(); + foreach (var parameter in native.NamedParams) + values.TryAdd(parameter.ParamId, parameter); + if (!filters.All(f => values.TryGetValue(f.Parameter, out var value) + && (f.Type == 2 ? value.Int == f.Value : value.Int != f.Value))) continue; + if (columns.Any(c => !values.ContainsKey(c.Parameter)) || sorts.Any(s => !values.ContainsKey(s.Parameter))) continue; + items.Add((element.Id, values)); + } + + int spacer = binding.InitialSpacer ? 1 : 0; + if (items.Count == 0 || items.Count + spacer != section.BodyRows) return null; + items.Sort((left, right) => + { + foreach (var sort in sorts) + { + var a = left.Values[sort.Parameter]; + var b = right.Values[sort.Parameter]; + int order = sort.Kind == 606 ? string.CompareOrdinal(a.Str, b.Str) : a.Int.CompareTo(b.Int); + if (order != 0) return sort.Order == 0 ? order : -order; + } + return left.Id.CompareTo(right.Id); + }); + + var rows = new List>(); + if (spacer > 0) rows.Add(Enumerable.Repeat(new RevitFileInfo.ScheduleCellValue(""), columns.Length).ToList()); + foreach (var item in items) + rows.Add(columns.Select(column => + { + var value = item.Values[column.Parameter]; + return column.Kind switch + { + 606 => new RevitFileInfo.ScheduleCellValue(value.Str ?? ""), + 2866 => new RevitFileInfo.ScheduleCellValue("", value.Int != 0), + _ => new RevitFileInfo.ScheduleCellValue(value.Int.ToString(CultureInfo.InvariantCulture)), + }; + }).ToList()); + return rows; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs b/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs new file mode 100644 index 00000000..98b4b43e --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs @@ -0,0 +1,36 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + internal static Dictionary> BuildSiteContourLabels(ParsingState state) + { + var labels = new Dictionary>(); + foreach (var (id, element) in state.NativeParams) + { + if (element.SiteContourLabels is not { } data + || element.Fields.GetValueOrDefault("m_id") != id + || element.Fields.GetValueOrDefault("m_ownerDBViewId") is not (> 0 and var view) + || !state.NativeParams.TryGetValue((uint)data.SurfaceId, out var surface) || surface.SiteContours == null + || element.Fields.GetValueOrDefault("m_attrId") is not (> 0 and var styleId) + || !state.NativeParams.TryGetValue((uint)styleId, out var style)) continue; + + // shortcut: plain labels using the internal elevation and project length format. + var fields = style.Fields; + if (fields.GetValueOrDefault("836:m_baseElevation", -1) != 0 + || fields.GetValueOrDefault("84:m_bUseDefault") != 1 + || fields.GetValueOrDefault("625:m_bBold") != 0 || fields.GetValueOrDefault("625:m_bItalic") != 0 + || fields.GetValueOrDefault("625:m_bUnderline") != 0 + || fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || font.DoubleFields.GetValueOrDefault("1923:m_size") is not (> 0 and < 1 and var size)) continue; + + if (!labels.TryGetValue(view, out var group)) labels.Add(view, group = []); + for (int i = 0; i < data.Positions.Length; i++) + group.Add(new((int)id, data.SurfaceId, data.Positions[i], data.Directions[i], size)); + } + return labels; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 020f11ba..ebed2593 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -215,13 +215,39 @@ double[] Corner(int x, int y, int z) => TransformGeometryPoint( return geometry; } - private static double[] TransformGeometryPoint(double[] point, double[] t) => + internal static double[] TransformGeometryPoint(double[] point, double[] t) => [ t[9] + point[0] * t[0] + point[1] * t[1] + point[2] * t[2], t[10] + point[0] * t[3] + point[1] * t[4] + point[2] * t[5], t[11] + point[0] * t[6] + point[1] * t[7] + point[2] * t[8], ]; + internal static void ApplyPlanFixtureGraphics(IReadOnlyList elements, ParsingState state) + { + foreach (var element in elements) + { + bool siteEquipment = element.CategoryId is (int)BuiltIns.BuiltInCategory.OST_ElectricalEquipment or (int)BuiltIns.BuiltInCategory.OST_Site; + if (!siteEquipment && element.CategoryId is not ((int)BuiltIns.BuiltInCategory.OST_PlumbingFixtures or (int)BuiltIns.BuiltInCategory.OST_Furniture) + || element.ValidatedOriginalFamilySymbolId is not int symbolId + || state.GrepBlocks.GetValueOrDefault((uint)element.Id)?.Instances is not [var placement] + || placement.SymbolElemId != symbolId + || !IsRigidPlacement(placement.Transform) || Math.Abs(placement.Transform[8] - 1) > 1e-9 + || !state.PlanFixtureGraphicsBySymbol.TryGetValue((uint)symbolId, out var source) + || element.Geometry is { Faces.Count: > 0 } && source.MediumProjection == null && (!siteEquipment || source.CoarseProjection == null)) + continue; + + double[] Place(double[] point) => TransformGeometryPoint(point, placement.Transform); + element.PlacedPlanFixtureGraphics = new( + source.Lines.Select(line => line with { Start = Place(line.Start), End = Place(line.End) }).ToList(), + source.Masks.Select(ring => ring.Select(Place).ToList()).ToList(), + PlaceProjection(source.MediumProjection), siteEquipment ? PlaceProjection(source.CoarseProjection) : null); + + PlanFixtureProjection? PlaceProjection(PlanFixtureProjection? projection) => projection == null ? null : new( + projection.Lines.Select(line => line with { Start = Place(line.Start), End = Place(line.End) }).ToList(), + projection.Masks.Select(ring => ring.Select(Place).ToList()).ToList()); + } + } + /// Set to true when this symbol or a nested one is replaced by its tight box. /// Set to true when a symbol nested in this one, at any depth, placed nothing. internal static GeometryData? BuildPlacedSymbolGeometry( @@ -402,7 +428,7 @@ internal static bool IsRigidPlacement(double[] t) /// Apply a GInstance placement (rows: basisX, basisY, basisZ, origin - 12 doubles) to a /// symbol's geometry, producing world-space faces for the instance. /// - private static GeometryData? TransformGeometry(GeometryData sym, double[] t) + internal static GeometryData? TransformGeometry(GeometryData sym, double[] t) { if (t.Length < 12) return null; double[] Map(double[] p) @@ -415,7 +441,20 @@ double[] Map(double[] p) t[11] + x * t[6] + y * t[7] + z * t[8], }; } + double[] MapAxis(double[] axis) => + [ + axis[0] * t[0] + axis[1] * t[1] + axis[2] * t[2], + axis[0] * t[3] + axis[1] * t[4] + axis[2] * t[5], + axis[0] * t[6] + axis[1] * t[7] + axis[2] * t[8], + ]; var outGeo = new GeometryData { Faces = new List() }; + bool rigid = IsRigidPlacement(t); + bool preservesVertical = rigid && Math.Abs(Math.Abs(t[8]) - 1) < 1e-9; + if (rigid && sym.ViewFacingLines is { Count: > 0 } viewLines) + outGeo.ViewFacingLines = viewLines.Select(line => line with + { + Start = Map(line.Start), End = Map(line.End), Axis = MapAxis(line.Axis), + }).ToList(); var faceMap = new Dictionary(); double minx = double.MaxValue, miny = double.MaxValue, minz = double.MaxValue; double maxx = double.MinValue, maxy = double.MinValue, maxz = double.MinValue; @@ -451,12 +490,18 @@ double[] Map(double[] p) Origin = verts[0], Area = f.Area, PlaneSurface = f.PlaneSurface, + ExcludedFromTopPlan = preservesVertical && f.ExcludedFromTopPlan, + ModelPattern = f.ModelPattern is { } pattern + ? new ModelFacePattern(pattern.PatternId, Map(pattern.Origin), MapAxis(pattern.U), MapAxis(pattern.V)) + : null, + PolygonMesh = f.PolygonMesh, NestedRenderStyleId = f.NestedRenderStyleId ?? f.RenderStyleId, GeometryNode = f.GeometryNode, NodeOrder = f.NodeOrder, GeometryStyle = f.GeometryStyle, MeshMarker = f.SourceFace != 0 ? f.SourceFace : f.MeshMarker, - QuadratureArea = IsRigidPlacement(t) ? f.QuadratureArea : null, + MeshArcs = rigid ? f.MeshArcs?.Select(arc => arc.Transformed(Map, MapAxis, 1) with { Edge = arc.Edge }).ToArray() : null, + QuadratureArea = rigid ? f.QuadratureArea : null, }); faceMap[sourceFaceIndex] = targetFaceIndex; } @@ -471,12 +516,12 @@ double[] Map(double[] p) // the Revit face meshes of the nodes are made in the frame of the symbol and placed // with the transform of the instance (a rotation or a mirror image; a scaled instance keeps // the polygons) - if (sym.MeshNodes is { Count: > 0 } && !IsRigidPlacement(t) && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") + if (sym.MeshNodes is { Count: > 0 } && !rigid && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") DiagnosticSink.WriteLine($"[meshmesh] {sym.MeshNodes.Count} nodes not placed: the transform is scaled ({string.Join(",", t.Select(v => v.ToString("G4")))})"); - if (sym.MeshNodes is { Count: > 0 } && IsRigidPlacement(t)) + if (sym.MeshNodes is { Count: > 0 } && rigid) outGeo.MeshNodes = sym.MeshNodes.Select(node => node with { Placement = node.Placement == null ? (double[])t.Clone() : ComposeTransforms(t, node.Placement) }).ToList(); // area and volume are the same in a rigidly placed frame; a scaled one has none - if (sym.NodeMeasures is { Count: > 0 } && IsRigidPlacement(t)) outGeo.NodeMeasures = sym.NodeMeasures; + if (sym.NodeMeasures is { Count: > 0 } && rigid) outGeo.NodeMeasures = sym.NodeMeasures; if (sym.BrepSolids is { Count: > 0 }) { outGeo.BrepSolids = new(); @@ -580,6 +625,7 @@ double[] Intersect(double[] a, double[] b) Solids = source.Solids, MeshNodes = source.MeshNodes, UntriangulatedFaces = source.UntriangulatedFaces, + ViewFacingLines = source.ViewFacingLines?.ToList(), }; var oldToNew = new Dictionary(); var clippedFaces = new HashSet(); @@ -610,6 +656,10 @@ double[] Intersect(double[] a, double[] b) ring.Select(point => (double[])point.Clone()).ToList()).ToList(), Area = face.Area, PlaneSurface = face.PlaneSurface, + MeshArcs = faceChanged ? null : face.MeshArcs, + ExcludedFromTopPlan = face.ExcludedFromTopPlan, + ModelPattern = face.ModelPattern, + PolygonMesh = face.PolygonMesh, NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, GeometryNode = face.GeometryNode, NodeOrder = face.NodeOrder, @@ -692,6 +742,7 @@ internal static string FaceCornerKey(List cs) }).ToList(), MeshNodes = grep.MeshNodes, UntriangulatedFaces = grep.UntriangulatedFaces, + ViewFacingLines = grep.ViewFacingLines?.ToList(), NodeMeasures = grep.NodeMeasures, Transform = grep.Transform, Instances = grep.Instances.Count > 0 @@ -788,12 +839,16 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou QuadratureArea = fp.QuadratureArea, CurvedSurface = fp.CurvedSurface, PlaneSurface = fp.PlaneSurface, + ExcludedFromTopPlan = fp.ExcludedFromTopPlan, + PolygonMesh = fp.PolygonMesh, PlaneXAxis = fp.PlaneX, PlaneYAxis = fp.PlaneY, SourceFace = fp.SourceFace, FirstSourceLoop = fp.FirstSourceLoop, SourceLoops = fp.SourceLoops, RenderStyleId = fp.RenderStyleId, + ModelPattern = fp.ModelPattern, + SurfaceRegions = fp.SurfaceRegions, GeometryNode = fp.GeometryNode, NodeOrder = fp.NodeOrder, GeometryStyle = fp.GeometryStyle, @@ -830,6 +885,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou YVector = fp.YVector, Normal = normal, Envelope = fp.Envelope, + ExcludedFromTopPlan = fp.ExcludedFromTopPlan, RenderStyleId = fp.RenderStyleId, GeometryNode = fp.GeometryNode, NodeOrder = fp.NodeOrder, @@ -2505,6 +2561,9 @@ void Add(int id, string name, StorageType st, object val) // in ExtractMaterialAppearance. Add(-1002551, "MATERIAL_PARAM_TRANSPARENCY", StorageType.Integer, Math.Max(0, m.Transparency)); if (m.TransparencyFraction >= 0) e.SerializedMaterialTransparency = m.TransparencyFraction; + if (state.NativeParams.GetValueOrDefault(eid)?.Fields.TryGetValue("2479:m_bUseRenderAppearance", out int useRender) == true + && useRender is 0 or 1) + e.SerializedMaterialUsesRenderAppearance = useRender == 1; // Smoothness: decoded value when the integer-percent guard passed and non-zero, else // the Revit default 50 ( materials in the export are 50). Add(-1002553, "MATERIAL_PARAM_SMOOTHNESS", StorageType.Integer, m.Smoothness > 0 ? m.Smoothness : 50); @@ -2950,7 +3009,7 @@ internal static void ApplyViewCrops(RevitFileInfo info, ParsingState? state) if (state == null || state.ViewCropBlocks.Count == 0) return; var views = new Dictionary(info.Elements.Count); foreach (var e in info.Elements) views[e.Id] = e; - foreach (var (_, crop) in state.ViewCropBlocks) + foreach (var (viewerId, crop) in state.ViewCropBlocks) { // The stored viewed id is kept only when it names a real view: a wrong read offset degrades to no crop. if (!views.TryGetValue(crop.RawViewId, out var view) || view.ViewCrop != null) continue; @@ -2963,6 +3022,66 @@ internal static void ApplyViewCrops(RevitFileInfo info, ParsingState? state) crop.Origin[0], crop.Origin[1], crop.Origin[2], crop.Basis[0], crop.Basis[1], crop.Basis[2], x0, y0, x1, y1, active); + if (view.RootClassName == "DBView3d" + && state.NativeParams.TryGetValue(viewerId, out var camera) + && camera.Fields.GetValueOrDefault("621:m_projMethodType") == 1 + && camera.Fields.GetValueOrDefault("4122:m_modelClipBoxId") is > 0 and int boxId + && state.NativeParams.TryGetValue((uint)boxId, out var box) + && box.Fields.GetValueOrDefault("2505:m_viewer3dId") == viewerId) + view.OrthographicModelBounds = box.ModelClipBox; + if (view.OrthographicModelBounds != null + && state.NativeParams.TryGetValue((uint)view.Id, out var display) + && display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is > 0 and int studyId + && state.NativeParams.TryGetValue((uint)studyId, out var study) + && study.Fields.GetValueOrDefault("m_ownerDBViewId") == view.Id + && study.Fields.GetValueOrDefault("3878:m_type") == 2 + && study.Fields.GetValueOrDefault("3878:m_bGroundPlane") == 1 + && study.Fields.GetValueOrDefault("3878:m_sunriseToSunset", -1) == 0 + && study.Fields.GetValueOrDefault("3878:m_sunPathSize") is >= 100 and <= 500 and int size + && study.Fields.GetValueOrDefault("3878:m_idLevel") is > 0 and int level + && study.SunStudyOutline is { } outline) + { + int annotation = study.Fields.GetValueOrDefault("3878:m_idAnnotation"); + if (!views.TryGetValue(annotation, out var sunAnnotation) + || sunAnnotation.RootClassName != "SunAnnotationElem" || sunAnnotation.OwnerViewId != view.Id) + annotation = 0; + int shadowIntensity = display.Fields.GetValueOrDefault("4107:m_lighting") == 1 + && display.Fields.GetValueOrDefault("4110:m_castShadows") == 1 + && display.Fields.GetValueOrDefault("4106:m_shadowIntensity") is > 0 and <= 100 and int intensity + ? intensity : 0; + int? sunlightIntensity = display.Fields.GetValueOrDefault("4107:m_lighting") == 1 + && display.Fields.GetValueOrDefault("4108:m_surfaces") == 4 + && display.Fields.GetValueOrDefault("4106:m_ambientLightIntensity", -1) == 0 + && display.Fields.GetValueOrDefault("4106:m_sunlightIntensity", -1) is >= 0 and <= 100 and int sunlight + ? sunlight : null; + view.SolarStudy = new(outline, size, level, annotation, + unchecked((uint)study.Fields.GetValueOrDefault("3878:m_startDateTime")), + unchecked((uint)study.Fields.GetValueOrDefault("3878:m_endDateTime")), + study.Fields.GetValueOrDefault("3878:m_eSunStudyTimeInterval", -1), + study.DoubleFields.GetValueOrDefault("3878:m_activeFrame"), shadowIntensity, + display.Fields.GetValueOrDefault("4108:m_bShowSurfacePatterns") == 1, + display.Fields.GetValueOrDefault("4108:m_edges") == 1, sunlightIntensity); + } + if (state.NativeParams.TryGetValue(viewerId, out var viewer) + && viewer.Fields.TryGetValue("621:m_bAnnotationCropActive", out int annotationActive) + && annotationActive is 0 or 1) + { + view.ViewAnnotationCropActive = annotationActive == 1; + if (annotationActive == 1 + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@0", out double left) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@1", out double right) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@2", out double top) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@3", out double bottom) + && left is >= 0 and < 100 && right is >= 0 and < 100 + && top is >= 0 and < 100 && bottom is >= 0 and < 100) + view.ViewAnnotationCrop = (left, right, top, bottom); + } + if (state.SectionViews.TryGetValue(viewerId, out var section)) + { + view.ViewAnnotationCrop ??= section.Viewdata?.AnnotationCrop; + if (section.Viewdata is { CalloutHead: { } head } data) + view.SectionCallout = (data.ParentViewId, head); + } } } @@ -3035,13 +3154,17 @@ void Add(int id, string name, double val) /// private static void ApplyDetailLines(RevitFileInfo info, ParsingState? state) { - if (state == null || (state.DetailCurveStyles.Count == 0 && state.CurveBlockOwners.Count == 0)) return; + if (state == null) return; + bool applyLineMetadata = state.DetailCurveStyles.Count != 0 || state.CurveBlockOwners.Count != 0; + if (!applyLineMetadata && state.CurveGeometry.Count == 0) return; foreach (var e in info.Elements) { - if (e.CategoryId.HasValue) continue; // categorized owners (sketch profiles etc.) keep their category + bool hasGeom = state.CurveGeometry.TryGetValue((uint)e.Id, out var cgeom); + if (hasGeom && cgeom.GStyle == -1) + e.DetailCircle = cgeom.Circle; + if (!applyLineMetadata || e.CategoryId.HasValue) continue; // Sketch profiles keep their category. bool hasStyle = state.DetailCurveStyles.TryGetValue((uint)e.Id, out int style); // A decoded line style (not -1) marks a detail/model line directly. - bool hasGeom = state.CurveGeometry.TryGetValue((uint)e.Id, out var cgeom); bool isCurveOwner = (state.CurveBlockOwners.Contains((uint)e.Id) || hasGeom) && !state.SketchCurves.ContainsKey((uint)e.Id); if (!hasStyle && !isCurveOwner) continue; @@ -3193,6 +3316,36 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) if (!state.NativeParams.TryGetValue((uint)e.Id, out var np)) continue; if (np.Fields.TryGetValue("3471:m_bIsLocationless", out int locationless)) e.SerializedRoomIsLocationless = locationless != 0; + e.DetailBreak = np.DetailBreak; + e.SitePropertyCurve = np.SitePropertyCurve; + e.SitePropertyArcCenter = np.SitePropertyArcCenter; + if (np.DoubleFields.TryGetValue("2202:m_widthInFeet", out double imageWidth) + && np.DoubleFields.TryGetValue("2202:m_heightInFeet", out double imageHeight) + && imageWidth is > 0 and < 100 && imageHeight is > 0 and < 100) + e.ImagePaperSize = (imageWidth, imageHeight); + if (np.Fields.TryGetValue("2202:m_idImageHolder", out int imageHolderId) && imageHolderId > 0) + e.ImageHolderId = imageHolderId; + if (np.DoubleFields.TryGetValue("2197:m_dWidthScale", out double imageWidthScale) + && np.DoubleFields.TryGetValue("2197:m_dHeightScale", out double imageHeightScale) + && imageWidthScale is > 0 and < 100 && imageHeightScale is > 0 and < 100) + e.ImageInstanceScale = (imageWidthScale, imageHeightScale); + if (np.Fields.TryGetValue("689:m_idSchemeCategory", out int legendCategory) + && legendCategory == (int)RvtIO.BuiltIns.BuiltInCategory.OST_Rooms + && np.DoubleFields.TryGetValue("689:m_origin@0", out double legendX) + && np.DoubleFields.TryGetValue("689:m_origin@1", out double legendY) + && double.IsFinite(legendX) && double.IsFinite(legendY)) + e.RoomLegendOrigin = (legendX, legendY); + if (np.DoubleFields.TryGetValue("697:m_swatchWidth", out double swatchWidth) + && np.DoubleFields.TryGetValue("697:m_swatchHeight", out double swatchHeight) + && swatchWidth is > 0 and < 1 && swatchHeight is > 0 and < 1) + e.ColorLegendSwatch = (swatchWidth, swatchHeight); + if (e.CategoryId == (int)RvtIO.BuiltIns.BuiltInCategory.OST_InsulationLines + && np.DoubleFields.TryGetValue("2239:m_width", out double insulationWidth) + && np.DoubleFields.TryGetValue("2239:m_scale", out double insulationScale) + && np.Fields.TryGetValue("2239:m_mirrored", out int mirrored) + && insulationWidth is > 0 and < 100 && insulationScale is > 0 and < 100 + && mirrored is 0 or 1) + e.DetailInsulation = (insulationWidth, insulationScale, mirrored == 1); if (np.StringFields.TryGetValue("388:m_areaElemName", out string? areaSchemeName) && np.StringFields.TryGetValue("388:m_areaElemDescription", out string? areaSchemeDescription)) e.SerializedAreaScheme = (areaSchemeName, areaSchemeDescription); @@ -4981,6 +5134,7 @@ internal static int ApplyWallJoinedToTop(IReadOnlyList elements, Parsin foreach (Element element in elements) { element.SerializedWallJoinedToTop = null; + element.SerializedWallTopAttachmentTargets = null; if (element.Id <= 0 || element.CategoryId != -2000011 || counts[element.Id] != 1 @@ -4989,6 +5143,7 @@ internal static int ApplyWallJoinedToTop(IReadOnlyList elements, Parsin || source.JoinedToTop is not bool joinedToTop) continue; element.SerializedWallJoinedToTop = joinedToTop; + if (joinedToTop) element.SerializedWallTopAttachmentTargets = source.Targets; if (joinedToTop) SetParam(element, -1001117, "WALL_TOP_IS_ATTACHED", StorageType.Integer, 1); applied++; @@ -5813,25 +5968,50 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null rvtInfo.TitleBlockTexts = state?.TitleBlockTexts .Where(pair => pair.Value is { BlockCount: 1, Texts: not null }) .ToDictionary(pair => (int)pair.Key, - pair => (IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>)pair.Value.Texts! - .Select(text => (text.Ox, text.Oy, text.Height, text.Width, text.Flags, text.Bx, text.By, text.Rtf)).ToList()); + pair => (IReadOnlyList)pair.Value.Texts!); rvtInfo.TitleBlockLabels = state?.TitleBlockLabels .Where(pair => pair.Value is { BlockCount: 1, Labels: not null }) .ToDictionary(pair => (int)pair.Key, - pair => (IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>)pair.Value.Labels! - .Select(label => (label.Ox, label.Oy, label.Height, label.Width, label.Flags, label.Bx, label.By, label.ParamId, label.Prefix, label.Suffix)).ToList()); + pair => (IReadOnlyList)pair.Value.Labels!); + if (state != null && rvtInfo.TitleBlockLabels is { } titleLabels) + { + var capHeights = new Dictionary(); + var opaqueStyles = new HashSet(); + var arialStyles = new HashSet(); + foreach (int attributesId in titleLabels.Values.SelectMany(labels => labels).Select(label => label.AttrId).Distinct()) + { + if (attributesId <= 0 || !state.NativeParams.TryGetValue((uint)attributesId, out var attributes) + || attributes.Fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || font.DoubleFields.GetValueOrDefault("1923:m_size") is not (> 0 and < 1 and var height)) + continue; + capHeights.Add(attributesId, height); + if (attributes.Fields.GetValueOrDefault("625:m_background", -1) == 0) + opaqueStyles.Add(attributesId); + if (attributes.Fields.GetValueOrDefault("625:m_bBold") == 0 + && attributes.Fields.GetValueOrDefault("625:m_bItalic") == 0 + && font.StringFields.GetValueOrDefault("1923:m_name")?.Equals("Arial", StringComparison.OrdinalIgnoreCase) == true) + arialStyles.Add(attributesId); + } + rvtInfo.TitleBlockCapHeightsFeet = capHeights; + rvtInfo.OpaqueSymbolLabelStyles = opaqueStyles; + rvtInfo.RegularArialSymbolLabelStyles = arialStyles; + rvtInfo.PlanElevationMarks = ReadPlanElevationMarks(state); + rvtInfo.SectionMarkerSymbols = state.NativeParams + .Where(pair => state.ElemClassIdx.GetValueOrDefault(pair.Key) == 3546 + && pair.Value.Fields.GetValueOrDefault("3546:m_sectionHeadFamilyTagId") > 0 + && pair.Value.Fields.GetValueOrDefault("3546:m_sectionTailFamilyTagId") > 0) + .ToDictionary(pair => (int)pair.Key, + pair => (pair.Value.Fields["3546:m_sectionHeadFamilyTagId"], + pair.Value.Fields["3546:m_sectionTailFamilyTagId"])); + } rvtInfo.ScheduleInstances = state?.ScheduleInstances .Where(pair => pair.Value is { BlockCount: 1, Placement: not null }) .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Placement!.ScheduleId, pair.Value.Placement!.Ox, pair.Value.Placement!.Oy)); rvtInfo.ScheduleTables = state?.ScheduleTables .Where(pair => pair.Value is { BlockCount: 1, Table: not null }) - .ToDictionary(pair => (int)pair.Key, - pair => (pair.Value.Table!.Columns, pair.Value.Table!.CategoryId, pair.Value.Table!.ShowTitle, - pair.Value.Table!.ShowHeaders, pair.Value.Table!.ShowGridLines, pair.Value.Table!.ShowOutline, - pair.Value.Table!.GridStyleId, pair.Value.Table!.OutlineStyleId, - pair.Value.Table!.TitleHeightFt, pair.Value.Table!.TitleBands, pair.Value.Table!.BodySections, - pair.Value.Table!.FixedHeightFt)); + .ToDictionary(pair => (int)pair.Key, pair => ResolveRevisionTextTypes(state, pair.Value.Table!)); rvtInfo.ScheduleSheetRevisions = state?.SheetRevisions .Where(pair => pair.Value is { BlockCount: 1, RevisionIds: not null }) .ToDictionary(pair => (int)pair.Key, @@ -5841,14 +6021,102 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Viewdata!.ParentViewId, pair.Value.Viewdata!.CoarserScale, (IReadOnlyList?)pair.Value.Viewdata!.FrontCut)); + rvtInfo.SectionTraceOrigins = state?.SectionViews + .Where(pair => pair.Value is { BlockCount: 1, Viewdata.TraceOrigin: not null }) + .ToDictionary(pair => (int)pair.Key, pair => pair.Value.Viewdata!.TraceOrigin!.Value); + rvtInfo.SiteCutGraphics = state is { SiteCutGraphicsCount: 1 } ? state.SiteCutGraphics : null; + rvtInfo.PropertyBearingFormat = state is { PropertyBearingFormatCount: 1 } ? state.PropertyBearingFormat : null; + rvtInfo.DatumExtents = state?.DatumExtents + .Where(p => p.Value.BlockCount == 1).ToDictionary(p => p.Key, p => p.Value.Extents); + rvtInfo.DatumHeads = state?.DatumHeads.Where(p => p.Value != null).ToDictionary(p => p.Key, p => p.Value!); rvtInfo.MaterialPatterns = state?.MaterialPatterns .Where(pair => pair.Value is { SurfacePatternId: not -1 } or { CutPatternId: not -1 }) .ToDictionary(pair => (int)pair.Key, - pair => (pair.Value.CutPatternId, pair.Value.SurfacePatternId)); + pair => (pair.Value.CutPatternId, pair.Value.SurfacePatternId, pair.Value.SurfacePatternColor)); + rvtInfo.MaterialCutPatternColors = state?.MaterialPatterns + .Where(pair => pair.Value is { BlockCount: 1, CutPatternId: > 0, CutPatternColor: >= 0 and <= 0xffffff }) + .ToDictionary(pair => (int)pair.Key, pair => pair.Value.CutPatternColor!.Value); rvtInfo.FillPatterns = state?.FillPatterns .Where(pair => pair.Value is { Name: not null, Grids: not null }) .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Name!, (IReadOnlyList)pair.Value.Grids!)); + if (state != null) + { + rvtInfo.ViewRoomColors = BuildViewRoomColors(rvtInfo, state); + ReadPlanDimensions(rvtInfo, state); + rvtInfo.PlanNotes = ReadPlanNotes(state); + rvtInfo.PlanStairPaths = ReadPlanStairPaths(state); + rvtInfo.SiteContours = state.NativeParams.Where(entry => entry.Value.SiteContours != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.SiteContours!); + rvtInfo.SiteContourLabels = BuildSiteContourLabels(state); + rvtInfo.ViewHiddenElements = state.NativeParams.Where(entry => entry.Value.ViewHiddenElements != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.ViewHiddenElements!); + rvtInfo.ViewHiddenCategories = state.NativeParams.Where(entry => entry.Value.ViewHiddenCategories != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.ViewHiddenCategories!); + var opaqueViews = state.NativeParams.Where(entry => + entry.Value.Fields.GetValueOrDefault("4107:m_hlr") == 1 + && entry.Value.Fields.GetValueOrDefault("4108:m_surfaces") == 2 + && entry.Value.Fields.GetValueOrDefault("4108:m_transparency", -1) == 0) + .ToArray(); + rvtInfo.OpaquePlanViews = opaqueViews.Select(entry => (int)entry.Key).ToHashSet(); + var skyGradients = new Dictionary(); + foreach (var (view, display) in opaqueViews) + if (display.Fields.GetValueOrDefault("4103:m_type") == 257 + && display.Fields.GetValueOrDefault("4103:m_skyColor", -1) is >= 0 and <= 0xffffff and int sky + && display.Fields.GetValueOrDefault("4103:m_backgroundColor", -1) is >= 0 and <= 0xffffff and int horizon) + skyGradients.Add((int)view, (sky, horizon, + display.Fields.GetValueOrDefault("4103:m_groundColor", -1) is >= 0 and <= 0xffffff and int ground + ? ground : null)); + rvtInfo.ViewSkyGradients = skyGradients; + var groundShadows = new Dictionary(); + foreach (var (view, display) in opaqueViews) + { + if (display.Fields.GetValueOrDefault("4110:m_castShadows") != 1 + || display.Fields.GetValueOrDefault("4106:m_shadowIntensity", -1) is not (>= 0 and <= 100 and int intensity) + || display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is not (> 0 and int id) + || !state.NativeParams.TryGetValue((uint)id, out var light) + // Lighting study with an authored ground plane and light angles relative to the view. + || light.Fields.GetValueOrDefault("3878:m_type") != 3 + || light.Fields.GetValueOrDefault("3878:m_bGroundPlane") != 1 + || light.Fields.GetValueOrDefault("3878:m_bRelativeToView") != 1 + || light.Fields.GetValueOrDefault("3878:m_idLevel") is not (> 0 and int level) + || !light.DoubleFields.TryGetValue("3878:m_dAzimuth", out double azimuth) + || !(azimuth >= 0 && azimuth <= 2 * Math.PI) + || !light.DoubleFields.TryGetValue("3878:m_dAltitude", out double altitude) + || !(altitude > 0 && altitude <= Math.PI / 2)) continue; + groundShadows.Add((int)view, (azimuth, altitude, level, intensity)); + } + rvtInfo.ViewGroundShadows = groundShadows; + var stillSunDates = new Dictionary(); + foreach (var (view, display) in opaqueViews) + if (display.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && display.Fields.GetValueOrDefault("4110:m_castShadows", -1) == 0 + && display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is > 0 and int id + && state.NativeParams.TryGetValue((uint)id, out var light) + && light.Fields.GetValueOrDefault("3878:m_type", -1) == 0 + && light.Fields.TryGetValue("3878:m_startDateTime", out int time)) + stillSunDates.Add((int)view, unchecked((uint)time)); + rvtInfo.ViewStillSunDates = stillSunDates; + rvtInfo.ViewAmbientLight = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && entry.Value.Fields.GetValueOrDefault("4106:m_ambientLightIntensity", -1) is >= 0 and <= 100) + .ToDictionary(entry => (int)entry.Key, + entry => entry.Value.Fields["4106:m_ambientLightIntensity"] / 100.0); + rvtInfo.ViewAmbientFractions = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && entry.Value.Fields.GetValueOrDefault("4106:m_ambientLightIntensity", -1) is > 0 and <= 100 + && entry.Value.Fields.GetValueOrDefault("4106:m_sunlightIntensity", -1) is >= 0 and <= 100) + .ToDictionary(entry => (int)entry.Key, + entry => (double)entry.Value.Fields["4106:m_ambientLightIntensity"] + / (entry.Value.Fields["4106:m_ambientLightIntensity"] + entry.Value.Fields["4106:m_sunlightIntensity"])); + rvtInfo.OpaqueViewsWithSurfacePatterns = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4108:m_bShowSurfacePatterns", -1) == 1) + .Select(entry => (int)entry.Key).ToHashSet(); + rvtInfo.UnshadedHiddenLineViews = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows", -1) == 0 + && entry.Value.Fields.GetValueOrDefault("4110:m_castShadows", -1) == 0) + .Select(entry => (int)entry.Key).ToHashSet(); + } rvtInfo.PlanViewRanges = state?.PlanViewRanges .Where(pair => pair.Value is { Offsets: not null, LevelIds: not null }) .ToDictionary(pair => (int)pair.Key, @@ -6551,6 +6819,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplySerializedSystemTypeIdentity(rvtInfo.Elements, state); ApplyValidatedOriginalFamilySymbols(rvtInfo.Elements, state); ApplyOwnFamilyCutoutInputs(rvtInfo.Elements, state); + ApplyPlanFixtureGraphics(rvtInfo.Elements, state); ApplySolidTrimmedAxis(rvtInfo.Elements); ApplyValidatedCeilingCanonicalTypes(rvtInfo.Elements, state); ApplySerializedStairData( @@ -6636,6 +6905,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyColumnAttachments(rvtInfo); ApplyMovesWithGrids(rvtInfo); ApplyEditedByCategoryRules(rvtInfo, state); + if (state != null) rvtInfo.EvaluatedScheduleRows = EvaluateScheduleRows(rvtInfo, state); ApplyCapturedCurveStyles(rvtInfo, state); // Reference precedence needs the final decoded instance/type parameter sets. if (state != null) @@ -6754,11 +7024,13 @@ internal static void ApplyHeaderBoundingBoxes(RevitFileInfo rvtInfo, ParsingStat } /// The order key of the GInstance node the source geometry is the symbol of: the source's nodes then sort at that node's place among the nodes of the target (Revit walks a GInstance's symbol where the GInstance stands); null keeps the keys of the source as they are. - private static void AppendGeometry(GeometryData target, GeometryData source, long? instanceOrder = null) + internal static void AppendGeometry(GeometryData target, GeometryData source, long? instanceOrder = null) { int faceOffset = target.Faces.Count; int edgeOffset = target.Edges?.Count ?? 0; target.UntriangulatedFaces += source.UntriangulatedFaces; + if (source.ViewFacingLines is { Count: > 0 } viewLines) + (target.ViewFacingLines ??= []).AddRange(viewLines); // Geometry node ids are unique within one GeometryData: the appended nodes follow the // existing ones. (a negative id marks a node that Revit does not take, see // GRepParserV2). @@ -6810,6 +7082,9 @@ face.AnalyticCylinderReferenceDirection is null QuadratureArea = face.QuadratureArea, CurvedSurface = face.CurvedSurface, PlaneSurface = face.PlaneSurface, + ExcludedFromTopPlan = face.ExcludedFromTopPlan, + ModelPattern = face.ModelPattern, + PolygonMesh = face.PolygonMesh, PlaneXAxis = face.PlaneXAxis, PlaneYAxis = face.PlaneYAxis, SourceFace = face.SourceFace, diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a90f342b..b69eaa7e 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -37,10 +37,12 @@ private sealed class DecodeStop : Exception { } /// Class "Geometry" (a GBRep): one stored solid. internal const ushort SolidClass = 2092; - private sealed record InstanceRec( + internal sealed record InstanceRec( int SymbolElemId, double[] Transform, int OwnerQueueIndex); - private sealed class Cur + internal sealed record SheetImagePlacement(int SymbolId, double X, double Y, double ScaleX, double ScaleY); + + internal sealed class Cur { public byte[] D = []; public int Pos, End; @@ -50,6 +52,7 @@ private sealed class Cur public bool NativeWallBody; public bool IncludeNonVisible; public bool SawDetailCondition; // a node was judged below a detail-level condition + public List? SheetImages; public int BlockStart, BlockEnd; // this block's payload bounds (plane scan) public int LastEdgeEnd; // pos after the last decoded Edge public List<(ushort Cls, int V)> Queue = new(); @@ -58,6 +61,7 @@ private sealed class Cur public int FaceCount; // faces seen (schema-walked) public List FaceOrder = new(); // face handle (queue v) in processing order public Dictionary FaceRenderStyle = new(); // GFace.m_renderStyleId (the face material) by face handle + public Dictionary? FacePatternPlacers; public Dictionary FaceFlagsV9 = new(); // GFace.m_faceFlags_v9 by face handle public List SurfClasses = new(); // surface classId per face, in queue order public List Edges = new(); @@ -107,7 +111,7 @@ private sealed class Cur public Dictionary HarvestSurf = new(); // Exact deferred-pointer graph. QueueLinks is also needed by production geometry ownership; - // QueueChildren retains only m_oConditions outside targeted diagnostics. + // QueueChildren keeps condition links and direct root-filter contents outside diagnostics. public int CurrentObjectHandle; public ushort CurrentObjectClass; public int CurrentQueueIndex = -1; @@ -118,6 +122,9 @@ private sealed class Cur public Dictionary>> QueueDoubles = new(); public Dictionary>> QueueBytes = new(); public Dictionary ObjectGInfo = new(); + public List<(int Index, int Tag, int StyleId, ArcRec Line)>? ViewLineCandidates; + public List<(int Filter, uint Handle, uint Flags, bool Filled, int StyleId)>? PlanCurveCandidates; + public List<(int FaceIndex, uint Handle)>? PlanMaskCandidates; public EdgeRec? CapEdge; // non-null while walking an Edge public bool ExactPlanarSpaceBoundary; @@ -512,7 +519,7 @@ private static void RegisterSpaceWeldPoints(Cur c) } } - private sealed class SpaceEdgeLoopRec + internal sealed class SpaceEdgeLoopRec { public uint Face, Next, Prev; public byte Open; @@ -790,9 +797,10 @@ static double Distance(double[] a, double[] b) => Math.Sqrt((a[0] - b[0]) * (a[0 /// holds detail-level alternatives that differ (). /// /// Use native Low edge sampling only after confirming a unique own wall root and GRep. - public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false) + public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false, + Action? collectPlanFixtures = null) { - var fine = ParseCore(d, blockStart, dataSize, nativeWallBody); + var fine = ParseCore(d, blockStart, dataSize, nativeWallBody, collectPlanFixtures: collectPlanFixtures); if (fine is not { HasDetailLevelAlternatives: true }) return fine; try { @@ -828,7 +836,18 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = && fine.Instances.Zip(coarse.Instances).All(pair => pair.First.SymbolElemId == pair.Second.SymbolElemId && pair.First.Transform.SequenceEqual(pair.Second.Transform)); - private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false) + internal static IReadOnlyList ReadSheetImages(byte[] block) + { + if (block.Length < 20) return []; + uint size = BitConverter.ToUInt32(block, 8); + if (size != block.Length - 16 || BitConverter.ToUInt32(block, block.Length - 4) != size) return []; + var images = new List(); + ParseCore(block, 0, size, false, sheetImages: images); + return images; + } + + private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false, + List? sheetImages = null, Action? collectPlanFixtures = null) { int payloadStart = blockStart + 14; int payloadEnd = (int)Math.Min((long)blockStart + 16 + dataSize, d.Length); @@ -851,6 +870,7 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = RootClass = classId, CurrentObjectHandle = elementId, CurrentObjectClass = classId, + SheetImages = sheetImages, }; if (targeted) { @@ -858,17 +878,22 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = Array.Copy(d, blockStart, raw, 0, raw.Length); File.WriteAllBytes(Path.Combine(Path.GetTempPath(), $"grep_schema_{elementId}.bin"), raw); } + int resyncs = 0; try { foreach (var f in rootFields) ReadField(c, f, 0); if (dbg) DiagnosticSink.WriteLine($" V2 eid={elementId} root bbox=[{string.Join(',', c.RootBoundingBox ?? [])}] tight=[{string.Join(',', c.RootTightBoundingBox ?? [])}]"); - int resyncs = 0; for (int qi = 0; qi < c.Queue.Count; qi++) { int itemStart = c.Pos; if (targeted) c.DebugItemStarts.Add(itemStart); - try { WalkQueueItem(c, qi); } + try + { + WalkQueueItem(c, qi); + if (resyncs == 0 && c.Queue[qi].Cls == 2014) + CaptureFacePattern(c, qi, itemStart); + } catch (DecodeStop) { if (dbg) @@ -895,6 +920,7 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = } catch (DecodeStop) { if (dbg) DiagnosticSink.WriteLine($" V2 stop at pos={c.Pos}/{c.End} faces={c.FaceCount} edges={c.Edges.Count} queue={c.Queue.Count}"); } catch (Exception ex) { if (dbg) DiagnosticSink.WriteLine($" V2 exc {ex.GetType().Name}: {ex.Message} at pos={c.Pos} faces={c.FaceCount} edges={c.Edges.Count}"); } + if (sheetImages != null && c.Pos != c.End) sheetImages.Clear(); // Grammar-first harvest of a large unwalked tail: post-gap objects belong to queue entries // whose parents were never walked (never enqueued) - the queue can't reach them, but the @@ -1001,9 +1027,17 @@ string Number(double value) => value.ToString("G17", } } } + if (collectPlanFixtures != null && c.Pos == c.End && resyncs == 0 + && ReadPlanFixtureGraphics(c) is { } planGraphics) + collectPlanFixtures(planGraphics); var built = BuildGeometry(c); if (built != null) { + if (c.Pos == c.End) + { + built.ViewFacingLines = ReadViewFacingLines(c); + if (resyncs == 0) built.DoorPlanSymbols = ReadDoorPlanSymbols(c); + } built.QueueClassCounts = c.Queue.GroupBy(item => item.Cls).ToDictionary(group => group.Key, group => group.Count()); built.HasDetailLevelAlternatives = c.SawDetailCondition; built.RootBoundingBox = ValidBox(c.RootBoundingBox) ? c.RootBoundingBox : null; @@ -1241,6 +1275,74 @@ bool TryReadCount(out uint count) return true; } + private static void ReadSheetImage(Cur c) + { + // ImageInfoScaled starts with the base/up vectors and the inline Trf basis and origin. + ReadOnlySpan basis = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!c.CanRead(168)) return; + int start = c.Pos; + for (int i = 0; i < basis.Length; i++) + if (BitConverter.ToDouble(c.D, start + 8 * i) != basis[i]) return; + double x = BitConverter.ToDouble(c.D, start + 120); + double y = BitConverter.ToDouble(c.D, start + 128); + double z = BitConverter.ToDouble(c.D, start + 136); + int symbol = BitConverter.ToInt32(c.D, start + 144); + double sx = BitConverter.ToDouble(c.D, start + 152); + double sy = BitConverter.ToDouble(c.D, start + 160); + if (symbol > 0 && z == 0 && Math.Abs(x) < 100 && Math.Abs(y) < 100 + && sx is > 0 and < 100 && sy is > 0 and < 100) + c.SheetImages!.Add(new SheetImagePlacement(symbol, x, y, sx, sy)); + } + + private static void CaptureFacePattern(Cur c, int qi, int start) + { + if (c.QueueLinks[qi] is not (>= 0 and var parent, "m_pGFilling") + || c.Queue[parent] is not (1589, var face)) return; + if (c.RootClass == 2007 && !c.IncludeNonVisible && c.Pos - start == 94) + { + var fill = c.D.AsSpan(start, 94); + // A blank pattern with the saved background-color token forms the mask of a 2D symbol. + if (BitConverter.ToInt32(fill[16..]) == face && BitConverter.ToUInt32(fill[78..]) == 0 + && BitConverter.ToInt32(fill[82..]) == -1 && BitConverter.ToUInt32(fill[86..]) == 0x01000000u + && BitConverter.ToInt32(fill[90..]) == 34) + (c.PlanMaskCandidates ??= []).Add((parent, (uint)face)); + return; + } + if (c.Pos - start != 96) return; + + // GFilling: GInfo, face back-reference, FillPatternPlacer, FillPatternData pointer, id, color, flags. + var data = c.D.AsSpan(start, 96); + if (BitConverter.ToInt32(data[16..]) != face + || BitConverter.ToUInt32(data[78..]) != uint.MaxValue || BitConverter.ToUInt16(data[82..]) != 1850 + || BitConverter.ToUInt32(data[88..]) != 0 || BitConverter.ToInt32(data[92..]) != 9) + return; + int id = BitConverter.ToInt32(data[84..]); + // shortcut: support black model placers with unit scales, extend when other layouts are verified. + if (id <= 0 || BitConverter.ToDouble(data[20..]) != 1 || BitConverter.ToDouble(data[60..]) != 1 + || BitConverter.ToDouble(data[68..]) != 1 || data[76] != 0 || data[77] != 0) return; + double u = BitConverter.ToDouble(data[28..]), v = BitConverter.ToDouble(data[36..]); + double du = BitConverter.ToDouble(data[44..]), dv = BitConverter.ToDouble(data[52..]); + if (!IsFinite(u) || !IsFinite(v) || !IsFinite(du) || !IsFinite(dv) + || Math.Abs(du * du + dv * dv - 1) > 1e-9) return; + (c.FacePatternPlacers ??= new())[(uint)face] = (id, u, v, du, dv); + } + + private static ModelFacePattern? PlacedFacePattern(Cur c, uint face) + { + if (c.FacePatternPlacers?.TryGetValue(face, out var placer) != true + || !c.DirectSurfaceByFace.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane + || World(ToPlane(surface), placer.U, placer.V) is not { } origin) return null; + + var u = new double[3]; + var v = new double[3]; + for (int axis = 0; axis < 3; axis++) + { + u[axis] = placer.Du * surface.X[axis] + placer.Dv * surface.Y[axis]; + v[axis] = -placer.Dv * surface.X[axis] + placer.Du * surface.Y[axis]; + } + return new ModelFacePattern(placer.Id, origin, u, v); + } + private static void WalkQueueItem(Cur c, int qi) { var (cls, v) = c.Queue[qi]; @@ -1249,6 +1351,9 @@ private static void WalkQueueItem(Cur c, int qi) c.CurrentObjectClass = cls; var qf = TfBlockDeserializer.SerializationFields(cls); if (qf == null) throw Stop; + if (cls == 2197 && c.SheetImages != null && c.QueueLinks[qi] is (int parent, "m_imageInfo") + && parent >= 0 && c.Queue[parent].Cls == 2022) + ReadSheetImage(c); // Blob-headed items: refresh the class's tag base (tag = base + ordinal). if (qf.Count > 0 && qf[0].Name == "m_GInfo" && c.CanRead(16)) { @@ -1426,6 +1531,7 @@ double[] ReadParameters() ar.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); ar.C[k] = BitConverter.ToDouble(c.D, c.Pos + 88 + 8 * k); } + CapturePlanCutCurve(c, qi, (uint)v, c.D[c.Pos + 112] != 0); c.Take(113); if (IsFinite(ar.R) && IsFinite(ar.C[0]) && Math.Abs(ar.R) > 1e-9 && Math.Abs(ar.R) < 1e5) c.Curves[(uint)v] = ar; @@ -1448,6 +1554,7 @@ double[] ReadParameters() ellipse.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); ellipse.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 80 + 8 * k); } + CapturePlanCutCurve(c, qi, (uint)v, false); c.Take(120); if (IsFinite(ellipse.R) && IsFinite(ellipse.RY) && Math.Abs(ellipse.R) > 1e-9 && Math.Abs(ellipse.R) < 1e5 @@ -1480,6 +1587,16 @@ double[] ReadParameters() ln.C[k] = BitConverter.ToDouble(c.D, c.Pos + 32 + 8 * k); ln.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); } + if (c.RootClass == 2007 && !c.IncludeNonVisible + && c.QueueLinks[qi] is (>= 0 and int parentIndex, "m_subNodes") + && c.Queue[parentIndex].Cls == 2015 && c.QueueLinks[parentIndex].ParentQueueIndex < 0) + { + int style = BitConverter.ToInt32(c.D, c.Pos + 8); + uint flags = BitConverter.ToUInt32(c.D, c.Pos + 12); + if (style > 0 && !IsHiddenInstanceVariant(flags) && IsPhysicalBodySurface(flags)) + (c.ViewLineCandidates ??= []).Add((qi, BitConverter.ToInt32(c.D, c.Pos), style, ln)); + } + CapturePlanCutCurve(c, qi, (uint)v, false); c.Take(80); if (IsFinite(ln.C[0]) && IsFinite(ln.X[0])) c.Curves[(uint)v] = ln; @@ -1807,6 +1924,292 @@ internal static bool ShouldAttachSymbolGeometry(ushort ownerClass) /// internal static bool IsHiddenInstanceVariant(uint nodeFlags) => (nodeFlags & 0xE0u) == 0xE0u; + private static void CapturePlanCutCurve(Cur c, int index, uint handle, bool filled) + { + if (c.RootClass != 2007 || c.IncludeNonVisible + || c.QueueLinks[index] is not (>= 0 and int filter, "m_subNodes") + || c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes")) + return; + int style = BitConverter.ToInt32(c.D, c.Pos + 4) == 0 ? BitConverter.ToInt32(c.D, c.Pos + 8) : -1; + (c.PlanCurveCandidates ??= []).Add((filter, handle, BitConverter.ToUInt32(c.D, c.Pos + 12), filled, style)); + } + + internal static List? ReadDoorPlanSymbols(Cur c) + { + if (c.PlanCurveCandidates == null) return null; + var symbols = new List(); + foreach (var group in c.PlanCurveCandidates.GroupBy(candidate => candidate.Filter)) + { + var conditions = c.QueueChildren.GetValueOrDefault(group.Key)?.Where(index => + c.QueueLinks[index].Field == "m_oConditions").ToArray(); + if (conditions is not [int condition] || c.Queue[condition].Cls is not (1995 or 1996) + || !IsTopPlanCondition(c, condition, out var values)) + continue; + (double Lo, double Hi)? cutRange = null; + if (c.Queue[condition].Cls == 1995) + { + if (values.GetValueOrDefault("m_rangeLo") is not [double lo] + || values.GetValueOrDefault("m_rangeHi") is not [double hi] + || !IsFinite(lo) || !IsFinite(hi) || hi <= lo) + continue; + cutRange = (lo, hi); + } + // shortcut: require a complete set of direct line and circular-arc children. + if (c.QueueChildren[group.Key].Count != group.Count() + 1 + || !c.ObjectGInfo.TryGetValue(c.Queue[group.Key].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0) + continue; + var curves = new List(); + foreach (var item in group) + { + if (item.Filled || (item.Flags & 0x20u) != 0 + || !c.Curves.TryGetValue(item.Handle, out var curve) || curve.RY != 0 || !IsPlanCutCurve(curve)) + break; + curves.Add(curve); + } + if (curves.Count == group.Count() && curves.Any(curve => curve.R > 0) + && curves.Any(curve => curve.R == 0)) + symbols.Add(new(cutRange, curves)); + } + return symbols.Count == 0 ? null : symbols; + } + + private static bool IsTopPlanCondition(Cur c, int condition, + [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Dictionary>? values) + { + values = c.QueueDoubles.GetValueOrDefault(condition); + return c.QueueInts.GetValueOrDefault(condition)?.GetValueOrDefault("m_comp") == 6 + && c.QueueBytes.GetValueOrDefault(condition)?.GetValueOrDefault("m_negateDirCondition") is [0] + && values?.GetValueOrDefault("m_dir") is [0, 0, 1]; + } + + private static bool ExcludesTopPlan(Cur c, int node) + { + while (node >= 0 && node < c.QueueLinks.Count && c.QueueLinks[node] is (>= 0 and int parent, "m_subNodes")) + { + if (c.Queue[parent].Cls == 2015 + && c.QueueChildren.TryGetValue(parent, out var children) + && children.Any(child => c.QueueLinks[child].Field == "m_oConditions" + && c.Queue[child].Cls == 1996 + && c.QueueInts.GetValueOrDefault(child)?.GetValueOrDefault("m_comp") == 8 + && c.QueueBytes.GetValueOrDefault(child)?.GetValueOrDefault("m_negateDirCondition") is [1] + && c.QueueDoubles.GetValueOrDefault(child)?.GetValueOrDefault("m_dir") is [var x, var y, var z] + && Math.Abs(x) < 1e-9 && Math.Abs(y) < 1e-9 && Math.Abs(Math.Abs(z) - 1) < 1e-9)) + return true; + node = parent; + } + return false; + } + + internal static PlanFixtureGraphics? ReadPlanFixtureGraphics(Cur c) + { + var lines = new List(); + foreach (var group in (c.PlanCurveCandidates ?? []).GroupBy(candidate => candidate.Filter)) + { + // The unconditional line branch is complete, including any tagged non-printing lines. + if (c.QueueChildren[group.Key].Count != group.Count() + || !c.ObjectGInfo.TryGetValue(c.Queue[group.Key].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0 + || c.QueueChildren[group.Key].Any(index => c.QueueLinks[index].Field != "m_subNodes" || c.Queue[index].Cls != 1736)) + continue; + var visible = group.Where(item => (item.Flags & 0x20u) == 0).ToArray(); + var strokes = new List(); + foreach (var item in visible) + { + if (item.StyleId <= 0 || !c.Curves.TryGetValue(item.Handle, out var curve) + || !IsPlanCutCurve(curve)) break; + var start = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T0 * curve.X[i]).ToArray(); + var end = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T1 * curve.X[i]).ToArray(); + if (!start.All(IsFinite) || !end.All(IsFinite) || start.SequenceEqual(end)) break; + strokes.Add(new(start, end, item.StyleId)); + } + if (strokes.Count == visible.Length) lines.AddRange(strokes); + } + var mediumProjection = ReadTopFixtureProjection(c, 2); + var coarseProjection = ReadTopFixtureProjection(c, 1); + return lines.Count == 0 && mediumProjection == null && coarseProjection == null ? null + : new(lines, lines.Count == 0 ? [] : ReadPlanFixtureMasks(c), mediumProjection, coarseProjection); + } + + internal static PlanFixtureProjection? ReadTopFixtureProjection(Cur c, int detailLevel) + { + if (c.PlanMaskCandidates == null && c.PlanCurveCandidates == null) return null; + var lines = new List(); + var masks = new List>(); + var curvesByFilter = (c.PlanCurveCandidates ?? []).ToLookup(candidate => candidate.Filter); + Dictionary>? loopsByFace = null; + Dictionary? edges = null; + foreach (var (filter, children) in c.QueueChildren) + { + if (c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes") + || !c.ObjectGInfo.TryGetValue(c.Queue[filter].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0) + continue; + var conditions = children.Where(index => c.QueueLinks[index].Field == "m_oConditions").ToArray(); + if (!conditions.Any(index => c.Queue[index].Cls == 1996 && IsTopPlanCondition(c, index, out _))) + continue; + if (conditions.Length > 2) return null; + if (conditions.Length == 2) + { + var detailConditions = conditions.Where(index => c.Queue[index].Cls == 1999).ToArray(); + if (detailConditions is not [int detail] + || c.QueueInts.GetValueOrDefault(detail) is not { } values + || values.GetValueOrDefault("m_param") != 3 + || !values.TryGetValue("m_comp", out int comparison) || comparison is < -1 or > 5 + || values.GetValueOrDefault("m_value") is not (>= 1 and <= 3 and var level)) + return null; + if (!CompareSerializedInteger(detailLevel, comparison, level)) continue; + } + + var drawable = children.Where(index => c.QueueLinks[index].Field == "m_subNodes").ToArray(); + var geometries = drawable.Where(index => c.Queue[index].Cls == 2092).ToArray(); + if (drawable.Length != geometries.Length + curvesByFilter[filter].Count()) return null; + foreach (int geometry in geometries) + { + if (!c.ObjectGInfo.TryGetValue(c.Queue[geometry].V, out var geometryInfo) + || (geometryInfo.Flags & 0x20u) != 0 + || c.PlanMaskCandidates?.Where(candidate => c.QueueLinks[candidate.FaceIndex] == (geometry, "m_pFaces")) + .ToArray() is not [var candidate] + || !c.ObjectGInfo.TryGetValue((int)candidate.Handle, out var faceInfo) + || (faceInfo.Flags & (DisplaySurfaceBit | 0x20u)) != DisplaySurfaceBit + || !c.DirectSurfaceByFace.TryGetValue(candidate.Handle, out var surface) || surface.Kind != SurfKind.Plane + || Math.Abs(surface.X[2]) > 1e-9 || Math.Abs(surface.Y[2]) > 1e-9 + || !(loopsByFace ??= CompleteFaceLoops(c)).TryGetValue(candidate.Handle, out var loops)) + return null; + var segments = new List<(double[] A, double[] B)>(); + var loopEdges = new HashSet(); + if (TryOrderLoopRings(c, candidate.Handle, loops, edges ??= EdgesByHandle(c), ToPlane(surface), segments, loopEdges) is not { } rings) + return null; + if (rings is [var mask]) masks.Add(mask); + + var styles = loopEdges.Select(edge => c.ObjectGInfo.GetValueOrDefault((int)edge)).ToArray(); + if (styles.Any(style => (style.Flags & 0x20u) == 0)) + { + if (styles.Select(style => style.Category).Distinct().ToArray() is not [> 0 and int styleId] + || styles.Any(style => (style.Flags & 0x20u) != 0)) + return null; + lines.AddRange(segments.Select(segment => new StyledModelLine(segment.A, segment.B, styleId))); + } + } + + foreach (var item in curvesByFilter[filter]) + { + if ((item.Flags & 0x20u) != 0) continue; + if (item.Filled || item.StyleId <= 0 || !c.Curves.TryGetValue(item.Handle, out var curve) + || !IsPlanCutCurve(curve) || (curve.RY != 0 && (!IsFinite(curve.RY) || curve.RY < 0))) + return null; + var parameters = curve.R == 0 ? [curve.T0, curve.T1] + : RefineAngularSamples([curve.T0, curve.T1], Math.Max(curve.R, curve.RY)); + var start = curve.Eval(parameters[0]); + if (!start.All(IsFinite)) return null; + foreach (double parameter in parameters.Skip(1)) + { + var end = curve.Eval(parameter); + if (!end.All(IsFinite)) return null; + if (!start.SequenceEqual(end)) lines.Add(new(start, end, item.StyleId)); + start = end; + } + } + } + return lines.Count == 0 ? null : new(lines, masks); + } + + internal static List> ReadPlanFixtureMasks(Cur c) + { + var masks = new List>(); + if (c.PlanMaskCandidates == null) return masks; + var loopsByFace = CompleteFaceLoops(c); + var edges = EdgesByHandle(c); + foreach (var (faceIndex, face) in c.PlanMaskCandidates) + { + if (c.QueueLinks[faceIndex] is not (>= 0 and int geometry, "m_pFaces") + || c.Queue[geometry].Cls != 2092 + || !c.ObjectGInfo.TryGetValue(c.Queue[geometry].V, out var geometryInfo) + || (geometryInfo.Flags & 0x20u) != 0 + || c.QueueLinks[geometry] is not (>= 0 and int filter, "m_subNodes") + || c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes") + || !c.ObjectGInfo.TryGetValue(c.Queue[filter].V, out var filterInfo) || (filterInfo.Flags & 0x20u) != 0 + || c.QueueChildren.GetValueOrDefault(filter)?.Where(i => c.QueueLinks[i].Field == "m_oConditions").ToArray() + is not [int condition] || c.Queue[condition].Cls != 1996 || !IsTopPlanCondition(c, condition, out _) + || !c.DirectSurfaceByFace.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane + || Math.Abs(surface.X[2]) > 1e-9 || Math.Abs(surface.Y[2]) > 1e-9 + || loopsByFace.GetValueOrDefault(face) is not { Count: 1 } loops + || TryOrderLoopRings(c, face, loops, edges, ToPlane(surface), [], []) is not [var ring]) + continue; + masks.Add(ring); + } + return masks; + } + + private static bool IsPlanCutCurve(ArcRec curve) + { + if (!IsFinite(curve.T0) || !IsFinite(curve.T1) || curve.T1 <= curve.T0 + || !curve.C.All(IsFinite) || !curve.X.All(IsFinite) || Math.Abs(curve.X[2]) > 1e-9) + return false; + if (curve.R == 0) return curve.X[0] != 0 || curve.X[1] != 0; + return curve.R > 0 && curve.T1 - curve.T0 <= Math.Tau + 1e-9 + && curve.Y.All(IsFinite) && Math.Abs(curve.Y[2]) <= 1e-9 + && Math.Abs(curve.X[0] * curve.X[0] + curve.X[1] * curve.X[1] - 1) <= 1e-9 + && Math.Abs(curve.Y[0] * curve.Y[0] + curve.Y[1] * curve.Y[1] - 1) <= 1e-9 + && Math.Abs(curve.X[0] * curve.Y[0] + curve.X[1] * curve.Y[1]) <= 1e-9; + } + + internal static List? ReadViewFacingLines(Cur c) + { + if (c.ViewLineCandidates == null) return null; + // shortcut: require matching opposite elevation filters until asymmetric direction modes are decoded. + var alternatives = new List<(int Tag, int Side, ViewFacingLine Line)>(); + foreach (var (index, tag, style, curve) in c.ViewLineCandidates) + { + int filter = c.QueueLinks[index].ParentQueueIndex; + var conditions = c.QueueChildren.GetValueOrDefault(filter)?.Where(i => + i < c.QueueLinks.Count && c.QueueLinks[i].Field == "m_oConditions").ToArray(); + if (conditions is not ({ Length: 1 } or { Length: 2 })) continue; + int direction = conditions.FirstOrDefault(i => c.Queue[i].Cls == 1996, -1); + if (direction < 0) continue; + int side = c.QueueInts.GetValueOrDefault(direction)?.GetValueOrDefault("m_comp") ?? 0; + if (side is not (6 or 7) + || c.QueueBytes.GetValueOrDefault(direction)?.GetValueOrDefault("m_negateDirCondition") is not [0] + || c.QueueDoubles.GetValueOrDefault(direction)?.GetValueOrDefault("m_dir") is not { Count: 3 } axis + || Normalize(axis.ToArray()) is not { } unitAxis) continue; + (int Comparison, int Level)? detailCondition = null; + if (conditions.Length == 2) + { + int detail = conditions.FirstOrDefault(i => c.Queue[i].Cls == 1999, -1); + if (detail < 0 || c.QueueInts.GetValueOrDefault(detail) is not { } level + || level.GetValueOrDefault("m_param") != 3 + || !level.TryGetValue("m_comp", out int comparison) || comparison is < -1 or > 5 + || !level.TryGetValue("m_value", out int detailLevel) || detailLevel is < 1 or > 3) continue; + detailCondition = (comparison, detailLevel); + } + var start = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T0 * curve.X[i]).ToArray(); + var end = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T1 * curve.X[i]).ToArray(); + if (!start.All(IsFinite) || !end.All(IsFinite) || start.SequenceEqual(end)) continue; + alternatives.Add((tag, side, new(start, end, unitAxis, style, detailCondition))); + } + var result = new List(); + foreach (var group in alternatives.GroupBy(item => (item.Tag, item.Line.StyleId))) + { + if (group.OrderBy(item => item.Side).ToArray() is not [{ Side: 6, Line: var a }, { Side: 7, Line: var b }]) continue; + if (a.DetailCondition != b.DetailCondition || !a.Axis.SequenceEqual(b.Axis) + || !SameProjection(a.Start, b.Start, a.Axis, out double startSpacing) + || !SameProjection(a.End, b.End, a.Axis, out double endSpacing) + || Math.Abs(startSpacing - endSpacing) > 1e-9) continue; + var reverse = a.Axis.Select(value => -value).ToArray(); + result.Add(a with { Axis = startSpacing >= 0 ? reverse : a.Axis }); + result.Add(b with { Axis = startSpacing >= 0 ? a.Axis : reverse }); + } + return result.Count == 0 ? null : result; + + static bool SameProjection(double[] a, double[] b, double[] axis, out double spacing) + { + double x = a[0] - b[0], y = a[1] - b[1], z = a[2] - b[2]; + spacing = x * axis[0] + y * axis[1] + z * axis[2]; + return Math.Abs(x - spacing * axis[0]) <= 1e-9 && Math.Abs(y - spacing * axis[1]) <= 1e-9 + && Math.Abs(z - spacing * axis[2]) <= 1e-9; + } + } + /// /// Plausibility gate for the 3x3 part of a serialized GInstance placement (InstanceInfo.m_Trf), /// which also rejects a misparsed record. @@ -2214,7 +2617,8 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) case 0x04: { int value = c.U32(); - bool captureModelCondition = c.CurrentObjectClass is 1999 or 2002; + bool captureModelCondition = c.CurrentObjectClass is 1999 or 2002 + || c.RootClass == 2007 && (c.CurrentObjectClass is 1995 or 1996) && f.Name == "m_comp"; if (c.CurrentQueueIndex >= 0 && ((c.Debug && c.CurrentObjectClass is >= 1992 and <= 2015) || captureModelCondition)) @@ -2229,7 +2633,11 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) case 0x07: { double value = c.F64(); - if (c.Debug && c.CurrentQueueIndex >= 0 && c.CurrentObjectClass is >= 1992 and <= 2003) + if (c.CurrentQueueIndex >= 0 && (c.Debug && c.CurrentObjectClass is >= 1992 and <= 2003 + || c.RootClass == 2007 && c.CurrentObjectClass == 1995 + && f.Name is "m_dir" or "m_rangeLo" or "m_rangeHi" + || c.CurrentObjectClass == 1996 && f.Name == "m_dir" + && c.QueueInts.GetValueOrDefault(c.CurrentQueueIndex)?.GetValueOrDefault("m_comp") is 6 or 7 or 8)) { if (!c.QueueDoubles.TryGetValue(c.CurrentQueueIndex, out var values)) c.QueueDoubles[c.CurrentQueueIndex] = values = new(); @@ -2314,7 +2722,9 @@ private static void Enqueue(Cur c, ushort cls, int handle, string field) int childIndex = c.Queue.Count; c.Queue.Add((cls, handle)); c.QueueLinks.Add((c.CurrentQueueIndex, field)); - if (c.CurrentQueueIndex >= 0 && (c.Debug || field == "m_oConditions")) + if (c.CurrentQueueIndex >= 0 && (c.Debug || field == "m_oConditions" + || c.RootClass == 2007 && !c.IncludeNonVisible && field == "m_subNodes" + && c.CurrentObjectClass == 2015 && c.QueueLinks[c.CurrentQueueIndex] == (-1, "m_subNodes"))) { if (!c.QueueChildren.TryGetValue(c.CurrentQueueIndex, out var children)) c.QueueChildren[c.CurrentQueueIndex] = children = new(); @@ -2750,6 +3160,10 @@ void AddFractions(double start, double end, // and a node it does not take is marked with a negative id (the faces stay in the geometry // for every other consumer): see ResolveGeometryNodes. var geometryNodeByFace = ResolveGeometryNodes(c.Queue, c.QueueLinks, c.ObjectGInfo, c.IncludeNonVisible); + var excludedFromTopPlan = c.RootClass == 2007 && c.Pos == c.End + ? geometryNodeByFace.Values.Select(owner => owner.Node).Where(node => node != 0) + .Distinct().Where(node => ExcludesTopPlan(c, Math.Abs(node) - 1)).ToHashSet() + : []; foreach (uint handle in inactiveBodyFaceHandles) { if (!c.DirectSurfaceByFace.TryGetValue(handle, out var surface) || surface.Kind == SurfKind.Unknown @@ -2830,9 +3244,11 @@ void AddFace(uint handle, GRepFace face) face = boundedFace with { SourceFace = handle, GeometryNode = faceNode, + ExcludedFromTopPlan = excludedFromTopPlan.Contains(faceNode), NodeOrder = faceNode != 0 ? nodeOrders.GetValueOrDefault(Math.Abs(faceNode) - 1) : 0, GeometryStyle = faceStyle, GInfoFlags = c.ObjectGInfo.TryGetValue((int)handle, out var faceGInfo) ? faceGInfo.Flags : null, + ModelPattern = PlacedFacePattern(c, handle), MeshEdgeBounds = meshEdgeBounds.GetValueOrDefault(handle), // (the circular Edges of the loops the face was built from; the others are // leftovers of an earlier state of the join) @@ -3233,6 +3649,33 @@ bool InCore(List poly) && !chainFaces.Contains(edge.FaceA) && !chainFaces.Contains(edge.FaceB)) .Select(edge => (edge.FaceA, edge.FaceB)))); + // Paint regions carry material and trim loops. Keep them with the parent without adding shell faces. + if (regionFaces.Count > 0) + { + for (int index = 0; index < c.QueueLinks.Count; index++) + { + if (c.QueueLinks[index] is not (>= 0 and int parentIndex, "m_faceRegions") + || c.Queue[index] is not (1589, > 0 and int handle) + || c.Queue[parentIndex] is not (1589, > 0 and int parent) + || deadFaces.Contains((uint)handle) + || !faceIndicesByHandle.TryGetValue((uint)parent, out var indices) + || c.FaceRenderStyle.GetValueOrDefault((uint)handle) is not (> 0 and int material) + || !c.DirectSurfaceByFace.TryGetValue((uint)handle, out var surface) || surface.Kind != SurfKind.Plane + || !loopsByFace.TryGetValue((uint)handle, out var loops) + || TryOrderLoopRings(c, (uint)handle, loops, edgeByHandle ??= EdgesByHandle(c), + ToPlane(surface), [], []) is not { } rings) continue; + + var regions = ClassifyCoplanarRings(rings) + .Select(region => new SurfaceMaterialRegion(material, region.Outer, region.Holes)).ToList(); + foreach (int faceIndex in indices) + { + var face = gd.Faces[faceIndex]; + if (face.PlaneSurface && regions.Count > 0) + (face.SurfaceRegions ??= []).AddRange(regions); + } + } + } + int polyMeshFaceCount = AppendPolyMeshes(gd, c); gd.BoundingBox = authoritativeBounds is { Length: 6 } ? (double[])authoritativeBounds.Clone() @@ -3801,6 +4244,7 @@ private static int AppendPolyMeshes(GRepData target, Cur c) Origin = vertices[0], XVector = normal, RenderStyleId = meshMaterial, + PolygonMesh = true, }); AddEdge(a, b); AddEdge(b, d); diff --git a/src/RvtIO/Parsing/NativeFieldParameters.cs b/src/RvtIO/Parsing/NativeFieldParameters.cs index 05962e36..5d2154a5 100644 --- a/src/RvtIO/Parsing/NativeFieldParameters.cs +++ b/src/RvtIO/Parsing/NativeFieldParameters.cs @@ -369,7 +369,10 @@ internal static class NativeFieldParameters new(-1006630, StorageType.Integer, "3703:m_showArrowheadToCutMark", ["3703"], null), // Show Arrowhead to Cut Mark new(-1006625, StorageType.Double, "3703:m_distanceToCutMark", ["3703"], null), // Distance to Cut Mark new(-1006623, StorageType.ElementId, "3703:m_arrowheadTypeId", ["3703"], null), // Arrowhead Type + new(-1006621, StorageType.Double, "974:m_cutMarkSymbolSize", ["974"], null), // Cut Mark Symbol Size new(-1006620, StorageType.Integer, "974:m_cutLineType", ["974"], null), // Cut Line Type + new(-1006619, StorageType.Double, "974:m_rotationAngle", ["974"], null), // Cut Line Angle + new(-1006618, StorageType.Double, "974:m_extensionDistanceToBoundary", ["974"], null), // Cut Line Extension new(-1006616, StorageType.Integer, "974:m_cutMarkSymbol", ["974"], null), // Cut Mark Symbol new(-1006525, StorageType.String, "174:m_prefix", ["174/-2000150", "174/None"], null), // Dimension Prefix new(-1006523, StorageType.Integer, "174:m_interiorTickMarkDisplay", ["174/-2000150", "174/None"], null), // Interior Tick Mark Display diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index 3a01bb8c..820c9df5 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -41,6 +41,7 @@ internal static class PartitionFraming internal sealed record Framed(IReadOnlyList Segments, List Items, int IdWidth, int? Partition = null) { private long[]? starts; + internal List<(string Key, ProjectItem Item)>? FamilyAnnotationItems { get; init; } /// Where the bytes of the item are: in its segment when it lies in one, else in a copy (an item can run into the next segment /// of its chain); Copied tells which. diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs b/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs new file mode 100644 index 00000000..ef7228d4 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs @@ -0,0 +1,32 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private const int BreakReferenceCount = 20; + + internal sealed record BreakLineProfile(IReadOnlyList<(double X, double Y)> Line, double MaskY); + + // The computed M_Break Line symbol's reference faces carry the stretched extents and the + // reference planes for the six vertices. The profile is used only for that family. + internal static BreakLineProfile? ReadBreakReferencePlanes(ReadOnlySpan data) + { + const int planeSize = 105; + if (data.Length < BreakReferenceCount * planeSize) return null; + Span x = stackalloc double[BreakReferenceCount]; + Span y = stackalloc double[BreakReferenceCount]; + for (int i = 0; i < BreakReferenceCount; i++) + { + var plane = data.Slice(i * planeSize, planeSize); + if (plane[32] != 1) return null; + x[i] = BitConverter.ToDouble(plane[33..]); + y[i] = BitConverter.ToDouble(plane[41..]); + if (!(Math.Abs(x[i]) < 1000 && Math.Abs(y[i]) < 1000 + && Math.Abs(BitConverter.ToDouble(plane[49..])) < 1e-7)) return null; + } + if (!(x[0] < x[14] && x[14] < x[19] && x[19] < 0 + && 0 < x[18] && x[18] < x[15] && x[15] < x[2])) return null; + if (!(Math.Abs(y[9]) < 1e-7 && Math.Abs(y[16] + y[17]) < 1e-7 + && Math.Abs(y[16]) > 1e-7 && Math.Abs(y[13]) > Math.Abs(y[16]))) return null; + return new([(x[0], 0), (x[14], 0), (x[19], y[16]), (x[18], y[17]), (x[15], 0), (x[2], 0)], y[13]); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs b/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs new file mode 100644 index 00000000..17e574ea --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs @@ -0,0 +1,218 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record DatumLeader(double[] End, double[] Elbow, double[] Anchor); + internal sealed record DatumExtent(double FreeEnd, double BubbleEnd, byte Overrides, DatumLeader? BubbleLeader, + double? FreeEnd3d = null, double? BubbleEnd3d = null, DatumLeader? FreeEndLeader = null); + internal sealed record ViewDatumExtents(int ViewId, double[] Normal, Dictionary Datums, + IReadOnlyDictionary? Sections = null); + internal sealed record SectionTraceExtent(double Start, double End, int SegmentCount); + internal sealed record DatumHead(int SymbolId, int GridBubblePosition, double? EndSegmentLength = null, + bool? BubbleAtEnd1 = null, bool? BubbleAtEnd2 = null); + + internal static DatumHead? ExtractDatumHead(byte[] data, int start, uint size, ushort classId) + { + if (classId is not (2109 or 2301) || start < 0 || size > int.MaxValue + || (long)start + 16 + size > data.Length || size < 6 + || BitConverter.ToUInt32(data, start + 8) != size + || BitConverter.ToUInt16(data, start + 12) != classId) return null; + int end = start + 12 + (int)size; + if (BitConverter.ToUInt32(data, end) != size) return null; + var fields = SerializationFields(classId); + if (fields == null || !HasExactSchemaField(fields, classId, "m_familyTagId", 14, 0, 20)) return null; + var cursor = new Cursor { D = data, Pos = start + 14, End = end, RootClassId = classId }; + var queue = new List<(ushort Cls, uint Id)>(); + int owner = -1, symbol = -1, position = -1; + double? endLength = null; + bool? end1 = null, end2 = null; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_id", Type: 14, Mods: 0, Ref: 20 }) owner = ReadI32(cursor); + else if (field.Declaring == classId && field is { Name: "m_familyTagId", Type: 14, Mods: 0, Ref: 20 }) + symbol = ReadI32(cursor); + else if (field is { Declaring: 2109, Name: "m_bubbleLocInElev", Type: 4, Mods: 0 }) + position = ReadI32(cursor); + else if (field is { Declaring: 2109, Name: "m_endSegmentsLength", Type: 7, Mods: 0 }) + endLength = ReadF64(cursor); + else if (field is { Declaring: 2109, Name: "m_bubbleAtEnd1" or "m_bubbleAtEnd2", Type: 1, Mods: 0 }) + { + if (!TryReadFlag(cursor, field, out bool visible)) throw Fail; + if (field.Name == "m_bubbleAtEnd1") end1 = visible; + else end2 = visible; + } + else ReadField(cursor, field, queue, 0, null); + } + } + catch (DecodeFail) { return null; } + return owner > 0 && (uint)owner == BitConverter.ToUInt32(data, start) && symbol > 0 + ? new DatumHead(symbol, position, endLength, end1, end2) : null; + } + + internal static ViewDatumExtents? ExtractViewDatumExtents(byte[] data, int start, uint size, ushort classId) + { + const ushort extentElement = 1471, datumRecord = 1054, leaderRecord = 622, sectionRecord = 886; + if (classId != extentElement || start < 0 || size > int.MaxValue + || (long)start + 16 + size > data.Length || size < 6 + || BitConverter.ToUInt32(data, start + 8) != size + || BitConverter.ToUInt16(data, start + 12) != classId) return null; + int end = start + 12 + (int)size; + if (BitConverter.ToUInt32(data, end) != size) return null; + + var fields = SerializationFields(classId); + if (fields == null || !HasExactSchemaField(fields, extentElement, "m_idExtents", 14, 80, null) + || !HasExactSchemaField(fields, extentElement, "m_dbViewId", 14, 0, 20) + || !HasExactSchemaField(fields, 37, "m_id", 14, 0, 20)) return null; + var cursor = new Cursor { D = data, Pos = start + 14, End = end, RootClassId = classId }; + var queue = new List<(ushort Cls, uint Id)>(); + var datumIndices = new Dictionary(); + var sectionIndices = new Dictionary(); + var sections = new Dictionary(); + var leaders = new Dictionary(); + var records = new Dictionary(); + double[]? normal = null; + int viewId = -1, owner = -1; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_id" }) owner = ReadI32(cursor); + else if (field is { Declaring: extentElement, Name: "m_dbViewId" }) viewId = ReadI32(cursor); + else if (field is { Declaring: extentElement, Name: "m_dbViewNorm", Type: 7, Mods: 16, Cnt: 3 }) + normal = ReadPoint(); + else if (field is { Declaring: extentElement, Name: "m_idExtents" }) + { + uint count = ReadU32(cursor); + if (count > 10_000) return null; + for (int i = 0; i < count; i++) + { + int datumId = ReadI32(cursor); + int index = queue.Count; + ReadPoly(cursor, queue); + if (queue.Count != index + 1) continue; + if (queue[index].Cls == datumRecord) datumIndices.Add(index, datumId); + if (queue[index].Cls == sectionRecord) sectionIndices.Add(index, datumId); + } + } + else ReadField(cursor, field, queue, 0, null); + } + if (owner <= 0 || (uint)owner != BitConverter.ToUInt32(data, start) + || viewId <= 0 || normal == null || !normal.All(double.IsFinite) + || (datumIndices.Count == 0 && sectionIndices.Count == 0)) return null; + + for (int i = 0; i < queue.Count; i++) + { + if (datumIndices.TryGetValue(i, out int id)) + { + double free = double.NaN, bubble = double.NaN; + double? free3d = null, bubble3d = null; + byte overrides = 0; + int recordViewId = -1; + bool supported = true; + foreach (var field in SerializationFields(datumRecord) ?? throw Fail) + { + if (field is { Name: "m_freeEnd", Type: 7, Mods: 0 }) free = ReadF64(cursor); + else if (field is { Name: "m_bubbleEnd", Type: 7, Mods: 0 }) bubble = ReadF64(cursor); + else if (field is { Name: "m_freeEnd3d", Type: 7, Mods: 0 }) free3d = ReadF64(cursor); + else if (field is { Name: "m_bubbleEnd3d", Type: 7, Mods: 0 }) bubble3d = ReadF64(cursor); + else if (field is { Name: "m_dbViewId", Type: 14, Mods: 0, Ref: 20 }) recordViewId = ReadI32(cursor); + else if (field is { Name: "m_endBubbleOverrides", Type: 2, Mods: 0 }) + { + if (!cursor.Take(1)) throw Fail; + overrides = data[cursor.Pos - 1]; + } + else if (field is { Name: "m_pLeader" or "m_pFreeEndLeader" }) + { + int index = queue.Count; + uint pointer = ReadPoly(cursor, queue); + if (pointer == 0) continue; + if (queue.Count == index + 1 && queue[index].Cls == leaderRecord) + leaders.Add(index, (id, field.Name == "m_pFreeEndLeader")); + else supported = false; + } + else ReadField(cursor, field, queue, 1, null); + } + if (supported && id > 0 && (recordViewId == -1 || recordViewId == viewId) + && double.IsFinite(free) && double.IsFinite(bubble) + && !records.TryAdd(id, new DatumExtent(free, bubble, overrides, null, free3d, bubble3d))) return null; + } + else if (leaders.TryGetValue(i, out var ownership)) + { + double[]? tip = null, elbow = null, anchor = null; + foreach (var field in SerializationFields(leaderRecord) ?? throw Fail) + { + if (field is { Name: "m_end", Type: 7, Mods: 16, Cnt: 3 }) tip = ReadPoint(); + else if (field is { Name: "m_elbow", Type: 7, Mods: 16, Cnt: 3 }) elbow = ReadPoint(); + else if (field is { Name: "m_anchor", Type: 7, Mods: 16, Cnt: 3 }) anchor = ReadPoint(); + else ReadField(cursor, field, queue, 1, null); + } + if (tip == null || elbow == null || anchor == null + || !tip.All(double.IsFinite) || !elbow.All(double.IsFinite) || !anchor.All(double.IsFinite)) return null; + if (records.TryGetValue(ownership.DatumId, out var record)) + { + var leader = new DatumLeader(tip, elbow, anchor); + records[ownership.DatumId] = ownership.FreeEnd + ? record with { FreeEndLeader = leader } : record with { BubbleLeader = leader }; + } + } + else if (queue[i].Cls == sectionRecord) + { + uint segments = 0; + bool continuous = true, hideLine = true; + double startExtent = double.NaN, endExtent = double.NaN; + double startUncropped = double.NaN, endUncropped = double.NaN; + int head = 0, tail = 0; + foreach (var field in SerializationFields(sectionRecord) ?? throw Fail) + { + if (field is { Name: "m_endVisLengths", Type: 13, Mods: 80 }) + { + segments = ReadU32(cursor); + if (segments == uint.MaxValue) segments = 0; + if (segments > 10_000) throw Fail; + for (int segment = 0; segment < segments; segment++) + { + double first = ReadF64(cursor), last = ReadF64(cursor); + continuous &= first == -1 && last == -1; + } + } + else if (field is { Name: "m_horzExtents", Type: 7, Mods: 16, Cnt: 2 }) + { + startUncropped = ReadF64(cursor); + endUncropped = ReadF64(cursor); + } + else if (field is { Name: "m_croppedHorzExtents", Type: 7, Mods: 16, Cnt: 2 }) + { + startExtent = ReadF64(cursor); + endExtent = ReadF64(cursor); + } + else if (field is { Name: "m_end1Mark", Type: 4, Mods: 0 }) head = ReadI32(cursor); + else if (field is { Name: "m_end2Mark", Type: 4, Mods: 0 }) tail = ReadI32(cursor); + else if (field is { Name: "m_hideLine", Type: 1, Mods: 0 }) + { + if (!TryReadFlag(cursor, field, out hideLine)) throw Fail; + } + else ReadField(cursor, field, queue, 1, null); + } + // A straight trace can supply only the first cropped endpoint. Use its saved uncut + // end when the second cropped coordinate is zero and the two start coordinates agree. + if (segments == 1 && startExtent == startUncropped && endExtent == 0 && startExtent >= endExtent) + endExtent = endUncropped; + // Continuous traces with the head on the first leg and the tail on the last. + if (sectionIndices.TryGetValue(i, out int sectionId) && sectionId > 0 + && continuous && !hideLine && head == 1 && tail == 2 && segments > 0 + && double.IsFinite(startExtent) && double.IsFinite(endExtent) && startExtent < endExtent + && !sections.TryAdd(sectionId, new SectionTraceExtent(startExtent, endExtent, (int)segments))) + return null; + } + else SkipQueuedObjects(cursor, queue, i + 1, i); + } + } + catch (DecodeFail) { return null; } + return cursor.Pos == end && (records.Count > 0 || sections.Count > 0) + ? new ViewDatumExtents(viewId, normal, records, sections) : null; + + double[] ReadPoint() => [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs new file mode 100644 index 00000000..46fad3f8 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs @@ -0,0 +1,22 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static double[] ReadStoredPoint(Cursor cursor) => [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + + private static (double[] Origin, double[] Direction)? ReadDimensionLine(Cursor cursor, + IReadOnlyList fields, List<(ushort, uint)> queue) + { + double[]? origin = null, direction = null; + foreach (var field in fields) + { + if (field is { Declaring: 1736, Name: "m_origin", Type: 7, Mods: 16, Cnt: 3 }) + origin = ReadStoredPoint(cursor); + else if (field is { Declaring: 1736, Name: "m_dirVec", Type: 7, Mods: 16, Cnt: 3 }) + direction = ReadStoredPoint(cursor); + else + ReadField(cursor, field, queue, 1, null); + } + return origin != null && direction != null ? (origin, direction) : null; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs new file mode 100644 index 00000000..91667c2c --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs @@ -0,0 +1,13 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static HashSet ReadViewIdSet(Cursor cursor) + { + int count = ReadI32(cursor); + if (count is < -1 or > 1_000_000 || count * 4L > cursor.End - cursor.Pos) throw Fail; + var hidden = new HashSet(); + for (int i = 0; i < count; i++) hidden.Add(ReadI32(cursor)); + return hidden; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs new file mode 100644 index 00000000..0527280a --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs @@ -0,0 +1,37 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record PlanNoteLeader(double[] End, double[] Elbow, double[] Anchor); + + private static (string Text, double? FontSizePoints)? ReadPlanNoteRtf(Cursor cursor, + IReadOnlyList fields) + { + if (fields is not [{ Declaring: 3487, Name: "m_arrRtfStream", Type: 2, Mods: 80 }]) throw Fail; + int count = ReadI32(cursor); + if (count is -1 or 0) return null; + int start = cursor.Pos; + if (count is < 0 or > 1_048_576 || !cursor.Take(count)) throw Fail; + return RtfText.Parse(cursor.D, start, cursor.Pos); + } + + private static PlanNoteLeader? ReadPlanNoteLeader(Cursor cursor, IReadOnlyList fields, + List<(ushort, uint)> queue) + { + double[]? end = null, elbow = null, anchor = null; + int type = -1; + foreach (var field in fields) + { + if (field is { Declaring: 622, Name: "m_end", Type: 7, Mods: 16, Cnt: 3 }) end = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_elbow", Type: 7, Mods: 16, Cnt: 3 }) elbow = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_anchor", Type: 7, Mods: 16, Cnt: 3 }) anchor = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_type", Type: 4, Mods: 0 }) type = ReadI32(cursor); + else ReadField(cursor, field, queue, 1, null); + } + return type == 1 && end != null && elbow != null && anchor != null + && ValidPoint(end) && ValidPoint(elbow) && ValidPoint(anchor) + ? new(end, elbow, anchor) : null; + + static bool ValidPoint(double[] point) => point.All(value => Math.Abs(value) < 1_000_000); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs new file mode 100644 index 00000000..710cb759 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs @@ -0,0 +1,94 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record FamilyAnnotationArc(double X, double Y, double Radius, double Start, double End, int StyleId); + + internal static (TitleBlockLine? Line, FamilyAnnotationArc? Arc, bool TypeDependent, int SketchId)? + ReadFamilyAnnotationCurve(byte[] data, int start, uint size) + { + var fields = SerializationFields(838); + if (fields == null || size < 6 || start < 0 || (long)start + size + 16 > data.Length + || BitConverter.ToUInt16(data, start + 12) != 838 + || BitConverter.ToUInt32(data, start + 12 + (int)size) != size) return null; + var queue = new List<(ushort Cls, uint Id)>(); + var cursor = new Cursor + { + D = data, Pos = start + 14, End = start + 12 + (int)size, RootClassId = 838, TailWalk = true, RootQueue = queue + }; + int driver = -1, curve = -1, sketch = -1; + try + { + foreach (var field in fields) + { + int next = queue.Count; + ReadField(cursor, field, queue, 0, null); + if (field is { Declaring: 838, Name: "m_pCurveDriver", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 929) + driver = next; + } + if (driver < 0) return null; + for (int i = 0; i < queue.Count; i++) + { + if (i == curve) + { + bool typeDependent = queue.Any(entry => entry.Cls == 1806); + if (queue[i].Cls == 1974) + return ReadFamilyAnnotationArc(cursor) is { } arc ? (null, arc, typeDependent, sketch) : null; + if (!TryReadGLine(cursor, queue, i, out var line) || (line.Flags & 0x20) != 0) return null; + double x0 = line.Ox + line.T0 * line.Dx, y0 = line.Oy + line.T0 * line.Dy; + double x1 = line.Ox + line.T1 * line.Dx, y1 = line.Oy + line.T1 * line.Dy; + if (x0 == x1 && y0 == y1 + || !(Math.Abs(line.Oz + line.T0 * line.Dz) < 1e-8 + && Math.Abs(line.Oz + line.T1 * line.Dz) < 1e-8)) return null; + return Math.Abs(x0) < 1 && Math.Abs(x1) < 1 && Math.Abs(y0) < 1 && Math.Abs(y1) < 1 + ? (new(x0, y0, x1, y1, line.CategoryId), null, typeDependent, sketch) : null; + } + cursor.TailClassId = queue[i].Cls; + foreach (var field in SerializationFields(queue[i].Cls) ?? throw Fail) + { + int next = queue.Count; + if (queue[i].Cls == 3606 && field is { Declaring: 422, Name: "m_groupId", Type: 14, Mods: 0, Ref: 20 }) + sketch = ReadI32(cursor); + else ReadField(cursor, field, queue, 1, null); + if (i == driver && field is { Declaring: 87, Name: "m_pCrv" } + && queue.Count == next + 1 && queue[next].Cls is 1736 or 1974) + curve = next; + } + } + } + catch (DecodeFail) { return null; } + return null; + } + + private static FamilyAnnotationArc? ReadFamilyAnnotationArc(Cursor cursor) + { + if (SerializationFields(1974) is not { Count: 7 } fields + || fields[0] is not { Declaring: 1246, Name: "m_GInfo", Type: 14, Mods: 0 } + || fields[1] is not { Declaring: 1737, Name: "m_endParams", Type: 7, Mods: 16, Cnt: 2 } + || fields[2] is not { Declaring: 1974, Name: "m_xVec", Type: 7, Mods: 16, Cnt: 3 } + || fields[3] is not { Declaring: 1974, Name: "m_yVec", Type: 7, Mods: 16, Cnt: 3 } + || fields[4] is not { Declaring: 1974, Name: "m_radius", Type: 7, Mods: 0 } + || fields[5] is not { Declaring: 1974, Name: "m_center", Type: 7, Mods: 16, Cnt: 3 } + || fields[6] is not { Declaring: 1974, Name: "m_bFilled", Type: 1, Mods: 0 } + || !cursor.Take(8)) return null; + int styleId = ReadI32(cursor); + uint flags = ReadU32(cursor); + double start = ReadF64(cursor), end = ReadF64(cursor); + double xx = ReadF64(cursor), xy = ReadF64(cursor), xz = ReadF64(cursor); + double yx = ReadF64(cursor), yy = ReadF64(cursor), yz = ReadF64(cursor); + double radius = ReadF64(cursor); + double x = ReadF64(cursor), y = ReadF64(cursor), z = ReadF64(cursor); + if (!cursor.Take(1) || cursor.D[cursor.Pos - 1] != 0 || (flags & 0x20) != 0 + || !(radius is > 0 and < 1) || !(Math.Abs(x) < 1 && Math.Abs(y) < 1) + || z != 0 || xz != 0 || yz != 0 + || !(Math.Abs(xx * xx + xy * xy - 1) < 1e-8 && Math.Abs(yx * yx + yy * yy - 1) < 1e-8 + && Math.Abs(xx * yx + xy * yy) < 1e-8) + || !double.IsFinite(start) || !double.IsFinite(end) || !(end - start is >= 0 and <= 2 * Math.PI + 1e-8)) + return null; + if (start == end) end = start + 2 * Math.PI; + double angle = Math.Atan2(xy, xx), sign = Math.Sign(xx * yy - xy * yx); + return new(x, y, radius, (angle + sign * start) * (180 / Math.PI), + (angle + sign * end) * (180 / Math.PI), styleId); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs b/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs new file mode 100644 index 00000000..f5f7c84e --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs @@ -0,0 +1,31 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record RoomColorEntry(string Name, uint Color, int PatternId); + + private static List ReadRoomColorEntries(Cursor cursor) + { + uint count = ReadU32(cursor); + var colors = new List(); + if (count == uint.MaxValue) return colors; + if (count > 10_000) throw Fail; + for (uint i = 0; i < count; i++) + { + ReadString(cursor); // Caption is independent of the value used to select a room. + string name = ReadString(cursor); + ReadF64(cursor); + ReadI32(cursor); // ElementId and integer storage slots. + ReadI32(cursor); + int storage = ReadI32(cursor); + uint color = ReadU32(cursor); + int pattern = ReadI32(cursor); + if (!cursor.Take(6)) throw Fail; + var flags = cursor.D.AsSpan(cursor.Pos - 6, 6); + if (storage == 3 && name.Length > 0 && color <= 0xFFFFFF + && flags[0] == 0 && flags[3] == 0 && flags[5] == 0) + colors.Add(new RoomColorEntry(name, color, pattern)); + } + return colors; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs b/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs new file mode 100644 index 00000000..2ef9df73 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs @@ -0,0 +1,43 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed class ScheduleRowBindings + { + public readonly Dictionary Fields = new(); + public readonly Dictionary Sorts = new(); + public readonly Dictionary Filters = new(); + public List FieldIds = new(), FieldObjects = new(), SortObjects = new(), FilterObjects = new(); + public bool Itemized, InitialSpacer, Unsupported; + } + + private static bool ReadScheduleBindingField(ScheduleRowBindings bindings, Cursor cur, TfField field, List<(ushort, uint)> queue) + { + switch (field.Name) + { + case "m_pFields": bindings.FieldObjects = Pointers(); return true; + case "m_sortFieldArr": bindings.SortObjects = Pointers(); return true; + case "m_filterArr": bindings.FilterObjects = Pointers(); return true; + case "m_fieldIds": + uint count = ReadU32(cur); + if (count != uint.MaxValue) + { + if (count > 100_000) throw Fail; + for (uint i = 0; i < count; i++) bindings.FieldIds.Add(ReadI32(cur)); + } + return true; + case "m_bInstanceSchedule": bindings.Itemized = Flag(); return true; + case "m_showInitialSpacer": bindings.InitialSpacer = Flag(); return true; + case "m_bRefTable" or "m_bMaterialSchedule" or "m_bFilterBySheet" or "m_bIncludeLinkedFiles" + or "m_showGrandTotal" or "m_isEmbedded": + bindings.Unsupported |= Flag(); + return true; + default: return false; + } + + List Pointers() => TryReadPtrArray(cur, queue, field with { Mods = 1 }, out var indices, out _) + ? indices : throw Fail; + + bool Flag() => TryReadFlag(cur, field, out bool value) ? value : throw Fail; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs b/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs new file mode 100644 index 00000000..e7a3ee93 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs @@ -0,0 +1,88 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record SiteContour(double Elevation, bool Primary, List> Lines); + internal sealed record SiteContourLabelData(int SurfaceId, double[][] Positions, double[][] Directions); + + private static SiteContourLabelData? ReadSiteContourLabels(Cursor cursor, List fields, + List<(ushort, uint)> queue) + { + if (fields is not + [{ Name: "m_oAssocPropData" }, { Name: "m_textPos", Type: 13, Mods: 80 }, + { Name: "m_textDir", Type: 13, Mods: 80 }, { Name: "m_textDirPerp", Type: 13, Mods: 80 }, + { Name: "m_surfId", Type: 14, Mods: 0, Ref: 20 }, { Name: "m_curveStatus", Type: 4, Mods: 0 }, + { Name: "m_makePrimaryOnly", Type: 1, Mods: 0 }]) throw Fail; + + ReadField(cursor, fields[0], queue, 1, null); + var positions = Points(); + var directions = Points(); + var perpendiculars = Points(); + int surface = ReadI32(cursor), status = ReadI32(cursor); + if (!cursor.Take(1)) throw Fail; + return status == 0 && surface > 0 && positions.Length == directions.Length + && positions.Length == perpendiculars.Length ? new(surface, positions, directions) : null; + + double[][] Points() + { + uint count = ReadU32(cursor); + if (count == uint.MaxValue) return []; + if (count > 100_000 || count > (cursor.End - cursor.Pos) / 24) throw Fail; + var points = new double[count][]; + for (int i = 0; i < points.Length; i++) + { + points[i] = [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + if (points[i].Any(value => !(Math.Abs(value) < 1_000_000))) throw Fail; + } + return points; + } + } + + private static List ReadSiteContours(Cursor cursor) + { + // ContourManager owns an inline map of elevations to polyline wrappers and facet indices. + if (SerializationFields(845) is not + [{ Name: "first", Type: 7, Mods: 0 }, { Name: "second", Type: 14, Mods: 0 }] + || SerializationFields(846) is not + [{ Name: "m_arr", Type: 14, Mods: 80 }, { Name: "m_facets", Type: 4, Mods: 80 }, + { Name: "m_isPrimary", Type: 1, Mods: 0 }] + || SerializationFields(847) is not [{ Name: "m_arr", Type: 13, Mods: 80 }]) + throw Fail; + uint count = Count(cursor, 10_000); + var result = new List((int)count); + for (uint i = 0; i < count; i++) + { + double level = ReadF64(cursor); + if (!double.IsFinite(level)) throw Fail; + uint lines = Count(cursor, 100_000); + var curves = new List>((int)lines); + for (uint j = 0; j < lines; j++) + { + uint points = Count(cursor, 100_000); + if (points > (cursor.End - cursor.Pos) / 24) throw Fail; + var vertices = new List<(double X, double Y)>((int)points); + for (uint k = 0; k < points; k++) + { + double x = ReadF64(cursor), y = ReadF64(cursor), z = ReadF64(cursor); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000 && Math.Abs(z - level) < 1e-6)) + throw Fail; + vertices.Add((x, y)); + } + if (vertices.Count > 1) curves.Add(vertices); + } + uint facets = Count(cursor, 1_000_000); + if (!cursor.Take((int)facets * 4) || cursor.Pos == cursor.End) throw Fail; + byte primary = cursor.D[cursor.Pos++]; + if (primary > 1) throw Fail; + result.Add(new(level, primary == 1, curves)); + } + return result; + + static uint Count(Cursor cursor, uint limit) + { + uint count = ReadU32(cursor); + if (count == uint.MaxValue) return 0; + return count <= limit ? count : throw Fail; + } + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs b/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs new file mode 100644 index 00000000..4ac62ed2 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs @@ -0,0 +1,46 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static List<(double X, double Y)> ReadSitePropertyCurve(Cursor cur, ushort classId, + out (double X, double Y)? arcCenter) + { + arcCenter = null; + if (!cur.Take(16)) throw Fail; // Inline GInfo in the property segment's own curve. + double start = ReadF64(cur), end = ReadF64(cur); + if (!double.IsFinite(start) || !double.IsFinite(end) || start == end) throw Fail; + if (classId == 1736) + { + var origin = ReadPoint(); + var direction = ReadPoint(); + return [PointAt(start), PointAt(end)]; + + (double X, double Y) PointAt(double t) => (origin.X + t * direction.X, origin.Y + t * direction.Y); + } + + var xAxis = ReadPoint(); + var yAxis = ReadPoint(); + double radius = ReadF64(cur); + var center = ReadPoint(); + double sweep = end - start; + if (!cur.Take(1) || !(radius is > 0 and < 1_000_000) || Math.Abs(sweep) > 2 * Math.PI + 1e-7) + throw Fail; + if (xAxis.Z == 0 && yAxis.Z == 0) arcCenter = (center.X, center.Y); + int segments = (int)Math.Ceiling(Math.Abs(sweep) * 60 / Math.PI); + var points = new List<(double X, double Y)>(segments + 1); + for (int i = 0; i <= segments; i++) + { + double t = start + sweep * i / segments; + double cos = radius * Math.Cos(t), sin = radius * Math.Sin(t); + points.Add((center.X + cos * xAxis.X + sin * yAxis.X, center.Y + cos * xAxis.Y + sin * yAxis.Y)); + } + return points; + + (double X, double Y, double Z) ReadPoint() + { + double x = ReadF64(cur), y = ReadF64(cur), z = ReadF64(cur); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000 && Math.Abs(z) < 1_000_000)) throw Fail; + return (x, y, z); + } + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs b/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs index cba92601..fee46f6c 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs @@ -9,7 +9,10 @@ internal enum StairRunStyle { Sketched = 2, Straight = 3, Spiral = 4 } internal sealed record StairRunNumbers(double BottomElevation, double TopElevation, double ActualRunWidth, int BaseRiserIndex, int TopRiserIndex, int BeginWithRiser = -1, int EndWithRiser = -1); internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle Style, - StairPathDirection[] Directions, StairRunNumbers? Numbers = null); + StairPathDirection[] Directions, StairRunNumbers? Numbers = null, StairPlanInput? Plan = null); + internal readonly record struct StairPlanLine(double X1, double Y1, double X2, double Y2, double Elevation); + internal sealed record StairPlanInput(StairPlanLine[] Treads, StairPlanLine[] Left, StairPlanLine[] Right, + StairPlanLine[] Center); /// Own R22 StairsRun graph, exact FIFO and footer. getRunType checks the own CellList run cell; /// getStairsPath2D uses m_oRefCurvesArr[0], not the cell's base lines. Only Straight/Sketched runs and @@ -20,13 +23,15 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St var cursor = new Cursor { D = data, Pos = start + 14, End = checked((int)((long)start + 12 + size)), RootClassId = classId }; var queue = new List<(ushort Cls, uint Id)>(); int cellList = -1, cachedLoop = -1, cell = -1, stairId = 0; - int[]? cachedCurves = null; + int[]? cachedCurves = null, outlineLoops = null; + int firstTread = -1, pastLastTread = -1; + var planLoops = new Dictionary(); double bottom = double.NaN, top = double.NaN, width = double.NaN; int baseIndex = int.MinValue, topIndex = int.MinValue; int beginRiser = -1, endRiser = -1; var directions = new Dictionary(); - var finiteOrigins = new HashSet(); - var boundedLines = new HashSet(); + var origins = new Dictionary(); + var bounds = new Dictionary(); try { foreach (var field in SerializationFields(classId) ?? throw Fail) @@ -79,7 +84,15 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St || BitConverter.ToUInt16(data, position + 8) != 938 || queue.Count <= before || queue[before].Cls != 938) throw Fail; cachedLoop = before; + // The two projected open side paths follow the ten path/riser reference groups. + if (BitConverter.ToUInt32(data, position) == 12 && queue.Count - before == 12 + && queue.Skip(before).All(item => item.Cls == 938)) + outlineLoops = [before + 10, before + 11]; } + if (field is { Declaring: 3708, Name: "m_orderedNosingFront", Type: 14, Mods: 81, Ref: null } + && queue.Count > before && BitConverter.ToUInt32(data, position) == queue.Count - before + && queue.Skip(before).All(item => item.Cls == 938)) + (firstTread, pastLastTread) = (before, queue.Count); if (queue.Count > 100_000) throw Fail; } if (cellList < 0 || cachedLoop < 0 || stairId <= 0 || stairId == owner) throw Fail; @@ -140,6 +153,12 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St cachedCurves = Enumerable.Range(before, queue.Count - before).ToArray(); if (cachedCurves.Any(i => queue[i].Cls is not (1736 or 1974))) throw Fail; } + if (sourceField is { Declaring: 938, Name: "m_curves", Type: 14, Mods: 81, Ref: null } + && (index == cachedLoop || outlineLoops?.Contains(index) == true + || index >= firstTread && index < pastLastTread) + && queue.Count > before && BitConverter.ToUInt32(data, position) == queue.Count - before + && queue.Skip(before).All(item => item.Cls == 1736)) + planLoops.Add(index, Enumerable.Range(before, queue.Count - before).ToArray()); if (cls == 1736 && sourceField is { Declaring: 1736, Name: "m_dirVec", Type: 7, Mods: 16, Cnt: 3 }) { var direction = new StairPathDirection(BitConverter.ToDouble(data, position), @@ -148,28 +167,64 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St } if (cls == 1736 && sourceField is { Declaring: 1736, Name: "m_origin", Type: 7, Mods: 16, Cnt: 3 } && Enumerable.Range(0, 3).All(i => double.IsFinite(BitConverter.ToDouble(data, position + i * 8)))) - finiteOrigins.Add(index); + origins.Add(index, new(BitConverter.ToDouble(data, position), + BitConverter.ToDouble(data, position + 8), BitConverter.ToDouble(data, position + 16))); if (cls == 1736 && sourceField is { Declaring: 1737, Name: "m_endParams", Type: 7, Mods: 16, Cnt: 2 }) { double first = BitConverter.ToDouble(data, position), last = BitConverter.ToDouble(data, position + 8); - if (double.IsFinite(first) && double.IsFinite(last) && first < last) boundedLines.Add(index); + if (double.IsFinite(first) && double.IsFinite(last) && first < last) bounds.Add(index, (first, last)); } } } // A spiral run has arcs for a base line and no direction and stops the walk early; every other style needs bounded horizontal lines and the exact footer. bool spiral = cell >= 0 && queue[cell].Cls == 3723; if (cell < 0 || cachedCurves == null || !spiral && cursor.Pos != cursor.End - || !spiral && cachedCurves.Any(i => !directions.ContainsKey(i) || !finiteOrigins.Contains(i) || !boundedLines.Contains(i))) throw Fail; + || !spiral && cachedCurves.Any(i => !directions.ContainsKey(i) || !origins.ContainsKey(i) || !bounds.ContainsKey(i))) throw Fail; StairPathDirection[] path = spiral ? [] : cachedCurves.Select(i => directions[i]).ToArray(); if (path.Any(direction => !double.IsFinite(direction.X) || !double.IsFinite(direction.Y) || direction.Z != 0 || direction.X == 0 && direction.Y == 0)) throw Fail; var numbers = double.IsFinite(bottom) && double.IsFinite(top) && double.IsFinite(width) && baseIndex != int.MinValue && topIndex != int.MinValue ? new StairRunNumbers(bottom, top, width, baseIndex, topIndex, beginRiser, endRiser) : null; + StairPlanInput? plan = null; + if (!spiral && outlineLoops is [int left, int right] && pastLastTread - firstTread > 1 + && ReadPlanLines([left]) is { } leftSide && ReadPlanLines([right]) is { } rightSide) + { + int[] treadLoops = Enumerable.Range(firstTread, pastLastTread - firstTread).ToArray(); + if (treadLoops.All(loop => planLoops.TryGetValue(loop, out var lines) && lines.Length == 1) + && ReadPlanLines(treadLoops) is { } treads) + plan = new(treads, leftSide, rightSide, ReadPlanLines([cachedLoop]) ?? []); + } return new(owner, stairId, queue[cell].Cls switch { 3725 => StairRunStyle.Straight, 3723 => StairRunStyle.Spiral, _ => StairRunStyle.Sketched }, - path, numbers); + path, numbers, plan); } catch (DecodeFail) { return null; } catch (OverflowException) { return null; } + + StairPlanLine[]? ReadPlanLines(int[] loops) + { + var lines = new List(); + foreach (int loop in loops) + { + if (!planLoops.TryGetValue(loop, out var indices)) return null; + foreach (int index in indices) + { + if (ReadPlanLine(index) is not { } line) return null; + lines.Add(line); + } + } + return lines.ToArray(); + } + + StairPlanLine? ReadPlanLine(int index) + { + if (!origins.TryGetValue(index, out var p) || !directions.TryGetValue(index, out var v) + || v.Z != 0 || !bounds.TryGetValue(index, out var t)) return null; + var line = new StairPlanLine(p.X + t.First * v.X, p.Y + t.First * v.Y, + p.X + t.Last * v.X, p.Y + t.Last * v.Y, p.Z); + return double.IsFinite(line.X1) && double.IsFinite(line.Y1) + && double.IsFinite(line.X2) && double.IsFinite(line.Y2) + && (line.X1 != line.X2 || line.Y1 != line.Y2) ? line : null; + } } } diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs b/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs index f3314180..6694f934 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs @@ -74,29 +74,12 @@ internal static bool TryReadUnitOptions(byte[] data, int start, int end, out int if (count > 100_000 || count * 30L + 16 > end - position) return false; var options = new UnitFormatOption[(int)count]; var specs = new HashSet(StringComparer.Ordinal); - bool ReadId(out string value) - { - value = ""; - if (position > end - 4) return false; - uint length = BitConverter.ToUInt32(data, position); position += 4; - if (length > 10_000 || length * 2L > end - position) return false; - try { value = UnitIdUtf16.GetString(data, position, (int)length * 2); } - catch (DecoderFallbackException) { return false; } - position += (int)length * 2; - return true; - } for (int index = 0; index < options.Length; index++) { - if (!ReadId(out string spec) || !ReadId(out string symbol) || !ReadId(out string unit) - || !specs.Add(spec) || position > end - 18) return false; - double accuracy = BitConverter.ToDouble(data, position); - if (!double.IsFinite(accuracy) || accuracy < 0) return false; - for (int flag = 12; flag < 18; flag++) - if (data[position + flag] > 1) return false; - options[index] = new(spec, symbol, unit, accuracy, BitConverter.ToInt32(data, position + 8), - data[position + 12], data[position + 13], data[position + 14], - data[position + 15], data[position + 16], data[position + 17]); - position += 18; + if (!ReadUnitId(data, ref position, end, out string spec) + || !specs.Add(spec) + || ReadUnitFormatOption(data, ref position, end, spec) is not { } option) return false; + options[index] = option; } if (position > end - 16) return false; units = new(options, BitConverter.ToInt32(data, position), BitConverter.ToInt32(data, position + 4), @@ -105,6 +88,33 @@ bool ReadId(out string value) return true; } + private static bool ReadUnitId(byte[] data, ref int position, int end, out string value) + { + value = ""; + if (position > end - 4) return false; + uint length = BitConverter.ToUInt32(data, position); position += 4; + if (length > 10_000 || length * 2L > end - position) return false; + try { value = UnitIdUtf16.GetString(data, position, (int)length * 2); } + catch (DecoderFallbackException) { return false; } + position += (int)length * 2; + return true; + } + + private static UnitFormatOption? ReadUnitFormatOption(byte[] data, ref int position, int end, string spec) + { + if (!ReadUnitId(data, ref position, end, out string symbol) + || !ReadUnitId(data, ref position, end, out string unit) || position > end - 18) return null; + double accuracy = BitConverter.ToDouble(data, position); + if (!double.IsFinite(accuracy) || accuracy < 0) return null; + for (int flag = 12; flag < 18; flag++) + if (data[position + flag] > 1) return null; + var option = new UnitFormatOption(spec, symbol, unit, accuracy, BitConverter.ToInt32(data, position + 8), + data[position + 12], data[position + 13], data[position + 14], + data[position + 15], data[position + 16], data[position + 17]); + position += 18; + return option; + } + private static bool UnitOptionSchemasMatch() { if (!Schemas.TryGetValue(4029, out var element) || element.Name != "UnitsElem" || element.Base != 37 diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.WallGeometryHistories.cs b/src/RvtIO/Parsing/TfBlockDeserializer.WallGeometryHistories.cs index fc4f62f7..51ce8d66 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.WallGeometryHistories.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.WallGeometryHistories.cs @@ -135,7 +135,7 @@ internal sealed record OwnWallGeometryHistories(OwnWallGeometryPhases List, continue; } var tail = new Cursor { D = data, Pos = objectStart, End = cursor.End }; - if (!TryReadExactWallGeomStep(tail, cls, out _, out _, out string? why)) + if (!TryReadExactWallGeomStep(tail, cls, out _, out _, out string? why, out _)) { failure += $":{why}"; return Result(failure); } if (tail.Pos < cursor.Pos) throw Fail; cursor.Pos = tail.Pos; diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index f8c58955..3ad89954 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using RvtIO.BuiltIns; using RvtIO.Internal; using RvtIO.Model; @@ -37,6 +38,21 @@ internal sealed class NativeParams public bool RootParameterStoresComplete { get; set; } /// Class tags of the cells of the element's CellList, when the deferred walk reached that object. public List? CellClasses { get; set; } + internal BreakLineProfile? DetailBreak { get; set; } + internal IReadOnlyList<(double X, double Y)>? SitePropertyCurve { get; set; } + internal (double X, double Y)? SitePropertyArcCenter { get; set; } + internal List? RoomColors { get; set; } + internal List? DimensionReferences { get; set; } + internal List? DimensionValues { get; set; } + internal (double[] Origin, double[] Direction)? DimensionLine { get; set; } + internal (string Text, double? FontSizePoints)? PlanNoteText { get; set; } + internal List? PlanNoteLeaders { get; set; } + internal HashSet? ViewHiddenElements { get; set; } + internal HashSet? ViewHiddenCategories { get; set; } + internal ViewModelBounds? ModelClipBox { get; set; } + internal double[]? SunStudyOutline { get; set; } + internal List? SiteContours { get; set; } + internal SiteContourLabelData? SiteContourLabels { get; set; } /// The deferred walk consumed every queued object of the record (so the NamedParams and cells are complete). public bool TailWalkComplete { get; set; } public List<(int ParamId, double Value)> Doubles { get; } = new(); @@ -58,7 +74,7 @@ internal sealed class NativeParams public double[]? PlanViewRangeOffsets { get; set; } public int[]? PlanViewRangeLevelIds { get; set; } public int Count => Doubles.Count + Ints.Count + Strings.Count + ElementIds.Count - + Fields.Count + DoubleFields.Count + StringFields.Count; + + Fields.Count + DoubleFields.Count + StringFields.Count + (SitePropertyCurve == null ? 0 : 1); } /// One NamedParam of FamilyParams.m_params. Which of Value/ElemId/Int/Str is meaningful depends on the @@ -230,6 +246,7 @@ private static void DiagNoteQueued(List<(ushort, uint)> queue) "602:m_idSystemCategory", "602:m_iEndReference", "602:m_idLevelStart", "602:m_pCurveDriver", "602:m_pConnectorManager", "527:m_leader", "527:m_leaderEndCondition", "527:m_tagRelOffsetCondition", "527:m_isRelPosValid", "527:m_hideTagIn3DView", "527:m_oTagOrientationCell", "527:m_symbolId", "527:m_taggedEntitiesCell", "527:m_multiReferenceAnnotationId", + "3936:m_isStraightLeader", "3936:m_needReconcile", "1990:m_dbViewId", "1990:m_dbDrawingId", "1990:m_viewportOrientation", "1990:m_clipping", "1990:m_detailNumber", ]; @@ -303,6 +320,49 @@ private static void DiagNoteQueued(List<(ushort, uint)> queue) "37:m_cellList", // HVAC zones: the default zone flag of a ZoneElement and the zone of a space (RoomElem). "4215:m_bDefault", "3471:m_zoneElementId", + "2239:m_width", "2239:m_scale", "2239:m_mirrored", + "2202:m_widthInFeet", "2202:m_heightInFeet", "2197:m_dWidthScale", "2197:m_dHeightScale", + "2202:m_idImageHolder", + "689:m_origin@0", "689:m_origin@1", "689:m_idSchemeCategory", + "697:m_swatchWidth", "697:m_swatchHeight", + "690:m_categoryId", "690:m_paramId", "690:m_bByRange", "693:m_bBackground", + "174:m_tickCategoryId", "174:m_dimensionStyleType", "174:m_linearDimType", + "174:m_textAlignment", "174:m_textLoc", "174:m_alternateUnits", "174:m_dimWitnCntrlExtBelow", + "174:m_arrowHeadStyleId", "174:m_interiorTickMarkStyleId", "174:m_prefix", "174:m_suffix", + "2295:m_tickType", "625:m_fontId", "625:m_categoryId", "1923:m_size", "1923:m_name", "84:m_bUseDefault", + "3702:m_stairsPathOffset", "3703:m_startFromRiser", "3703:m_endAtRiser", "3703:m_startSymbolTypeId", + "160:m_flags", "160:m_useEqualityFormula", "160:m_showLabelGP", "159:m_multiReferenceAnnotationId", + "3928:m_orig@0", "3928:m_orig@1", "3928:m_baseVec@0", "3928:m_baseVec@1", + "3928:m_upVec@0", "3928:m_upVec@1", "3928:m_flags", "3928:m_attrId", "3928:m_height", + "3928:m_lineWidth", "3928:m_bNoWrapping", "3931:m_leaderOffsetSheet", "3931:m_textBoxVisibility", + "625:m_background", "3971:m_bArcLeaders", + "625:m_bBold", "625:m_bItalic", "625:m_bUnderline", + "836:m_baseElevation", + "1861:m_sketchId", "1860:m_bMasking", "1862:m_fillPatternElemId", "1862:m_backgroundPatternElemId", + "621:m_bAnnotationCropActive", "334:m_leftRightTopBottomOffsets@0", "334:m_leftRightTopBottomOffsets@1", + "334:m_leftRightTopBottomOffsets@2", "334:m_leftRightTopBottomOffsets@3", + "2247:m_pos@0", "2247:m_pos@1", "2247:m_symbolId", "2248:m_parentId", + "621:m_dbViewId", "621:m_projMethodType", "4122:m_modelClipBoxId", "2505:m_viewer3dId", + "2249:m_coarserScale", "1020:m_elevatnAttrId", + "2251:m_elevationSymbolId", "2251:m_shape", "2251:m_ahAngleDouble", "2251:m_ahFilled", + "1763:first", "1724:m_masterSymId", + "4108:m_surfaces", "4108:m_transparency", "4108:m_edges", "4108:m_bShowSurfacePatterns", + "4107:m_hlr", "4107:m_lighting", + "4103:m_type", "4103:m_backgroundColor", "4103:m_skyColor", "4103:m_groundColor", + "4110:m_ambientShadows", "4110:m_castShadows", "4106:m_ambientLightIntensity", + "4106:m_sunlightIntensity", "4106:m_shadowIntensity", "4106:m_sunAndShadowSettingsId", + "3878:m_dAzimuth", "3878:m_dAltitude", "3878:m_type", "3878:m_idLevel", + "3878:m_bGroundPlane", "3878:m_bRelativeToView", + "3878:m_idAnnotation", "3878:m_sunPathSize", "3878:m_startDateTime", "3878:m_endDateTime", + "3878:m_activeFrame", "3878:m_eSunStudyTimeInterval", "3878:m_sunriseToSunset", + "108:m_bCustomScaleName", "108:m_strCustomScaleName", + "3475:m_symbolId", "3475:m_bLeader", "3475:m_bLeaderIsStraight", + "3475:m_leaderAnchor@0", "3475:m_leaderAnchor@1", + "3475:m_tagOffset@0", "3475:m_tagOffset@1", + "3934:m_headLocation@0", "3934:m_headLocation@1", "3934:m_rotationAngle", + "3934:m_orientation", "3934:m_isSpatialElementTag", + "2479:m_bUseRenderAppearance", + "3546:m_sectionHeadFamilyTagId", "3546:m_sectionTailFamilyTagId", .. RoomRuleFieldKeys, .. ListFactFieldKeys, ]; @@ -388,7 +448,7 @@ private static void MergeKeyed(NativeParams from, NativeParams into) { "m_scale", "m_topRailHeight", // GeoSite (project location symbol): latitude / longitude in radians. - "m_dLatitude", "m_dLongitude", + "m_dLatitude", "m_dLongitude", "m_dTimeZone", }; /// String schema fields captured into StringFields. @@ -592,6 +652,11 @@ private sealed class DecodeFail : Exception { } var queue = new List<(ushort Cls, uint Id)>(); cur.RootQueue = queue; var res = new NativeParams(); + int breakFaces = -1, breakPlanes = -1; + int propertyCurve = -1, dimensionLine = -1, linearFormat = -1; + int noteRtf = -1, noteLeaderStart = -1, noteLeaderEnd = -1; + int viewHiddenElements = -1, viewHiddenCategories = -1, viewDisplay = -1, planRange = -1; + int contourLabels = -1; if (CaptureAllFields) { diagRootQueue = queue; @@ -599,7 +664,61 @@ private sealed class DecodeFail : Exception { } } try { - foreach (var f in fields) ReadField(cur, f, queue, 0, res); + foreach (var f in fields) + { + int next = queue.Count; + if (classId is 986 or 1005 or 1016 + && f is { Declaring: 108, Name: "m_explicitlyHiddenElements", Type: 14, Mods: 80, Ref: 20 }) + res.ViewHiddenElements = ReadViewIdSet(cur); + else + ReadField(cur, f, queue, 0, res); + if (classId == 1829 && f is { Declaring: 1829, Name: "m_refFaces", Type: 14, Mods: 81 } + && queue.Count - next == BreakReferenceCount + && queue.Skip(next).All(entry => entry.Cls == 1589)) + breakFaces = next; + if (classId == 3070 && f is { Declaring: 3070, Name: "m_curve", Type: 14, Mods: 1 } + && queue.Count == next + 1 && queue[next].Cls is 1736 or 1974) + propertyCurve = next; + if (classId == 837 && f is { Declaring: 838, Name: "m_data" } + && next < queue.Count && queue[next].Cls == 840) + contourLabels = next; + if (classId == 2335 && f is { Declaring: 158, Name: "m_pDimLine", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 1736) + dimensionLine = next; + if (classId == 174 && f is { Declaring: 174, Name: "m_oLinFormatOptions", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 84) + linearFormat = next; + if (classId is 3971 or 3927 && f is { Declaring: 3928, Name: "m_oSavedRtfData", Type: 14, Mods: 1 } + && queue.Count == next + 1 && queue[next].Cls == 3487) + noteRtf = next; + if (classId == 3971 && f is { Declaring: 3971, Name: "m_leaders", Type: 14, Mods: 81 } + && queue.Count > next && queue.Skip(next).All(entry => entry.Cls == 622)) + { + noteLeaderStart = next; + noteLeaderEnd = queue.Count; + } + if (classId is 986 or 1005 or 1016 && queue.Count == next + 1) + { + if (f is { Declaring: 108, Name: "m_oHiddenElementsViewSettings" } + && queue[next].Cls == 2160) + viewHiddenElements = next; + if (f is { Declaring: 108, Name: "m_pViewDisplayMgr" } && queue[next].Cls == 4107) + viewDisplay = next; + if (f is { Declaring: 1005, Name: "m_pPlanViewRange2", Type: 14, Mods: 2 } + && queue[next].Cls == 2974) + planRange = next; + } + if (classId is 986 or 1005 or 1016 + && f is { Declaring: 108, Name: "m_oaDrawFilters", Type: 14, Mods: 81 }) + { + for (int i = next; i < queue.Count; i++) + if (queue[i].Cls == 2190) + { + viewHiddenCategories = i; + break; + } + } + } } catch (DecodeFail) { @@ -673,7 +792,71 @@ private sealed class DecodeFail : Exception { } walked?.Append(queue[qi].Cls).Append("<").Append(origin).Append("@").Append(cur.Pos).Append(qf == null ? "!," : ","); if (walked != null && WalkHexClasses.Contains(queue[qi].Cls)) walked.Append("[").Append(Convert.ToHexString(cur.D, cur.Pos, Math.Min(800, cur.End - cur.Pos))).Append("]"); if (qf == null) break; - if (queue[qi].Cls == 2974) + if (qi == breakPlanes) + res.DetailBreak = ReadBreakReferencePlanes(cur.D.AsSpan(cur.Pos, cur.End - cur.Pos)); + if (qi == propertyCurve) + { + res.SitePropertyCurve = ReadSitePropertyCurve(cur, queue[qi].Cls, out var center); + res.SitePropertyArcCenter = center; + continue; + } + if (qi == contourLabels) + { + res.SiteContourLabels = ReadSiteContourLabels(cur, qf, queue); + continue; + } + if (qi == viewDisplay) + { + if (!TryReadViewDisplayMgr(cur, queue, out _, tail)) throw Fail; + continue; + } + if (qi == viewHiddenElements) + { + foreach (var field in qf) + { + if (field is { Declaring: 2160, Name: "m_hiddenElements", Type: 14, Mods: 80, Ref: 20 }) + (res.ViewHiddenElements ??= []).UnionWith(ReadViewIdSet(cur)); + else + ReadField(cur, field, queue, 1, null); + } + continue; + } + if (qi == viewHiddenCategories) + { + foreach (var field in qf) + { + if (field is { Declaring: 2190, Name: "m_categoryIds", Type: 14, Mods: 80, Ref: 20 }) + res.ViewHiddenCategories = ReadViewIdSet(cur); + else + ReadField(cur, field, queue, 1, null); + } + continue; + } + if (qi == noteRtf) + { + res.PlanNoteText = ReadPlanNoteRtf(cur, qf); + continue; + } + if (qi >= noteLeaderStart && qi < noteLeaderEnd) + { + if (ReadPlanNoteLeader(cur, qf, queue) is { } leader) + (res.PlanNoteLeaders ??= new()).Add(leader); + continue; + } + if (qi == dimensionLine) + { + res.DimensionLine = ReadDimensionLine(cur, qf, queue); + continue; + } + if (qi == linearFormat) + { + var format = new NativeParams(); + foreach (var field in qf) ReadField(cur, field, queue, 1, format); + if (format.Fields.TryGetValue("84:m_bUseDefault", out int useDefault)) + res.Fields["174:linearFormatUsesDefault"] = useDefault; + continue; + } + if (qi == planRange) { // PlanViewRange2: two five-element arrays of the view's own block. Keeping its // offsets and level ids lets a plan decide which elements below the level it shows. @@ -694,8 +877,8 @@ private sealed class DecodeFail : Exception { } } if (offsetCount == 5 && levelCount == 5) { - tail.PlanViewRangeOffsets = offsets; - tail.PlanViewRangeLevelIds = levelIds; + res.PlanViewRangeOffsets = offsets; + res.PlanViewRangeLevelIds = levelIds; } continue; } @@ -731,7 +914,18 @@ private sealed class DecodeFail : Exception { } bool driveSpline = qi == cur.CurveDriverCurveQueueIndex && queue[qi].Cls == 2020; if (driveSpline) cur.HermiteNodes = new List(); int cellsBefore = queue[qi].Cls == 653 ? queue.Count : -1; + int nextObject = queue.Count; foreach (var sf in qf) { lastField = FieldKey(sf) + "/" + sf.Type + "/" + sf.Mods + "/" + sf.Ref; ReadField(cur, sf, queue, 1, tail); } + if (breakFaces >= 0 && qi >= breakFaces && qi < breakFaces + BreakReferenceCount) + { + if (queue.Count != nextObject + 1 || queue[nextObject].Cls != 522 + || (qi != breakFaces && nextObject != breakPlanes + qi - breakFaces)) + { + breakFaces = -1; + breakPlanes = -1; + } + else if (qi == breakFaces) breakPlanes = nextObject; + } if (cellsBefore >= 0 && ReferenceEquals(queue, cur.RootQueue)) tail.CellClasses = queue.Skip(cellsBefore).Select(entry => (int)entry.Item1).ToList(); KeepAnyAttachTop(tail, queue[qi].Cls, attachedTopBefore); @@ -778,6 +972,7 @@ private sealed class DecodeFail : Exception { } if (walked != null) tail.StringFields["walk:"] = walked.ToString() + " queue=" + queue.Count + " rest=" + (cur.End - cur.Pos); res.TailWalkComplete = tailDone; MergeKeyed(tail, res); + res.SiteContours = tail.SiteContours; res.NamedParams.AddRange(tail.NamedParams); if (tail.CellClasses != null) res.CellClasses = tail.CellClasses; } @@ -3159,7 +3354,7 @@ private sealed class StepLayoutSearch { failure = $"step {queuedClass}"; if (!TryReadExactWallGeomStep(cur, queuedClass, - out uint stepOwner, out _, out string? stepFailure)) + out uint stepOwner, out _, out string? stepFailure, out _)) { failure = $"step {queuedClass} {stepFailure}"; return null; @@ -3212,7 +3407,12 @@ private sealed class StepLayoutSearch /// Why no value was produced, for diagnostics. internal static bool? ExtractWallJoinedToTop( byte[] d, int blockStart, uint dataSize, ushort classId, out string? failure) + => ExtractWallJoinedToTop(d, blockStart, dataSize, classId, out failure, out _); + + internal static bool? ExtractWallJoinedToTop(byte[] d, int blockStart, uint dataSize, ushort classId, + out string? failure, out int[]? topTargetIds) { + topTargetIds = null; failure = "framing"; if (classId is not (3524 or 361) || blockStart < 0 @@ -3240,6 +3440,7 @@ private sealed class StepLayoutSearch var decodedSteps = new HashSet(); uint? owner = null; bool joinedToTop = false; + List? topTargets = null; try { failure = "root"; @@ -3297,7 +3498,8 @@ private sealed class StepLayoutSearch int stepStart = cur.Pos - blockStart; failure = $"step {queuedClass} @{stepStart}"; if (!TryReadExactWallGeomStep(cur, queuedClass, - out uint stepOwner, out bool stepJoinsTop, out string? stepFailure, anyVersion: true)) + out uint stepOwner, out bool stepJoinsTop, out string? stepFailure, out var targets, + anyVersion: true)) { failure = $"step {queuedClass} {stepFailure} @{stepStart}"; return null; @@ -3309,9 +3511,17 @@ private sealed class StepLayoutSearch } owner = stepOwner; joinedToTop |= stepJoinsTop; + if (stepJoinsTop && stepIndices?.Contains(queueIndex) == true) + { + topTargets ??= []; + for (int i = 0; i < targets.Count; i++) + topTargets.Add(BitConverter.ToInt32(d, targets.Offset + 4 * i)); + } decodedSteps.Add(queueIndex); if (stepIndices != null && stepIndices.IsSubsetOf(decodedSteps)) { + if (topTargets?.All(id => id > 0) == true) + topTargetIds = topTargets.Distinct().ToArray(); failure = null; return joinedToTop; } @@ -3426,20 +3636,63 @@ private sealed class StepLayoutSearch catch (DecodeFail) { return null; } } + internal static (double BaseFeet, int MaterialId)? ExtractSiteCutGraphics( + byte[] data, int start, uint size, ushort classId, out (int Method, int Units)? bearing) + { + bearing = null; + const ushort trueNorth = 4007; + if (classId != trueNorth || !HasExactOwnElementRoot(data, start, size, classId)) return null; + var fields = SerializationFields(classId)!; + if (!HasExactSchemaField(fields, 37, "m_famId", 14, 0, 20) + || !HasExactSchemaField(fields, trueNorth, "m_pocheDepth", 7, 0, null) + || !HasExactSchemaField(fields, trueNorth, "m_siteCutMaterialId", 14, 0, 20)) return null; + + var cursor = new Cursor { D = data, Pos = start + 14, End = start + 12 + (int)size }; + var queue = new List<(ushort Cls, uint Id)>(); + double baseFeet = double.NaN; + int materialId = -1, method = -1, units = -1; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_famId" }) + { + // Embedded families have their own TrueNorth settings. + if (ReadI32(cursor) != -1) return null; + } + else if (field is { Declaring: trueNorth, Name: "m_pocheDepth" }) + baseFeet = ReadF64(cursor); + else if (field is { Declaring: trueNorth, Name: "m_siteCutMaterialId" }) + materialId = ReadI32(cursor); + else if (field is { Declaring: trueNorth, Name: "m_propertyBearingMethod", Type: 4, Mods: 0 }) + method = ReadI32(cursor); + else if (field is { Declaring: trueNorth, Name: "m_propertyBearingUnits", Type: 4, Mods: 0 }) + units = ReadI32(cursor); + else + ReadField(cursor, field, queue, 0, null); + } + } + catch (DecodeFail) { return null; } + if (method >= 0 && units >= 0) bearing = (method, units); + return double.IsFinite(baseFeet) && materialId > 0 ? (baseFeet, materialId) : null; + } + /// One line family of a fill pattern: its angle (radians), origin, shift (along the line) and /// offset (between lines) in the pattern's own feet, and its repeating dash list (dash, gap, ...; a zero /// dash is a dot). internal sealed record PatternGrid(double Angle, double OriginX, double OriginY, double Shift, double Offset, - double[] Segments); + double[] Segments, int Target = -1, int Orientation = -1); /// Reads a material's cut and surface fill patterns: the MaterialElem root (class 2486) owns one /// deferred Material (class 2479) through m_pMaterial, whose m_cutPatternId and m_surfacePatternId name the /// pattern elements. Both ids are -1 when the material has no pattern of that kind. False when anything /// fails to decode. internal static bool TryExtractMaterialPatterns( - byte[] d, int blockStart, uint dataSize, ushort classId, out int cutPatternId, out int surfacePatternId) + byte[] d, int blockStart, uint dataSize, ushort classId, out int cutPatternId, out int surfacePatternId, + out int? surfacePatternColor, out int? cutPatternColor) { cutPatternId = surfacePatternId = -1; + surfacePatternColor = cutPatternColor = null; if (classId != 2486 || blockStart < 0 || dataSize > int.MaxValue @@ -3491,9 +3744,19 @@ internal static bool TryExtractMaterialPatterns( cutPatternId = ReadI32(cur); continue; } + if (field is { Declaring: 2479, Name: "m_cutPatternColor", Type: 5, Mods: 0 }) + { + cutPatternColor = ReadI32(cur); + continue; + } if (field is { Declaring: 2479, Name: "m_surfacePatternId", Type: 14, Mods: 0, Ref: 20 }) { surfacePatternId = ReadI32(cur); + continue; + } + if (field is { Declaring: 2479, Name: "m_surfacePatternColor", Type: 5, Mods: 0 }) + { + surfacePatternColor = ReadI32(cur); return true; } ReadField(cur, field, queue, 1, null); @@ -3520,9 +3783,9 @@ private static void SkipMaterialPathMap(Cursor cur) /// Walks the deferred objects queued before , so the cursor reaches the /// object whose fields the caller wants to read next. Parameter-set stores are read as their own records. - private static void SkipQueuedObjects(Cursor cur, List<(ushort Cls, uint Id)> queue, int stopIndex) + private static void SkipQueuedObjects(Cursor cur, List<(ushort Cls, uint Id)> queue, int stopIndex, int startIndex = 0) { - for (int queueIndex = 0; queueIndex < stopIndex; queueIndex++) + for (int queueIndex = startIndex; queueIndex < stopIndex; queueIndex++) { ushort queuedClass = queue[queueIndex].Cls; if (ParamSetTags.TryGetValue(queuedClass, out var parameterStore)) @@ -3590,14 +3853,16 @@ internal static bool TryExtractFillPattern( if (patternIndex < 0 || !ownOwnerRead) return false; SkipQueuedObjects(cur, queue, patternIndex); - int gridCount = 0; + int gridCount = -1, target = -1, orientation = -1; foreach (var field in patternFields) { if (field is { Declaring: 1849, Name: "m_gridsArr", Type: 14, Mods: 81 }) { - int before = queue.Count; + int start = cur.Pos, before = queue.Count; ReadField(cur, field, queue, 1, null); gridCount = queue.Count - before; + if (cur.Pos - start < 4 || BitConverter.ToUInt32(d, start) != (uint)gridCount) + return false; } else if (field is { Declaring: 1849, Name: "m_name", Type: 8, Mods: 96 }) name = ReadString(cur); @@ -3605,10 +3870,14 @@ internal static bool TryExtractFillPattern( ReadF64(cur); else if (field is { Declaring: 1849, Name: "m_windowSize", Type: 7, Mods: 0 }) ReadF64(cur); + else if (field is { Declaring: 1849, Name: "m_fpTarget", Type: 4, Mods: 0 }) + target = ReadI32(cur); + else if (field is { Declaring: 1849, Name: "m_fpOrientation", Type: 4, Mods: 0 }) + orientation = ReadI32(cur); else ReadField(cur, field, queue, 1, null); } - if (gridCount <= 0) return false; + if (gridCount < 0) return false; // The queued children are read in the stream order the pointers were seen: a CellList may have // queued a PatternHelper before the grids, so skip every non-FillGrid object up to the last grid. @@ -3652,7 +3921,7 @@ internal static bool TryExtractFillPattern( else ReadField(cur, field, queue, 1, null); } - result.Add(new PatternGrid(angle, ox, oy, shift, offset, segments)); + result.Add(new PatternGrid(angle, ox, oy, shift, offset, segments, target, orientation)); } if (result.Count != gridCount) return false; grids = result; @@ -4011,7 +4280,10 @@ internal sealed record TitleBlockText(double Ox, double Oy, double Oz, double Hx /// A label of a title block family symbol, in symbol feet: the anchor, the box, the flags, the base /// direction and the parameter it prints (a BuiltInParameter id) with its prefix, suffix and sample text. internal sealed record TitleBlockLabel(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, - double Height, double Width, int AttrId, int Flags, int ParamId, string Prefix, string Suffix); + double Height, double Width, int AttrId, int Flags, int ParamId, string Prefix, string Suffix, + UnitFormatOption? SingleParameterFormat = null, bool Wrap = false); + + private sealed record TagLabelParameter(int ParamId, string Prefix, string Suffix, UnitFormatOption? Format); /// A schedule instance placed on a sheet: the DBViewSchedule it shows and its top-left origin in /// sheet feet. @@ -4074,7 +4346,14 @@ internal static bool TryExtractSheetRevisions( /// A body section of a schedule table: its stored header texts (one per visible column, /// empty when the file stores none), the count of leading all-empty body rows and the total body row count. - internal sealed record ScheduleBodySection(List Header, int LeadingEmpty, int BodyRows); + internal sealed record ScheduleBodySection(List Header, int LeadingEmpty, int BodyRows) + { + internal IReadOnlyList? HeaderStyles { get; init; } + internal IReadOnlyList? BodyAlignment { get; init; } + internal ScheduleTextStyle? UniformBodyStyle { get; init; } + } + internal readonly record struct ScheduleTextStyle(double CapHeightPixels, int HorizontalAlignment, + int VerticalAlignment, string? FontName = null, int Flags = 0); /// A schedule definition decoded from its DBViewSchedule block: the visible columns (heading and width /// in feet, in order), the category id, the show flags, the title height and merged bands of the first shown @@ -4082,21 +4361,30 @@ internal sealed record ScheduleBodySection(List Header, int LeadingEmpty internal sealed record ScheduleTableDef(List<(string Heading, double WidthFt)> Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, int GridStyleId, int OutlineStyleId, - double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, - double FixedHeightFt); + double TitleHeightFt, List<(double HeightFt, string Text, ScheduleTextStyle Style)> TitleBands, + List BodySections, + double FixedHeightFt) + { + internal ScheduleRowBindings? RowBindings { get; init; } + internal ScheduleTextStyle TitleStyle { get; init; } + internal (int Header, int Body) TextTypeIds { get; init; } + internal (double Header, double Body)? RevisionCapHeightsFt { get; init; } + } /// A section annotation (class 3545) boiled down to what places its mark on a plan: the parent view /// (a section/elevation view for a callout, -1 for a top-level section), the coarsest scale it shows at, /// and the front-cut polyline in model feet (null when undecodable; the trace the reference draws). - internal sealed record SectionViewdata(int ParentViewId, double CoarserScale, List? FrontCut); + internal sealed record SectionViewdata(int ParentViewId, double CoarserScale, List? FrontCut, + (double Left, double Right, double Top, double Bottom)? AnnotationCrop = null, + double[]? CalloutHead = null, + (double X, double Y)? TraceOrigin = null); internal static bool TryExtractSectionViewdata( byte[] d, int blockStart, uint dataSize, ushort classId, out SectionViewdata viewdata) => TryExtractSectionViewdata(d, blockStart, dataSize, classId, out viewdata, out _); - /// Reads a section annotation (class 3545): the parent view id and the coarsest scale. Stops before - /// the front-cut polyline (a composite the generic walk cannot stride); every earlier field walks generically. - /// False when anything fails to decode. + /// Reads a section annotation (class 3545): the parent view, coarsest scale and, when available, + /// the front cut and annotation crop offsets. False when the parent or scale cannot be read. internal static bool TryExtractSectionViewdata( byte[] d, int blockStart, uint dataSize, ushort classId, out SectionViewdata viewdata, out string failure) { @@ -4130,6 +4418,9 @@ internal static bool TryExtractSectionViewdata( int parentViewId = 0; double coarserScale = 0; bool parentRead = false, coarserRead = false; + (double X, double Y)? traceOrigin = null; + int annotationCropIndex = -1; + bool annotationCropActive = false; foreach (var field in fields) { if (field is { Declaring: 2249, Name: "m_frontCut" }) break; @@ -4141,6 +4432,12 @@ internal static bool TryExtractSectionViewdata( parentViewId = ReadI32(cur); parentRead = true; } + else if (field is { Declaring: 2249, Name: "m_pntForViewData", Type: 7, Mods: 16, Cnt: 3 }) + { + double x = ReadF64(cur), y = ReadF64(cur); + ReadF64(cur); + if (double.IsFinite(x) && double.IsFinite(y)) traceOrigin = (x, y); + } else if (field is { Declaring: 2249, Name: "m_coarserScale" }) { if (field is not { Type: 7, Mods: 0 }) { failure = "coarser-type"; return false; } @@ -4155,11 +4452,17 @@ internal static bool TryExtractSectionViewdata( for (int i = 0; i < 3; i++) ReadF64(cur); if (!cur.Take(72 + 48 + 6 + 1)) throw Fail; } - else if (field.Name == "m_viewerFlags" && field.Type == 3) + else if (field is { Declaring: 621, Name: "m_pAnnotationCropOffsets", Type: 14, Mods: 2 }) + { + int index = queue.Count; + ReadPtr(cur, queue); + if (queue.Count == index + 1 && queue[index].Cls == 334) + annotationCropIndex = index; + } + else if (field is { Declaring: 621, Name: "m_bAnnotationCropActive", Type: 1, Mods: 0 }) { - // A two-byte flags field where the generic single-byte scalar stride would misalign - // the four one-byte flags and the view-layout pointer after it. - if (!cur.Take(2)) throw Fail; + if (!cur.Take(1)) throw Fail; + annotationCropActive = cur.D[cur.Pos - 1] == 1; } else ReadField(cur, field, queue, 0, null); } @@ -4175,7 +4478,12 @@ internal static bool TryExtractSectionViewdata( // The loop stopped at the front-cut polyline: a count-prefixed array of XYZ points in model // feet. A failure here never loses the parent/scale facts above; the mark just falls back // to its straight-line trace. - viewdata = new(parentViewId, coarserScale, TryReadFrontCut(cur)); + var frontCut = TryReadFrontCut(cur); + double[]? calloutHead = null; + var annotationCrop = frontCut != null + ? ReadSectionDecorations(cur, queue, annotationCropActive ? annotationCropIndex : -1, + fields, parentViewId, out calloutHead) : null; + viewdata = new(parentViewId, coarserScale, frontCut, annotationCrop, calloutHead, traceOrigin); return true; } catch (DecodeFail) { failure = $"decodefail pos={cur.Pos}"; return false; } @@ -4190,8 +4498,11 @@ internal static bool TryExtractSectionViewdata( { if (cur.Pos + 4 > cur.End || cur.Pos < 0) return null; uint n = BitConverter.ToUInt32(cur.D, cur.Pos); - if (n == 0xFFFFFFFF) return new List(); - if (n == 0) return new List(); + if (n is 0 or uint.MaxValue) + { + cur.Pos += 4; + return []; + } if (n > 10000 || cur.Pos + 4L + n * 24 > cur.End) return null; cur.Pos += 4; var points = new List((int)n); @@ -4213,6 +4524,53 @@ internal static bool TryExtractSectionViewdata( } } + private static (double Left, double Right, double Top, double Bottom)? ReadSectionDecorations( + Cursor cur, List<(ushort Cls, uint Id)> queue, int index, IReadOnlyList fields, + int parentViewId, out double[]? calloutHead) + { + calloutHead = null; + if (!HasExactSchemaField(fields, 2249, "m_pCreationViewData", 14, 1, null) + || !HasExactSchemaField(fields, 2249, "m_viewDataMapForCallout", 14, 80, null)) return null; + try + { + ReadPtr(cur, queue); + uint count = ReadU32(cur); + if (count == uint.MaxValue) count = 0; + if (count > 10000) return null; + // The map serializes an ElementId followed by an inline CalloutGraphicsViewData. + bool foundParent = false; + double[]? point = null; + for (uint i = 0; i < count; i++) + { + int owner = ReadI32(cur); + int start = cur.Pos; + ReadInlineStruct(cur, 626, queue, 0); + if (owner != parentViewId || owner <= 0) continue; + if (foundParent) return null; + foundParent = true; + // A straight leader uses its head point at the rim of the tag. + if (cur.Pos - start == 153 && cur.D[cur.Pos - 1] == 1 + && SerializationFields(626) is + [{ Name: "m_headPoint", Type: 7, Mods: 16, Cnt: 3 }, _, _]) + { + var head = new[] { BitConverter.ToDouble(cur.D, start), BitConverter.ToDouble(cur.D, start + 8), + BitConverter.ToDouble(cur.D, start + 16) }; + if (head.All(value => Math.Abs(value) < 1_000_000)) point = head; + } + } + calloutHead = point; + if (index < 0 || SerializationFields(334) is not + [{ Name: "m_leftRightTopBottomOffsets", Type: 7, Mods: 16, Cnt: 4 }]) return null; + for (int i = 0; i < index; i++) + ReadInlineStruct(cur, queue[i].Cls, queue, 0); + double left = ReadF64(cur), right = ReadF64(cur), top = ReadF64(cur), bottom = ReadF64(cur); + return Valid(left) && Valid(right) && Valid(top) && Valid(bottom) ? (left, right, top, bottom) : null; + } + catch (DecodeFail) { return null; } + + static bool Valid(double value) => value is >= 0 and < 100; + } + /// Reads a schedule instance (class 3532): the DBViewSchedule it shows and its top-left origin in /// sheet feet. False when anything fails to decode. internal static bool TryExtractScheduleInstance( @@ -4337,13 +4695,18 @@ internal static bool TryExtractScheduleTable( cur.RootQueue = queue; try { + int headerTextTypeId = -1, bodyTextTypeId = -1; try { foreach (var field in fields) { try { - ReadField(cur, field, queue, 0, null); + if (field is { Declaring: 1012, Name: "m_headerTextTypeId", Type: 14, Mods: 0, Ref: 20 }) + headerTextTypeId = ReadI32(cur); + else if (field is { Declaring: 1012, Name: "m_bodyTextTypeId", Type: 14, Mods: 0, Ref: 20 }) + bodyTextTypeId = ReadI32(cur); + else ReadField(cur, field, queue, 0, null); } catch (DecodeFail) { @@ -4366,7 +4729,9 @@ internal static bool TryExtractScheduleTable( var sectionInfos = new List<(int Index, List RowQis, List CellQis, bool Hide)>(); var rowHeights = new Dictionary(); var rowCellQis = new Dictionary>(); - var cellInfos = new Dictionary(); + var cellInfos = new Dictionary(); + var cellStyles = new Dictionary(); + var rowBindings = new ScheduleRowBindings(); double fixedHeightFt = 0; for (int qi = 0; qi < queue.Count; qi++) { @@ -4397,17 +4762,33 @@ internal static bool TryExtractScheduleTable( } if (queuedClass == 3528) { - if (!TryReadScheduleField(cur, queue, out var heading, out var widthFt, out var hidden, out string fieldFailure)) + if (!TryReadScheduleField(cur, queue, out var heading, out var widthFt, out var hidden, + out int parameterId, out int source, out string fieldFailure)) { failure = $"field qi={qi} pos={cur.Pos} {fieldFailure}"; return false; } if (!hidden) columns.Add((heading, widthFt)); + rowBindings.Fields[qi] = (parameterId, hidden, source); + continue; + } + if (queuedClass == 3542) + { + rowBindings.Sorts[qi] = (ReadI32(cur), ReadI32(cur), ReadI32(cur)); + continue; + } + if (queuedClass == 3530) + { + int fieldId = ReadI32(cur), type = ReadI32(cur); + ReadString(cur); // ParamStorage's string slot. + ReadF64(cur); + ReadI32(cur); + rowBindings.Filters[qi] = (fieldId, type, ReadI32(cur), ReadI32(cur)); continue; } if (queuedClass == 3535) { - if (!TryReadScheduleSchemaFlags(cur, queue, out int category, out bool title, out bool headers, out bool grid, out bool outline, out int gridStyle, out int outlineStyle, out string schemaFailure)) + if (!TryReadScheduleSchemaFlags(cur, queue, rowBindings, out int category, out bool title, out bool headers, out bool grid, out bool outline, out int gridStyle, out int outlineStyle, out string schemaFailure)) { failure = $"schema qi={qi} pos={cur.Pos} {schemaFailure}"; return false; @@ -4463,12 +4844,35 @@ internal static bool TryExtractScheduleTable( } if (queuedClass == 3921) { - if (!TryReadScheduleCell(cur, queue, out string cellText, out int cellType, out int coverBottom, out int coverRight, out string cellFailure)) + if (!TryReadScheduleCell(cur, queue, out string cellText, out int cellType, + out int coverBottom, out int coverRight, out int style, out string cellFailure)) { failure = $"tablecell qi={qi} pos={cur.Pos} {cellFailure}"; return false; } - cellInfos[qi] = (cellText, cellType, coverBottom, coverRight); + cellInfos[qi] = (cellText, cellType, coverBottom, coverRight, style); + continue; + } + if (queuedClass == 3922) + { + double size = 0; + int horizontal = -1, vertical = -1, flags = 0; + string? fontName = null; + foreach (var styleField in SerializationFields(queuedClass) ?? throw Fail) + { + if (styleField is { Declaring: 3922, Name: "m_textSize", Type: 7, Mods: 0 }) + size = ReadF64(cur); + else if (styleField is { Declaring: 3922, Name: "m_fontName", Type: 8, Mods: 96 }) + fontName = ReadString(cur); + else if (styleField is { Declaring: 3922, Name: "m_flag", Type: 4, Mods: 0 }) + flags = ReadI32(cur); + else if (styleField is { Declaring: 3922, Name: "m_horizontalAlignment", Type: 5, Mods: 0 }) + horizontal = ReadI32(cur); + else if (styleField is { Declaring: 3922, Name: "m_verticalAlignment", Type: 5, Mods: 0 }) + vertical = ReadI32(cur); + else ReadField(cur, styleField, queue, 1, null); + } + if (size is > 0 and <= 256) cellStyles[qi] = new(size, horizontal, vertical, fontName, flags); continue; } if (queuedClass == 3539) @@ -4524,10 +4928,11 @@ internal static bool TryExtractScheduleTable( failure = $"empty schema={schemaRead} cols={columns.Count} queue={queue.Count}"; return false; } - AssembleScheduleTitleBody(sectionInfos, rowHeights, rowCellQis, cellInfos, - out double titleHeightFt, out List<(double HeightFt, string Text)> titleBands, out List bodySections); + AssembleScheduleTitleBody(sectionInfos, rowHeights, rowCellQis, cellInfos, cellStyles, + out double titleHeightFt, out var titleStyle, out var titleBands, out var bodySections); table = new ScheduleTableDef(columns, categoryId, showTitle, showHeaders, showGridLines, showOutline, - gridStyleId, outlineStyleId, titleHeightFt, titleBands, bodySections, fixedHeightFt); + gridStyleId, outlineStyleId, titleHeightFt, titleBands, bodySections, fixedHeightFt) + { RowBindings = rowBindings, TitleStyle = titleStyle, TextTypeIds = (headerTextTypeId, bodyTextTypeId) }; return true; } catch (DecodeFail) @@ -4545,45 +4950,60 @@ private static void AssembleScheduleTitleBody( List<(int Index, List RowQis, List CellQis, bool Hide)> sectionInfos, Dictionary rowHeights, Dictionary> rowCellQis, - Dictionary cellInfos, - out double titleHeightFt, out List<(double HeightFt, string Text)> titleBands, out List bodySections) + Dictionary cellInfos, + Dictionary cellStyles, + out double titleHeightFt, out ScheduleTextStyle titleStyle, + out List<(double HeightFt, string Text, ScheduleTextStyle Style)> titleBands, out List bodySections) { titleHeightFt = 0; + titleStyle = default; titleBands = new(); bodySections = new(); var shown = sectionInfos.Where(section => !section.Hide).OrderBy(section => section.Index).ToList(); if (shown.Count == 0) return; - var first = shown[0]; + // A hidden title section still owns index zero. The first visible section can be the column header. + var first = shown[0].Index == 0 ? shown[0] : (Index: 0, RowQis: new List(), CellQis: new List(), Hide: true); + if (first.CellQis.Count > 0 && rowCellQis.GetValueOrDefault(first.CellQis[0]) is { Count: > 0 } titleCells + && cellInfos.TryGetValue(titleCells[0], out var titleCell)) + titleStyle = cellStyles.GetValueOrDefault(titleCell.Style); if (first.RowQis.Count > 0 && rowHeights.TryGetValue(first.RowQis[0], out double titleHeight) && titleHeight > 0 && titleHeight <= 10) titleHeightFt = titleHeight; // Later rows of the first section form merged bands: a band extends while its last row's cells // carry a bottom cover into the next row (the How-do-I long-text band spans two stored rows). - var bands = new List<(double HeightFt, string Text)>(); + var bands = new List<(double HeightFt, string Text, ScheduleTextStyle Style)>(); var bandRows = new List(); string bandText = ""; double bandHeight = 0; + ScheduleTextStyle bandStyle = default; for (int i = 1; i < first.RowQis.Count; i++) { int rowQi = first.RowQis[i]; double height = rowHeights.TryGetValue(rowQi, out double h) ? h : 0; - string text = FirstCellText(first, i, rowCellQis, cellInfos); + int cellGroup = first.CellQis[i]; + var cell = rowCellQis.GetValueOrDefault(cellGroup)? + .Select(qi => cellInfos.GetValueOrDefault(qi)).FirstOrDefault(item => !string.IsNullOrEmpty(item.Text)); bool extends = bandRows.Count > 0 && BandExtends(bandRows[^1], first, rowCellQis, cellInfos); if (!extends && bandRows.Count > 0 && bandHeight > 0 && bandHeight <= 20) { - bands.Add((bandHeight, bandText)); + bands.Add((bandHeight, bandText, bandStyle)); bandRows.Clear(); bandText = ""; bandHeight = 0; + bandStyle = default; } bandRows.Add(rowQi); if (height > 0 && height <= 10) bandHeight += height; - if (bandText.Length == 0 && text.Length > 0) bandText = text; + if (bandText.Length == 0 && cell is { Text.Length: > 0 } cellWithText) + { + bandText = cellWithText.Text; + bandStyle = cellStyles.GetValueOrDefault(cellWithText.Style); + } } if (bandRows.Count > 0 && bandHeight > 0 && bandHeight <= 20) - bands.Add((bandHeight, bandText)); + bands.Add((bandHeight, bandText, bandStyle)); titleBands = bands; - foreach (var section in shown.Skip(1)) + foreach (var section in shown.Where(section => section.Index != 0)) { var header = SectionRowTexts(section, 0, rowCellQis, cellInfos); int bodyRows = Math.Max(0, section.RowQis.Count - 1); @@ -4595,13 +5015,49 @@ private static void AssembleScheduleTitleBody( if (SectionRowTexts(section, i, rowCellQis, cellInfos).Any(text => text.Length > 0)) break; leadingEmpty++; } - bodySections.Add(new ScheduleBodySection(header, leadingEmpty, bodyRows)); + ScheduleTextStyle[]? StylesAt(int row) => rowCellQis.TryGetValue(section.CellQis[row], out var cells) + ? cells.Select(cellQi => cellInfos.TryGetValue(cellQi, out var cell) + ? cellStyles.GetValueOrDefault(cell.Style) : default).ToArray() + : null; + var headerStyles = section.CellQis.Count > 0 ? StylesAt(0) : null; + int[]? bodyAlignment = null; + // Evaluated rows can be reordered, so carry an alignment only when all stored data rows agree. + for (int row = 1 + leadingEmpty; row < section.CellQis.Count; row++) + { + if (StylesAt(row) is not { Length: > 0 } styles || styles.Length != header.Count) + { + bodyAlignment = null; + break; + } + if (bodyAlignment == null) + bodyAlignment = styles.Select(style => style.CapHeightPixels > 0 ? style.HorizontalAlignment : -1).ToArray(); + else + for (int col = 0; col < styles.Length; col++) + if (styles[col].CapHeightPixels <= 0 || styles[col].HorizontalAlignment != bodyAlignment[col]) + bodyAlignment[col] = -1; + } + // Evaluated rows need the style even when the saved cells have no text. + ScheduleTextStyle? uniformBodyStyle = null; + if (header.Count > 0 && section.CellQis.Count > 1 + && StylesAt(1) is { Length: > 0 } firstBodyStyles + && firstBodyStyles[0] is { CapHeightPixels: > 0 } firstStyle + && Enumerable.Range(1, section.CellQis.Count - 1).All(row => + StylesAt(row) is { } styles && styles.Length == header.Count + && styles.All(style => style == firstStyle))) + uniformBodyStyle = firstStyle; + + bodySections.Add(new ScheduleBodySection(header, leadingEmpty, bodyRows) + { + HeaderStyles = headerStyles, + BodyAlignment = bodyAlignment, + UniformBodyStyle = uniformBodyStyle, + }); } } private static List SectionRowTexts((int Index, List RowQis, List CellQis, bool Hide) section, int rowPos, Dictionary> rowCellQis, - Dictionary cellInfos) + Dictionary cellInfos) { var texts = new List(); if (rowPos < 0 || rowPos >= section.CellQis.Count) return texts; @@ -4617,18 +5073,9 @@ private static List SectionRowTexts((int Index, List RowQis, List RowQis, List CellQis, bool Hide) section, int rowPos, - Dictionary> rowCellQis, - Dictionary cellInfos) - { - foreach (string text in SectionRowTexts(section, rowPos, rowCellQis, cellInfos)) - if (text.Length > 0) return text; - return ""; - } - private static bool BandExtends(int rowQi, (int Index, List RowQis, List CellQis, bool Hide) section, Dictionary> rowCellQis, - Dictionary cellInfos) + Dictionary cellInfos) { int pos = section.RowQis.IndexOf(rowQi); if (pos < 0 || pos >= section.CellQis.Count) return false; @@ -4638,11 +5085,12 @@ private static bool BandExtends(int rowQi, (int Index, List RowQis, List queue, - out string heading, out double widthFt, out bool hidden, out string failure) + out string heading, out double widthFt, out bool hidden, out int parameterId, out int source, out string failure) { heading = ""; widthFt = 0; hidden = false; + parameterId = source = 0; failure = "ok"; var fieldFields = SerializationFields(3528); if (fieldFields == null) { failure = "no-schema-3528"; return false; } @@ -4669,6 +5117,8 @@ private static bool TryReadScheduleField(Cursor cur, List<(ushort, uint)> queue, cur.Pos++; hiddenRead = true; } + else if (field is { Declaring: 3528, Name: "m_paramElemId" }) parameterId = ReadI32(cur); + else if (field is { Declaring: 3528, Name: "m_sourceType" }) source = ReadI32(cur); else ReadField(cur, field, queue, 1, null); } if (!headRead || !widthRead || !hiddenRead) { failure = "missing-schedule-field"; return false; } @@ -4676,7 +5126,7 @@ private static bool TryReadScheduleField(Cursor cur, List<(ushort, uint)> queue, return true; } - private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> queue, + private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> queue, ScheduleRowBindings bindings, out int categoryId, out bool showTitle, out bool showHeaders, out bool showGridLines, out bool showOutline, out int gridStyleId, out int outlineStyleId, out string failure) { @@ -4690,6 +5140,7 @@ private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> foreach (var field in schemaFields) { if (field.Declaring != 3535) { ReadField(cur, field, queue, 1, null); continue; } + if (ReadScheduleBindingField(bindings, cur, field, queue)) continue; if (field is { Name: "m_categoryId" }) { if (field is not { Type: 14, Mods: 0, Ref: 20 }) { failure = "category-type"; return false; } @@ -4850,17 +5301,24 @@ private static bool TryReadScheduleRowCells(Cursor cur, List<(ushort, uint)> que } private static bool TryReadScheduleCell(Cursor cur, List<(ushort, uint)> queue, - out string text, out int cellType, out int coverBottom, out int coverRight, out string failure) + out string text, out int cellType, out int coverBottom, out int coverRight, out int style, out string failure) { text = ""; cellType = coverBottom = coverRight = 0; + style = -1; failure = "ok"; var fields = SerializationFields(3921); if (fields == null) { failure = "no-schema-3921"; return false; } bool textRead = false, typeRead = false, bottomRead = false, rightRead = false; foreach (var field in fields) { - if (field is { Declaring: 3921, Name: "m_text" }) + if (field is { Declaring: 3921, Name: "m_oTableCellStyle" }) + { + int before = queue.Count; + ReadField(cur, field, queue, 1, null); + if (queue.Count == before + 1 && queue[before].Item1 == 3922) style = before; + } + else if (field is { Declaring: 3921, Name: "m_text" }) { if (field is not { Type: 8, Mods: 96 }) { failure = "text-type"; return false; } text = ReadString(cur); @@ -4895,14 +5353,19 @@ private static bool TryReadScheduleCell(Cursor cur, List<(ushort, uint)> queue, /// (the file's own schema names their classes; the shipped schema leaves them unreferenced, so the generic /// walk would read them as polymorphic handles and misalign). The two raytrace settings stay queued owned /// pointers. False when anything fails to decode. - private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue, out string failure) + private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue, out string failure, + NativeParams? capture = null) { failure = "ok"; var fields = SerializationFields(4107); if (fields == null) { failure = "no-schema-4107"; return false; } foreach (var field in fields) { - if (field.Declaring != 4107 || field is not { Type: 14, Mods: 0 }) { ReadField(cur, field, queue, 1, null); continue; } + if (field.Declaring != 4107 || field is not { Type: 14, Mods: 0 }) + { + ReadField(cur, field, queue, 1, capture); + continue; + } int inlineClass = field.Name switch { "m_background" => 4103, @@ -4915,7 +5378,7 @@ private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue _ => 0, }; if (inlineClass == 0) ReadField(cur, field, queue, 1, null); - else ReadInlineStruct(cur, inlineClass, queue, 1); + else ReadInlineStruct(cur, inlineClass, queue, 1, inlineClass is 4103 or 4106 or 4108 or 4110 ? capture : null); } return true; } @@ -5003,7 +5466,7 @@ internal static bool TryExtractTitleBlockSymbol( // TextNoteData queues its RtfData; TagNoteData carries its parameter formatting inline. var geoms = new List<(double T0, double T1, double Ox, double Oy, double Oz, double Dx, double Dy, double Dz, int Tag, int Control, int CategoryId, uint Flags)>(); var rawTexts = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, int RtfQi)>(); - var rawLabels = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, List<(int ParamId, string Prefix, string Suffix, string Sample)> Params)>(); + var rawLabels = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, bool Wrap, List Params)>(); var rtfBlobs = new Dictionary(); for (int qi = 0; qi < queue.Count; qi++) { @@ -5133,7 +5596,8 @@ internal static bool TryExtractTitleBlockSymbol( } if (paramId == 0) continue; labels.Add(new TitleBlockLabel(raw.Ox, raw.Oy, raw.Oz, raw.Hx, raw.Hy, raw.Bx, raw.By, - raw.Height, raw.Width, raw.AttrId, raw.Flags, paramId, prefix, suffix)); + raw.Height, raw.Width, raw.AttrId, raw.Flags, paramId, prefix, suffix, + raw.Params.Count == 1 ? raw.Params[0].Format : null, raw.Wrap)); } failure = $"ok glines={geoms.Count} kept={lines.Count} texts={texts.Count} labels={labels.Count} queue={queue.Count}"; return true; @@ -5228,10 +5692,11 @@ private static bool TryReadGLine(Cursor cur, List<(ushort Cls, uint Id)> queue, private static bool TryReadTextDataBase(Cursor cur, List<(ushort Cls, uint Id)> queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string failure) + out int attrId, out int flags, out bool wrap, out string failure) { ox = oy = oz = hx = hy = bx = by = height = width = 0; attrId = flags = 0; + wrap = false; failure = "ok"; var baseFields = SerializationFields(3933); if (baseFields == null) @@ -5277,6 +5742,11 @@ private static bool TryReadTextDataBase(Cursor cur, List<(ushort Cls, uint Id)> if (field is not { Type: 4, Mods: 0 }) { failure = "flags-type"; return false; } flags = ReadI32(cur); f = true; } + else if (field is { Declaring: 3933, Name: "m_bNoWrapping", Type: 1, Mods: 0 }) + { + if (!cur.Take(1)) throw Fail; + wrap = cur.D[cur.Pos - 1] == 0; + } else ReadField(cur, field, queue, 1, null); } if (!o || !u || !b || !h || !w || !a || !f) { failure = "missing-base"; return false; } @@ -5290,7 +5760,7 @@ private static bool TryReadTextNoteData(Cursor cur, List<(ushort Cls, uint Id)> failure = "ok"; if (!TryReadTextDataBase(cur, queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string baseFailure)) + out int attrId, out int flags, out _, out string baseFailure)) { failure = baseFailure; return false; @@ -5329,20 +5799,20 @@ private static bool TryReadTextNoteData(Cursor cur, List<(ushort Cls, uint Id)> } private static bool TryReadTagNoteData(Cursor cur, List<(ushort Cls, uint Id)> queue, - out (double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, List<(int ParamId, string Prefix, string Suffix, string Sample)> Params) label, out string failure) + out (double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, bool Wrap, List Params) label, out string failure) { label = default; failure = "ok"; if (!TryReadTextDataBase(cur, queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string baseFailure)) + out int attrId, out int flags, out bool wrap, out string baseFailure)) { failure = baseFailure; return false; } var tagFields = SerializationFields(3932); if (tagFields == null) { failure = "no-schema-3932"; return false; } - var collected = new List<(int ParamId, string Prefix, string Suffix, string Sample)>(); + var collected = new List(); bool arrRead = false; foreach (var field in tagFields) { @@ -5364,26 +5834,27 @@ private static bool TryReadTagNoteData(Cursor cur, List<(ushort Cls, uint Id)> q failure = $"parr[{i}] {paramFailure}"; return false; } - collected.Add(param); + collected.Add(param!); } arrRead = true; } else ReadField(cur, field, queue, 1, null); } if (!arrRead) { failure = "missing-parr"; return false; } - label = (ox, oy, oz, hx, hy, bx, by, height, width, attrId, flags, collected); + label = (ox, oy, oz, hx, hy, bx, by, height, width, attrId, flags, wrap, collected); return true; } private static bool TryReadTagParam(Cursor cur, List<(ushort Cls, uint Id)> queue, - out (int ParamId, string Prefix, string Suffix, string Sample) param, out string failure) + out TagLabelParameter? param, out string failure) { param = default; failure = "ok"; var paramFields = SerializationFields(3929); if (paramFields == null) { failure = "no-schema-3929"; return false; } int paramId = 0; - string prefix = "", sample = "", suffix = ""; + string prefix = "", suffix = ""; + int formatStart = -1, formatEnd = -1; bool idRead = false, preRead = false, samRead = false, sufRead = false; foreach (var field in paramFields) { @@ -5398,16 +5869,30 @@ private static bool TryReadTagParam(Cursor cur, List<(ushort Cls, uint Id)> queu } else if (field is { Declaring: 3929, Name: "m_sampleText" }) { - sample = ReadString(cur); samRead = true; + ReadString(cur); samRead = true; } else if (field is { Declaring: 3929, Name: "m_suffix" }) { suffix = ReadString(cur); sufRead = true; } + else if (field is { Declaring: 3929, Name: "m_formatOptions", Type: 14, Mods: 0, Ref: 84 }) + { + formatStart = cur.Pos; + ReadField(cur, field, queue, 1, null); + formatEnd = cur.Pos; + } else ReadField(cur, field, queue, 1, null); } if (!idRead || !preRead || !samRead || !sufRead) { failure = "missing-param"; return false; } - param = (paramId, prefix, suffix, sample); + UnitFormatOption? format = null; + if (formatStart >= 0 && (BuiltInParameter)paramId is BuiltInParameter.PROPERTY_SEGMENT_N_S + or BuiltInParameter.PROPERTY_SEGMENT_BEARING or BuiltInParameter.PROPERTY_SEGMENT_E_W + or BuiltInParameter.PROPERTY_SEGMENT_DISTANCE) + { + format = ReadUnitFormatOption(cur.D, ref formatStart, formatEnd, ""); + if (formatStart != formatEnd) format = null; + } + param = new(paramId, prefix, suffix, format); return true; } @@ -5621,8 +6106,10 @@ internal static bool TryExtractLinePattern( /// ElementId> 8, an affected-edge entry an ElementId plus a counted tag set, a merged /// face entry an int key plus a counted int set. private static bool TryReadExactWallGeomStep( - Cursor c, ushort classId, out uint owner, out bool joinsTop, out string? failure, bool anyVersion = false) + Cursor c, ushort classId, out uint owner, out bool joinsTop, out string? failure, + out (int Offset, uint Count) topTargets, bool anyVersion = false) { + topTargets = default; owner = 0; joinsTop = false; failure = null; @@ -5681,11 +6168,13 @@ byte U8() case 2262: { uint targets = Count(); + int targetsOffset = c.Pos; Skip(4L * targets); int baseOrTop = ReadI32(c); ReadI32(c); if (targets == 0 || baseOrTop is not (0 or 1)) { failure = "join to roof"; return false; } joinsTop = baseOrTop == 1; + if (joinsTop) topTargets = (targetsOffset, targets); break; } case 4098: @@ -5925,10 +6414,11 @@ bool TryOrientation(bool reverseFirst, out List ordered) } /// Decode a CurveElem (0x346) block fully (root + all deferred objects) and - /// return the curve's line style (BUILDING_CURVE_GSTYLE) and length (CURVE_ELEM_LENGTH). + /// return the curve's line style, length, and the geometry of a closed horizontal circle. /// Detail arcs store geometry as deferred GArc/GLine/GEllipse objects the pattern scan /// couldn't reach; the full schema walk with rules R1-R7 recovers them. - public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int blockStart, uint dataSize) + public static (int GStyle, double Length, (double X, double Y, double Radius)? Circle)? + ExtractCurveGeometry(byte[] d, int blockStart, uint dataSize) { var fields = SerializationFields(0x346); if (fields == null) return null; @@ -5939,6 +6429,7 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl var cur = new Cursor { D = d, Pos = payloadStart, End = payloadEnd - 4, Curves = new() }; var queue = new List<(ushort Cls, uint Id)>(); + (double X, double Y, double Radius)? circle = null; try { foreach (var f in fields) ReadField(cur, f, queue, 0, null); @@ -5961,12 +6452,29 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl if (qf == null) throw Fail; bool isCurve = cls is 0x7B6 or 0x7DA or 0x6C8; if (isCurve) { cur.Ep0 = cur.Ep1 = cur.Radius = cur.XLen = cur.YLen = 0; } + if (cls == 0x7B6) cur.FamilyLineCapture = new(); foreach (var sf in qf) ReadField(cur, sf, queue, 1, null); if (isCurve) cur.Curves!.Add((cls, cur.Ep0, cur.Ep1, cur.Radius, cur.XLen, cur.YLen)); + if (cur.FamilyLineCapture is { } vectors) + { + double sweep = Math.Abs(cur.Ep1 - cur.Ep0); + if ((sweep < 1e-12 || Math.Abs(sweep - 2 * Math.PI) < 1e-9) + && cur.Radius > 0 && double.IsFinite(cur.Radius) + && vectors.GetValueOrDefault("m_center") is [var x, var y, var z] + && double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z) + && vectors.GetValueOrDefault("m_xVec") is [var ax, var ay, var az] + && vectors.GetValueOrDefault("m_yVec") is [var bx, var by, var bz] + && Math.Abs(az) < 1e-8 && Math.Abs(bz) < 1e-8 + && Math.Abs(ax * ax + ay * ay - 1) < 1e-8 + && Math.Abs(bx * bx + by * by - 1) < 1e-8 + && Math.Abs(ax * bx + ay * by) < 1e-8) + circle = (x, y, cur.Radius); + cur.FamilyLineCapture = null; + } } } - catch (DecodeFail) { } // Expected: an unsupported or truncated field ends the scan; fall through to the no-value result + catch (DecodeFail) { circle = null; } // Keep metadata from fully traversed objects. double? length = null; // Prefer a GArc/GEllipse over a GLine (a detail arc may carry a helper line). @@ -6005,7 +6513,8 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl int gs = cur.GStyle == int.MinValue ? -1 : cur.GStyle; if (gs < 0 && length == null) return null; - return (gs, length ?? 0); + // A circle can be accompanied by a straight helper curve. + return (gs, length ?? 0, cur.Pos == cur.End && cur.Curves!.Count(g => g.Kind != 0x6C8) == 1 ? circle : null); } /// Decode the two coordinate representations stored by a BasePoint block. @@ -6636,6 +7145,26 @@ private static void ReadField(Cursor c, TfField f, List<(ushort, uint)> queue, i if (hi == 5) { uint n = ReadU32(c); + if (capture != null && n == 4 + && f is { Declaring: 2247, Name: "m_arrowIds", Type: 14, Mods: 80, Ref: 20 } + or { Declaring: 2251, Name: "m_orderedSubIndices", Type: 4, Mods: 80 }) + { + for (int i = 0; i < 4; i++) capture.Fields[$"{FieldKey(f)}@{i}"] = ReadI32(c); + return; + } + if (capture != null && n == 4 && c.RootClassId == 1829 + && f is { Declaring: 1829, Name: "m_subInstData", Type: 14, Mods: 80, Ref: 1763 }) + { + for (int i = 0; i < 4; i++) + { + var item = new NativeParams(); + ReadInlineStruct(c, 1763, queue, depth, item); + if (item.Fields.TryGetValue("1763:first", out int index) + && item.Fields.TryGetValue("1724:m_masterSymId", out int symbol)) + capture.Fields.TryAdd($"1829:m_subInstData@{index}", symbol); + } + return; + } if (capture != null && c.RootClassId == 1772 && f is { Declaring: 1772, Name: "m_refTypeIds", Type: 4, Mods: 80, Ref: null, Cnt: null }) { @@ -6880,11 +7409,31 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q { switch (f.Declaring, f.Name) { + case (690, "m_colorFillArr") when f is { Type: 14, Mods: 80, Ref: 687 } && capture != null: + capture.RoomColors = ReadRoomColorEntries(c); + return true; + case (693, "m_categoryToSchema") when f is { Type: 14, Mods: 80, Ref: 24 } && capture != null: + { + uint count = ReadU32(c); + if (count == uint.MaxValue) return true; + if (count > 10_000) throw Fail; + for (uint i = 0; i < count; i++) + { + int category = ReadI32(c), scheme = ReadI32(c); + if (category == -2000160) + capture.Fields["693:m_roomColorScheme"] = scheme; + } + return true; + } // An attribute symbol's line-and-text attributes are an inline LineAndTextAttr struct (font id, // category id, background, bold/italic/underline flags: 15 bytes), not the polymorphic pointer // the typeless field would read (which drifts every later field of a GridAttributes root). case (624, "m_lineAndTextAttr") when f.Type == 14 && f.Mods == 0 && f.Ref == null: - if (!c.Take(15)) throw Fail; + if (c.RootClassId is 3972 or 1862 or 836 or 3930) ReadInlineStruct(c, 625, queue, depth, capture); + else if (!c.Take(15)) throw Fail; + return true; + case (838, "m_data") when c.RootClassId == 837 && f is { Type: 14, Mods: 0, Ref: null }: + ReadInlineStruct(c, 839, queue, depth, capture); return true; // A mullion's nominal axis belongs to the first reference of its own symbol, not its trimmed solid. case (1829, "m_refs") when IsSubclassOf(c.RootClassId, 1829) && f.Type == 14 && f.Mods == 81 @@ -6926,6 +7475,27 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q case (2008, "m_bBox" or "m_tightbBox") when f.Type == 13 && f.Mods == 16 && f.Cnt == 2: if (!c.Take(48)) throw Fail; return true; + // The viewer flags occupy two bytes before the annotation crop switch. + case (621, "m_viewerFlags") when f is { Type: 3, Mods: 0 }: + if (!c.Take(2)) throw Fail; + return true; + case (554, "m_boundedSpace") when c.RootClassId == 2505 + && f is { Type: 14, Mods: 0, Ref: 553 } && capture != null: + { + double[] Point() => [ReadF64(c), ReadF64(c), ReadF64(c)]; + double[] origin = Point(); + double[][] axes = [Point(), Point(), Point()]; + var offsets = new double[6]; + for (int i = 0; i < offsets.Length; i++) offsets[i] = ReadF64(c); + if (!c.Take(7)) throw Fail; + var flags = c.D.AsSpan(c.Pos - 7, 7); + if (flags[6] == 1 && flags[..6].IndexOfAnyExcept((byte)0, (byte)1) < 0 + && origin.All(double.IsFinite) && axes.All(axis => axis.All(double.IsFinite)) + && offsets.All(double.IsFinite) + && offsets[0] >= offsets[1] && offsets[2] >= offsets[3] && offsets[4] >= offsets[5]) + capture.ModelClipBox = new(origin, axes, offsets, flags[..6].ToArray().Select(flag => flag == 1).ToArray()); + return true; + } // BoundedSpace (553) composites are wider than Cnt x 8 per element: the basis is 3 x XYZ (72 bytes), // the bound offsets 3 pairs of doubles (48 bytes) and the active flags 3 pairs of booleans (6 bytes). // The generic stride under-reads them and misaligns every following field of a viewer root. @@ -6988,7 +7558,8 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q } // SpatialElementCalculationPointRegenData.m_position is an XYZ struct (three doubles); read here so that they are // kept under the key of the field (the key of the struct's own field, "171:m_xyz", is not a captured one). - case (3639, "m_position") when f.Type == 14 && f.Mods == 0 && f.Ref == 171 && capture != null: + case (3639, "m_position") or (3702, "m_downTextOffset") + when f.Type == 14 && f.Mods == 0 && f.Ref == 171 && capture != null: { if (SerializationFields(171) is not [{ Name: "m_xyz", Type: 7, Mods: 16, Cnt: 3 }]) throw Fail; for (int i = 0; i < 3; i++) capture.DoubleFields[FieldKey(f) + "@" + i] = ReadF64(c); @@ -7017,6 +7588,57 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q if (!c.Take((int)count * 8)) throw Fail; return true; } + case (527, "m_taggedEntitiesCell") when f is { Type: 14, Mods: 0, Ref: null }: + { + if (SerializationFields(528) is not { Count: 1 } entries + || entries[0] is not { Declaring: 528, Name: "m_taggedEntities", Type: 14, Mods: 81, Ref: 528 } + || c.End - c.Pos < 4) throw Fail; + bool single = BitConverter.ToUInt32(c.D, c.Pos) == 1; + int first = queue.Count; + ReadField(c, entries[0], queue, depth + 1, null); + if (capture != null && single && queue.Count == first + 1 && queue[first].Item1 == 3935) + capture.Fields["527:singleTaggedElement"] = 1; + return true; + } + case (844, "m_contourCache") when c.RootClassId == 3595 + && f is { Type: 14, Mods: 80, Ref: null }: + { + var contours = ReadSiteContours(c); + if (capture != null) capture.SiteContours = contours; + return true; + } + case (3936, "m_elbowOffset" or "m_endOffset") when c.RootClassId == 527 + && f is { Type: 14, Mods: 0, Ref: 171 } && capture != null: + capture.DoubleFields[$"3936:{f.Name}@0"] = ReadF64(c); + capture.DoubleFields[$"3936:{f.Name}@1"] = ReadF64(c); + ReadF64(c); + return true; + case (3935, "m_taggedId") when c.RootClassId == 527 && f is { Type: 14, Mods: 0, Ref: 180 } + && capture != null: + capture.Fields["3935:elementOrLinkId"] = ReadI32(c); + capture.Fields["3935:linkedElementId"] = ReadI32(c); + return true; + case (3475, "m_taggedRoomElemId") when f is { Type: 14, Mods: 0, Ref: 180 } && capture != null: + capture.Fields["3475:roomOrLinkId"] = ReadI32(c); + capture.Fields["3475:linkedRoomId"] = ReadI32(c); + return true; + case (1740, "m_contentDocGUID") when f is { Type: 14, Mods: 0, Ref: 30 } + && c.RootClassId == 1772 && capture != null: + if (!c.Take(16)) throw Fail; + capture.StringFields["1740:contentDoc"] = Convert.ToHexString(c.D.AsSpan(c.Pos - 16, 16)); + return true; + case (1807, "m_paramDrivenData") when f is { Type: 14, Mods: 80, Ref: null, Cnt: null }: + ReadInlineContainer(c, 1808, queue, depth); + return true; + case (3927, "m_paramDataFormattingArr") when f is { Type: 14, Mods: 80, Ref: null }: + ReadInlineContainer(c, 3929, queue, depth); + return true; + case (3702, "m_stairsLinkElementId") when f is { Type: 14, Mods: 0, Ref: 180 } && c.TailWalk: + { + int host = ReadI32(c), link = ReadI32(c); + if (capture != null && host > 0 && link == -1) capture.Fields[FieldKey(f)] = host; + return true; + } // The r22 schema's self-reference is not a recursive inline object: // RoomBoundingItem stores (host/link instance ElementId, linked ElementId). // Keep this 4-byte leaf local to exact RoomElem name extraction and the ExtractParams walk @@ -7405,6 +8027,15 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q case (716, "m_offsetGeomMap"): ReadInlineContainer(c, 717, queue, depth, capture); return true; + case (3878, "m_outline") when c.RootClassId == 3878 + && f is { Type: 14, Mods: 0, Ref: 297 } && capture != null: + { + var bounds = new double[6]; + for (int i = 0; i < bounds.Length; i++) bounds[i] = ReadF64(c); + if (bounds.All(double.IsFinite) && bounds[0] <= bounds[3] && bounds[1] <= bounds[4] + && bounds[2] <= bounds[5]) capture.SunStudyOutline = bounds; + return true; + } // Outline.m_minmax is a fixed array of two XYZ POD values. case (297, "m_minmax"): if (!c.Take(2 * 3 * 8)) throw Fail; @@ -7447,14 +8078,48 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q ReadField(c, record, queue, depth + 1, null); return true; } + case (174, "m_equalityFormattingArr") when f is { Type: 14, Mods: 80, Ref: null }: + ReadInlineContainer(c, 175, queue, depth); + return true; + case (175, "m_formatOptions") when f is { Type: 14, Mods: 0, Ref: 175 }: + ReadInlineStruct(c, 84, queue, depth); + return true; + case (160, "m_refPnts") when c.RootClassId == 2335 && capture != null + && f is { Type: 13, Mods: 80, Cnt: null }: + { + int count = ReadI32(c); + if (count is < -1 or > 100_000) throw Fail; + if (count >= 0) capture.Fields["m_refPnts#"] = count; + if (count is < 2 or > 128) + { + if (!c.Take(Math.Max(0, count) * 24)) throw Fail; + return true; + } + capture.DimensionReferences = new List(count); + for (int i = 0; i < count; i++) capture.DimensionReferences.Add(ReadStoredPoint(c)); + return true; + } case (0xA0, "m_ArrSegInfo"): // D1: [count] x inline DimSegInfo + if (c.RootClassId == 2335 && capture?.DimensionReferences != null) + capture.DimensionValues = new List(); ReadInlineContainer(c, 0xA1, queue, depth, capture); return true; case (0xA0, "m_ArrEqualityFormulaInfo_DimEqSegInfoArr"): // D3: inline DimEqSegInfoArr ReadInlineStruct(c, 0xA5, queue, depth); return true; case (0x9F, "m_witnessRefs"): // D4 - ReadInlineContainer(c, 0xA7, queue, depth); + ReadInlineContainer(c, 0xA7, queue, depth, capture?.DimensionValues != null ? capture : null); + return true; + case (161, "m_offset") when capture?.DimensionValues != null && f is { Type: 7, Mods: 16, Cnt: 2 }: + { + double x = ReadF64(c), y = ReadF64(c); + if (x != 0 || y != 0) capture.DimensionValues = null; + return true; + } + case (167, "m_modified" or "m_useDistToDimLn") when capture?.DimensionValues != null + && f is { Type: 1, Mods: 0 }: + if (!c.Take(1)) throw Fail; + if (c.D[c.Pos - 1] != 0) capture.DimensionValues = null; return true; case (0x162, "m_witnessRefs"): // D4 (radial chain) ReadInlineContainer(c, 0x163, queue, depth); @@ -7483,7 +8148,16 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q queue.Add((tag, 0xFFFFFFFF)); } else if (hdr > 1000) throw Fail; + int first = c.Pos, queued = queue.Count; for (int i = 0; i < 3; i++) ReadInlineStruct(c, 0xA3, queue, depth); + if (capture?.DimensionValues is { } values) + { + // Each value owns its text overrides and format state. Only plain measured labels are supported. + if (hdr != 0xFFFFFFFF && queued == queue.Count) + values.Add(BitConverter.ToDouble(c.D, first)); + else + capture.DimensionValues = null; + } return true; } case (0xA1, "m_id"): // D6: plain i32 (may be -1) @@ -7499,6 +8173,9 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q return true; // CurveElem / arc geometry (rules R1-R7) + case (838, "m_referenceType") when c.RootClassId == 837: + if (!c.Take(4)) throw Fail; + return true; case (0x346, "m_referenceType"): // R1: field i32 + a hidden extra i32 if (!c.Take(8)) throw Fail; return true; diff --git a/src/RvtIO/Pdf/PdfDocument.cs b/src/RvtIO/Pdf/PdfDocument.cs index f1fdc371..de5a4571 100644 --- a/src/RvtIO/Pdf/PdfDocument.cs +++ b/src/RvtIO/Pdf/PdfDocument.cs @@ -115,6 +115,9 @@ internal static (int Width, int Height, int Components) ReadHeader(byte[] jpeg) /// An RGB raster image of the document, 8 bits per channel, written with Flate compression. public sealed class PdfRasterImage : IPdfImage { + internal bool Interpolate { get; init; } + internal bool TransparentWhite { get; init; } + /// Width in pixels. public int Width { get; } @@ -161,6 +164,9 @@ public readonly record struct PdfColor(double R, double G, double B) B + (1 - B) * amount); } +internal sealed record PdfLinePattern(double Spacing, double Angle, double X, double Y, double Width, + double Shift = 0, double[]? Segments = null); + /// Horizontal placement of a text anchor. public enum PdfTextAlignment { @@ -193,6 +199,12 @@ public sealed class PdfDocument /// The characters drawn with , which the font's width array and ToUnicode map hold. internal HashSet UsedCharacters { get; } = new(); + internal PdfTrueTypeFont? BoldFont { get; set; } + internal HashSet UsedBoldCharacters { get; } = new(); + + internal List LinePatterns { get; } = new(); + internal List<(double BottomY, double TopY, PdfColor Bottom, PdfColor Top)> VerticalGradients { get; } = new(); + /// The pages, in the order they were added. public IReadOnlyList Pages => _pages; @@ -275,6 +287,19 @@ internal PdfPage(PdfPageSize size, PdfDocument document) public void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres = 0.25, double gray = 0) { Stroke(widthMillimetres, gray); + AppendLine(x1, y1, x2, y2); + } + + internal void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres, PdfColor color) + { + Stroke(widthMillimetres, 0); + _content.Append(Number(color.R)).Append(' ').Append(Number(color.G)).Append(' ') + .Append(Number(color.B)).Append(" RG\n"); + AppendLine(x1, y1, x2, y2); + } + + private void AppendLine(double x1, double y1, double x2, double y2) + { _content.Append(Number(Points(x1))).Append(' ').Append(Number(Points(y1))).Append(" m ") .Append(Number(Points(x2))).Append(' ').Append(Number(Points(y2))).Append(" l S\n"); } @@ -294,13 +319,31 @@ public void DrawArc(double centerX, double centerY, double radius, double startD if (endDegrees < startDegrees) (startDegrees, endDegrees) = (endDegrees, startDegrees); double span = endDegrees - startDegrees; if (span <= 0) return; + Stroke(widthMillimetres, gray); + AppendArc(centerX, centerY, radius, startDegrees, span); + _content.Append("S\n"); + } + + internal void DrawFilledCircle(double centerX, double centerY, double radius, double widthMillimetres, + PdfColor fill, PdfColor outline) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(radius); + Stroke(widthMillimetres, 0); + _content.Append(Number(outline.R)).Append(' ').Append(Number(outline.G)).Append(' ') + .Append(Number(outline.B)).Append(" RG\n"); + FillColor(fill); + AppendArc(centerX, centerY, radius, 0, 360); + _content.Append("h B\n"); + } + + private void AppendArc(double centerX, double centerY, double radius, double startDegrees, double span) + { double sweep = span * Math.PI / 180; int segments = Math.Max(1, (int)Math.Ceiling(sweep / (Math.PI / 2))); double step = sweep / segments; double handle = 4.0 / 3.0 * Math.Tan(step / 4); double angle = startDegrees * Math.PI / 180; double x0 = centerX + radius * Math.Cos(angle), y0 = centerY + radius * Math.Sin(angle); - Stroke(widthMillimetres, gray); _content.Append(Number(Points(x0))).Append(' ').Append(Number(Points(y0))).Append(" m "); for (int i = 0; i < segments; i++) { @@ -315,7 +358,6 @@ public void DrawArc(double centerX, double centerY, double radius, double startD .Append(Number(Points(x3))).Append(' ').Append(Number(Points(y3))).Append(" c "); angle = next; } - _content.Append("S\n"); } /// Draws a polyline through the points, optionally closed, either stroked or filled. @@ -351,6 +393,159 @@ public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widt _content.Append(stroke && fillColor != null ? "B\n" : stroke ? "S\n" : "f\n"); } + internal HashSet LinePatternIndices { get; } = []; + internal HashSet VerticalGradientIndices { get; } = []; + + internal void FillVerticalGradient(double x, double y, double width, double height, + PdfColor bottom, PdfColor top) + { + if (!(width > 0 && height > 0)) return; + var gradient = (Points(y), Points(y + height), bottom, top); + int index = _document.VerticalGradients.IndexOf(gradient); + if (index < 0) + { + index = _document.VerticalGradients.Count; + _document.VerticalGradients.Add(gradient); + } + VerticalGradientIndices.Add(index); + BeginClip(x, y, width, height); + _content.Append("/Sh").Append(index).Append(" sh\n"); + EndClip(); + } + + internal void DrawRoundDashedPolyline(IReadOnlyList<(double X, double Y)> points, double width, double[] dashes) + { + _content.Append("q 1 J 1 j\n"); + SetDashPoints(dashes); + DrawPolyline(points, width); + _content.Append("Q\n"); + } + + internal void FillWithParallelLines(IReadOnlyList<(double X, double Y)> polygon, double spacing, + double angle, double anchorX, double anchorY, double width) + => FillWithParallelLines([polygon], spacing, angle, anchorX, anchorY, width); + + internal void FillWithParallelLines(IReadOnlyList> rings, double spacing, + double angle, double anchorX, double anchorY, double width) + => FillWithLinePattern(rings, new PdfLinePattern(spacing, angle, anchorX, anchorY, width)); + + internal void FillWithClippedParallelLines(IReadOnlyList> rings, + double spacing, double angle, double anchorX, double anchorY, double width) + { + if (rings.Count == 0 || rings[0].Count < 3 || !(spacing > width && width > 0) + || !double.IsFinite(spacing) || !double.IsFinite(angle) + || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return; + + double sin = Math.Sin(angle), cos = Math.Cos(angle); + double minAcross = double.PositiveInfinity, maxAcross = double.NegativeInfinity; + double minAlong = double.PositiveInfinity, maxAlong = double.NegativeInfinity; + foreach (var ring in rings) + foreach (var (x, y) in ring) + { + double across = x * sin - y * cos, along = x * cos + y * sin; + minAcross = Math.Min(minAcross, across); + maxAcross = Math.Max(maxAcross, across); + minAlong = Math.Min(minAlong, along); + maxAlong = Math.Max(maxAlong, along); + } + if (!(maxAcross > minAcross && maxAlong > minAlong)) return; + + double half = width / 2; + double phase = (anchorX * sin - anchorY * cos) % spacing; + double first = phase + Math.Ceiling((minAcross - half - phase) / spacing) * spacing; + double last = maxAcross + half; + double count = 1 + Math.Floor((last - first) / spacing); + if (!(count > 0)) return; + // Keep tiling for very dense patterns to bound the size of the filled path. + if (count > 4096) + { + FillWithParallelLines(rings, spacing, angle, anchorX, anchorY, width); + return; + } + + BeginPolygonClip(rings, evenOdd: false); + FillPolygonUnion(Strips((int)count), 0); + EndClip(); + + IEnumerable> Strips(int stripCount) + { + for (int i = 0; i < stripCount; i++) + { + double across = first + i * spacing; + yield return [InPage(across - half, minAlong), InPage(across + half, minAlong), + InPage(across + half, maxAlong), InPage(across - half, maxAlong)]; + } + } + + (double X, double Y) InPage(double across, double along) => + (across * sin + along * cos, along * sin - across * cos); + } + + internal void FillWithLinePattern(IReadOnlyList> rings, PdfLinePattern pattern) + { + var (spacing, angle, anchorX, anchorY, width, _, _) = pattern; + if (rings.Count == 0 || rings[0].Count < 3 || !(spacing > width && width > 0) + || !double.IsFinite(spacing) || !double.IsFinite(angle) + || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return; + int index = _document.LinePatterns.IndexOf(pattern); + if (index < 0) + { + index = _document.LinePatterns.Count; + _document.LinePatterns.Add(pattern); + } + LinePatternIndices.Add(index); + _content.Append("q /Pattern cs /P").Append(index).Append(" scn\n"); + AppendFillRings(rings); + _content.Append("f Q\n"); + } + + // Outer rings share one orientation and holes use the opposite orientation; nonzero winding unions overlaps. + internal List FillOpacities { get; } = []; + + internal void FillPolygonUnion(IEnumerable> rings, double gray, + double opacity = 1) + { + if (opacity <= 0) return; + if (opacity < 1) + { + int index = FillOpacities.IndexOf(opacity); + if (index < 0) + { + index = FillOpacities.Count; + FillOpacities.Add(opacity); + } + _content.Append("q /Gs").Append(index).Append(" gs\n"); + } + Fill(gray); + AppendFillRings(rings); + _content.Append(opacity < 1 ? "f\nQ\n" : "f\n"); + } + + private void AppendFillRings(IEnumerable> rings) + { + foreach (var ring in rings) + { + if (ring.Count < 3) continue; + for (int i = 0; i < ring.Count; i++) + _content.Append(Number(Points(ring[i].X))).Append(' ').Append(Number(Points(ring[i].Y))) + .Append(i == 0 ? " m " : " l "); + _content.Append("h "); + } + } + + internal void BeginPolygonClip(IEnumerable> rings, bool evenOdd = true) + { + _content.Append("q "); + AppendFillRings(rings); + _content.Append(evenOdd ? "W* n\n" : "W n\n"); + } + + internal void IntersectPolygonClip(IEnumerable> rings) + { + AppendFillRings(rings); + _content.Append("W* n\n"); + } + /// Starts a clipping region: everything drawn until is cut to the rectangle. /// Left edge, millimetres. /// Bottom edge, millimetres. @@ -406,7 +601,9 @@ public void SetDash(double dashMillimetres, double gapMillimetres) => /// Sets an arbitrary dash pattern of the following strokes, in PDF points /// (a dash array alternating dash and gap lengths, starting with a dash). /// Dash and gap lengths in points. - public void SetDashPoints(double[] points) + public void SetDashPoints(double[] points) => SetDashPoints(points, 0); + + internal void SetDashPoints(double[] points, double phase) { _content.Append('['); for (int i = 0; i < points.Length; i++) @@ -414,7 +611,7 @@ public void SetDashPoints(double[] points) if (i > 0) _content.Append(' '); _content.Append(Number(points[i])); } - _content.Append("] 0 d\n"); + _content.Append("] ").Append(Number(phase)).Append(" d\n"); } /// Clears the dash pattern. @@ -451,21 +648,28 @@ public void DrawRectangle(double x, double y, double width, double height, doubl /// No font is set and the text holds a character outside printable ASCII. public void DrawText(string text, double x, double y, double heightMillimetres = 3, PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) + => DrawStyledText(text, x, y, heightMillimetres, alignment, gray, useBold: false); + + internal void DrawStyledText(string text, double x, double y, double heightMillimetres, + PdfTextAlignment alignment, double gray, bool useBold, PdfColor? ink = null) { if (string.IsNullOrEmpty(text)) return; ArgumentOutOfRangeException.ThrowIfNegativeOrZero(heightMillimetres); double fontPoints = heightMillimetres * 72.0 / 25.4; // Text is painted with the non-stroking colour, so set the fill (not the stroke) colour: after a white-filled // bubble or floor the fill could still be white and the text would disappear. - Fill(gray); - if (_document.Font is { } font) + if (ink is { } color) FillColor(color); + else Fill(gray); + var bold = useBold ? _document.BoldFont : null; + if ((bold ?? _document.Font) is { } font) { + var used = bold != null ? _document.UsedBoldCharacters : _document.UsedCharacters; var encoded = new StringBuilder(text.Length * 4); double width = 0; foreach (char character in text) { int glyph = font.GlyphOf(character); - _document.UsedCharacters.Add(character); + used.Add(character); width += font.AdvanceOf(glyph) / (double)font.UnitsPerEm * heightMillimetres; encoded.Append(glyph.ToString("X4", CultureInfo.InvariantCulture)); } @@ -475,7 +679,7 @@ public void DrawText(string text, double x, double y, double heightMillimetres = PdfTextAlignment.Right => x - width, _ => x, }; - _content.Append("BT /F2 ").Append(Number(fontPoints)).Append(" Tf ") + _content.Append(bold != null ? "BT /F3 " : "BT /F2 ").Append(Number(fontPoints)).Append(" Tf ") .Append(Number(Points(anchor))).Append(' ').Append(Number(Points(y))).Append(" Td <") .Append(encoded).Append("> Tj ET\n"); return; diff --git a/src/RvtIO/Pdf/PdfFonts.cs b/src/RvtIO/Pdf/PdfFonts.cs index c0592f57..b5084140 100644 --- a/src/RvtIO/Pdf/PdfFonts.cs +++ b/src/RvtIO/Pdf/PdfFonts.cs @@ -19,10 +19,22 @@ public static class PdfFonts /// Loads the first font file of that exists and parses. /// The file that was used, or null when none exists. /// The font, or null when no candidate is a TrueType font this reader supports. - public static PdfTrueTypeFont? TryFind(out string? path) + public static PdfTrueTypeFont? TryFind(out string? path) => TryFind(Candidates, out path); + + internal static PdfTrueTypeFont? TryFindBold() => TryFind( + [ + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", + "/System/Library/Fonts/Supplemental/Arial Bold.ttf", + @"C:\Windows\Fonts\arialbd.ttf", + @"C:\Windows\Fonts\segoeuib.ttf", + @"C:\Windows\Fonts\tahomabd.ttf" + ], out _); + + private static PdfTrueTypeFont? TryFind(IReadOnlyList candidates, out string? path) { path = null; - foreach (string candidate in Candidates) + foreach (string candidate in candidates) { if (!File.Exists(candidate)) continue; try diff --git a/src/RvtIO/Pdf/PdfSerializer.cs b/src/RvtIO/Pdf/PdfSerializer.cs index 093ce426..6b8dd9ca 100644 --- a/src/RvtIO/Pdf/PdfSerializer.cs +++ b/src/RvtIO/Pdf/PdfSerializer.cs @@ -14,21 +14,36 @@ internal static class PdfSerializer private const int PagesId = 2; private const int HelveticaId = 3; private const int Type0Id = 4; - private const int CidFontId = 5; - private const int DescriptorId = 6; - private const int FontFileId = 7; - private const int ToUnicodeId = 8; private const int FirstPageWithFont = 9; private const int FirstPageWithoutFont = 4; + private static string EncodeName(string value) + { + var name = new StringBuilder(); + foreach (byte b in Encoding.UTF8.GetBytes(value)) + { + if (b is >= 33 and <= 126 && !"#%()/<>[]{}".Contains((char)b)) + name.Append((char)b); + else + name.Append('#').Append(b.ToString("X2", CultureInfo.InvariantCulture)); + } + return name.ToString(); + } + internal static void Write(Stream stream, PdfDocument document) { IReadOnlyList pages = document.Pages; PdfTrueTypeFont? font = document.Font; int firstPage = font != null ? FirstPageWithFont : FirstPageWithoutFont; + var bold = document.UsedBoldCharacters.Count > 0 ? document.BoldFont : null; + int boldId = firstPage; + if (bold != null) firstPage += 5; int PageId(int index) => firstPage + index * 2; int ContentId(int index) => firstPage + index * 2 + 1; int ImageId(int index) => firstPage + pages.Count * 2 + index; + int PatternId(int index) => ImageId(document.Images.Count) + index; + int GradientId(int index) => PatternId(document.LinePatterns.Count) + index; + int outlinesId = GradientId(document.VerticalGradients.Count); var offsets = new List(); long position = 0; @@ -56,7 +71,6 @@ void BeginObject(int id) outlines.Add((i, title)); if (outlines.Count > 0) { - int outlinesId = firstPage + pages.Count * 2 + document.Images.Count; Raw($"<< /Type /Catalog /Pages {PagesId} 0 R /Outlines {outlinesId} 0 R /PageMode /UseOutlines >>\n"); } else @@ -75,47 +89,48 @@ void BeginObject(int id) Raw("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\n"); EndObject(); - if (font != null) + void WriteFont(PdfTrueTypeFont font, HashSet characters, int id) { + string name = EncodeName(font.Name); double scale = 1000.0 / font.UnitsPerEm; - BeginObject(Type0Id); - Raw($"<< /Type /Font /Subtype /Type0 /BaseFont /{font.Name} /Encoding /Identity-H " - + $"/DescendantFonts [ {CidFontId} 0 R ] /ToUnicode {ToUnicodeId} 0 R >>\n"); + BeginObject(id); + Raw($"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H " + + $"/DescendantFonts [ {(id + 1)} 0 R ] /ToUnicode {(id + 4)} 0 R >>\n"); EndObject(); var widths = new StringBuilder(); var used = new SortedSet(); - foreach (char character in document.UsedCharacters) used.Add(font.GlyphOf(character)); + foreach (char character in characters) used.Add(font.GlyphOf(character)); foreach (int glyph in used) { widths.Append(glyph).Append(" [ ") .Append(Number(font.AdvanceOf(glyph) * scale)).Append(" ] "); } - BeginObject(CidFontId); - Raw($"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{font.Name} " + BeginObject((id + 1)); + Raw($"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} " + "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> " - + $"/FontDescriptor {DescriptorId} 0 R /CIDToGIDMap /Identity /DW 1000 /W [ {widths.ToString().TrimEnd()} ] >>\n"); + + $"/FontDescriptor {(id + 2)} 0 R /CIDToGIDMap /Identity /DW 1000 /W [ {widths.ToString().TrimEnd()} ] >>\n"); EndObject(); - BeginObject(DescriptorId); - Raw($"<< /Type /FontDescriptor /FontName /{font.Name} /Flags 32 " + BeginObject((id + 2)); + Raw($"<< /Type /FontDescriptor /FontName /{name} /Flags 32 " + $"/FontBBox [ {Number(font.XMin * scale)} {Number(font.YMin * scale)} " + $"{Number(font.XMax * scale)} {Number(font.YMax * scale)} ] /ItalicAngle 0 " + $"/Ascent {Number(font.Ascent * scale)} /Descent {Number(font.Descent * scale)} " - + $"/CapHeight {Number(font.Ascent * 0.7 * scale)} /StemV 80 /FontFile2 {FontFileId} 0 R >>\n"); + + $"/CapHeight {Number(font.Ascent * 0.7 * scale)} /StemV 80 /FontFile2 {(id + 3)} 0 R >>\n"); EndObject(); byte[] file = font.File_; byte[] fontPayload = document.Compress ? Zlib(file) : file; - BeginObject(FontFileId); + BeginObject((id + 3)); Raw($"<< /Length {fontPayload.Length} /Length1 {file.Length}" + (document.Compress ? " /Filter /FlateDecode" : string.Empty) + " >>\nstream\n"); WriteBytes(fontPayload); Raw("\nendstream\n"); EndObject(); - BeginObject(ToUnicodeId); - string cmap = ToUnicode(document, font); + BeginObject((id + 4)); + string cmap = ToUnicode(characters, font); byte[] cmapBytes = Encoding.ASCII.GetBytes(cmap); byte[] cmapPayload = document.Compress ? Zlib(cmapBytes) : cmapBytes; Raw($"<< /Length {cmapPayload.Length}" @@ -125,17 +140,30 @@ void BeginObject(int id) EndObject(); } + if (font != null) WriteFont(font, document.UsedCharacters, Type0Id); + if (bold != null) WriteFont(bold, document.UsedBoldCharacters, boldId); + for (int i = 0; i < pages.Count; i++) { PdfPage page = pages[i]; var (width, height) = page.Size.InPoints; string fonts = font != null ? $"/F1 {HelveticaId} 0 R /F2 {Type0Id} 0 R" : $"/F1 {HelveticaId} 0 R"; + if (bold != null) fonts += $" /F3 {boldId} 0 R"; var xobjects = new StringBuilder(); for (int k = 0; k < page.Images.Count; k++) xobjects.Append($"/Im{k} {ImageId(document.ImageIndex(page.Images[k]))} 0 R "); - string resources = xobjects.Length == 0 - ? $"/Resources << /Font << {fonts} >> >>" - : $"/Resources << /Font << {fonts} >> /XObject << {xobjects.ToString().TrimEnd()} >> >>"; + string resources = $"/Resources << /Font << {fonts} >>"; + if (xobjects.Length > 0) resources += $" /XObject << {xobjects.ToString().TrimEnd()} >>"; + if (page.LinePatternIndices.Count > 0) + resources += $" /Pattern << {string.Join(" ", page.LinePatternIndices.Order() + .Select(index => $"/P{index} {PatternId(index)} 0 R"))} >>"; + if (page.VerticalGradientIndices.Count > 0) + resources += $" /Shading << {string.Join(" ", page.VerticalGradientIndices.Order() + .Select(index => $"/Sh{index} {GradientId(index)} 0 R"))} >>"; + if (page.FillOpacities.Count > 0) + resources += $" /ExtGState << {string.Join(" ", page.FillOpacities.Select((opacity, index) => + $"/Gs{index} << /Type /ExtGState /ca {Number(opacity)} >>"))} >>"; + resources += " >>"; BeginObject(PageId(i)); Raw($"<< /Type /Page /Parent {PagesId} 0 R /MediaBox [0 0 {Number(width)} {Number(height)}] " + resources + $" /Contents {ContentId(i)} 0 R >>\n"); @@ -162,17 +190,80 @@ void BeginObject(int id) BeginObject(ImageId(k)); Raw($"<< /Type /XObject /Subtype /Image /Width {image.Width} /Height {image.Height} " + $"/ColorSpace {image.ColorSpace} /BitsPerComponent 8" + filter + + (image is PdfRasterImage { Interpolate: true } ? " /Interpolate true" : string.Empty) + + (image is PdfRasterImage { TransparentWhite: true } ? " /Mask [255 255 255 255 255 255]" : string.Empty) + $" /Length {pixels.Length} >>\nstream\n"); WriteBytes(pixels); Raw("\nendstream\n"); EndObject(); } - // The document outline, after the images: one bookmark per titled page, in page order, each pointing + const double pointsPerMillimetre = 72.0 / 25.4; + double span = pages.Select(p => p.Size.InPoints.Width + p.Size.InPoints.Height).DefaultIfEmpty().Max(); + for (int k = 0; k < document.LinePatterns.Count; k++) + { + var (spacing, angle, x, y, width, shift, segments) = document.LinePatterns[k]; + double step = spacing * pointsPerMillimetre; + double inkWidth = width * pointsPerMillimetre; + double sin = Math.Sin(angle), cos = Math.Cos(angle); + if (segments != null) + { + double period = segments.Sum() * pointsPerMillimetre; + double skew = Math.IEEERemainder(shift * pointsPerMillimetre, period) / step; + double half = inkWidth / 2, pad = Math.Abs(skew) * half; + static string Exact(double value) => value.ToString("0.#########", CultureInfo.InvariantCulture); + string dashedMatrix = $"{Exact(cos)} {Exact(sin)} {Exact(-sin + cos * skew)} {Exact(cos + sin * skew)} " + + $"{Exact(x * pointsPerMillimetre)} {Exact(y * pointsPerMillimetre)}"; + var tile = new StringBuilder("0 g\n"); + double start = 0; + for (int i = 0; i < segments.Length; i++) + { + double end = start + segments[i] * pointsPerMillimetre; + if (i % 2 == 0 && end > start) + { + double slant = skew * half; + tile.Append($"{Exact(start + slant)} {Exact(-half)} m {Exact(end + slant)} {Exact(-half)} l " + + $"{Exact(end - slant)} {Exact(half)} l {Exact(start - slant)} {Exact(half)} l h "); + } + start = end; + } + tile.Append("f\n"); + BeginObject(PatternId(k)); + Raw($"<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 2 " + + $"/BBox [{Exact(-pad)} {Exact(-step / 2)} {Exact(period + pad)} {Exact(step / 2)}] " + + $"/XStep {Exact(period)} /YStep {Exact(step)} /Matrix [{dashedMatrix}] /Resources << >> /Length {tile.Length} >>\nstream\n"); + Raw(tile.ToString()); + Raw("endstream\n"); + EndObject(); + continue; + } + double normalOffset = ((x * sin - y * cos) * pointsPerMillimetre) % step - step / 2; + string matrix = $"{Number(sin)} {Number(-cos)} {Number(cos)} {Number(sin)} " + + $"{Number(sin * normalOffset)} {Number(-cos * normalOffset)}"; + // One tile spans the page along the line, so the print has no seams between line ends. + string ink = $"0 g {Number((step - inkWidth) / 2)} {Number(-span)} {Number(inkWidth)} {Number(2 * span)} re f\n"; + BeginObject(PatternId(k)); + Raw($"<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 2 /BBox [0 {Number(-span)} {Number(step)} {Number(span)}] " + + $"/XStep {Number(step)} /YStep {Number(2 * span)} /Matrix [{matrix}] /Resources << >> /Length {ink.Length} >>\nstream\n"); + Raw(ink); + Raw("endstream\n"); + EndObject(); + } + + for (int k = 0; k < document.VerticalGradients.Count; k++) + { + var (bottomY, topY, bottom, top) = document.VerticalGradients[k]; + string Rgb(PdfColor color) => $"{Number(color.R)} {Number(color.G)} {Number(color.B)}"; + BeginObject(GradientId(k)); + Raw($"<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 {Number(bottomY)} 0 {Number(topY)}] " + + $"/Function << /FunctionType 2 /Domain [0 1] /C0 [{Rgb(bottom)}] /C1 [{Rgb(top)}] /N 1 >> >>\n"); + EndObject(); + } + + // The document outline, after the resources: one bookmark per titled page, in page order, each pointing // at its page. Untitled documents write no outline, as before. if (outlines.Count > 0) { - int outlinesId = firstPage + pages.Count * 2 + document.Images.Count; int firstItem = outlinesId + 1; BeginObject(outlinesId); Raw($"<< /Type /Outlines /First {firstItem} 0 R /Last {firstItem + outlines.Count - 1} 0 R " @@ -227,10 +318,10 @@ private static byte[] Zlib(byte[] data) return output.ToArray(); } - private static string ToUnicode(PdfDocument document, PdfTrueTypeFont font) + private static string ToUnicode(HashSet characters, PdfTrueTypeFont font) { var byGlyph = new SortedDictionary(); - foreach (char character in document.UsedCharacters) + foreach (char character in characters) byGlyph.TryAdd(font.GlyphOf(character), character); var text = new StringBuilder(); text.Append("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n") diff --git a/src/RvtIO/Pdf/PdfTrueTypeFont.cs b/src/RvtIO/Pdf/PdfTrueTypeFont.cs index f67a5e3b..bfb8c528 100644 --- a/src/RvtIO/Pdf/PdfTrueTypeFont.cs +++ b/src/RvtIO/Pdf/PdfTrueTypeFont.cs @@ -53,6 +53,10 @@ public PdfTrueTypeFont(byte[] file, string name) XMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 40)); YMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 42)); + if (tables.TryGetValue("OS/2", out var os2) && os2.Length >= 90 + && os2.Offset >= 0 && os2.Offset <= file.Length - 90 + && BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(os2.Offset)) >= 2) + CapHeight = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(os2.Offset + 88)); Ascent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 4)); Descent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 6)); int metrics = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(hhea.Offset + 34)); @@ -87,6 +91,7 @@ public PdfTrueTypeFont(byte[] file, string name) internal int XMax { get; } internal int YMax { get; } internal int Ascent { get; } + internal int CapHeight { get; } internal int Descent { get; } /// The font file, embedded whole. diff --git a/src/RvtIO/Pdf/WindowsArialLayout.cs b/src/RvtIO/Pdf/WindowsArialLayout.cs new file mode 100644 index 00000000..f23e2710 --- /dev/null +++ b/src/RvtIO/Pdf/WindowsArialLayout.cs @@ -0,0 +1,83 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace RvtIO.Pdf; + +internal static class WindowsArialLayout +{ + private const double MillimetresPerPixel = 25.4 / 384; + + internal static bool TryMeasure(string text, double sizeMm, out double width, out double ascent) + { + width = ascent = 0; + // shortcut: the verified 12 pt Arial layout uses a 64-pixel em, extend when other sizes are verified. + if (!OperatingSystem.IsWindows() || Math.Abs(sizeMm - 64 * MillimetresPerPixel) > 1e-6) + return false; + nint dc = CreateCompatibleDC(0); + if (dc == 0) return false; + nint font = CreateFontW(-64, 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 0, 0, "Arial"); + nint previous = 0; + try + { + if (font == 0) return false; + previous = SelectObject(dc, font); + var face = new StringBuilder(32); + if (previous == 0 || previous == -1 || GetTextFaceW(dc, face.Capacity, face) == 0 + || !string.Equals(face.ToString(), "Arial", StringComparison.OrdinalIgnoreCase) + || !GetTextExtentPoint32W(dc, text, text.Length, out var size) + || !GetTextMetricsW(dc, out var metrics)) + return false; + width = size.Width * MillimetresPerPixel; + ascent = metrics.Ascent * MillimetresPerPixel; + return width > 0 && ascent > 0; + } + finally + { + if (previous != 0 && previous != -1) SelectObject(dc, previous); + if (font != 0) DeleteObject(font); + DeleteDC(dc); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct TextSize + { + public int Width; + public int Height; + } + + [StructLayout(LayoutKind.Explicit, Size = 60)] + private struct TextMetrics + { + [FieldOffset(4)] + public int Ascent; + } + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern nint CreateCompatibleDC(nint device); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + private static extern nint CreateFontW(int height, int width, int escapement, int orientation, int weight, + uint italic, uint underline, uint strikeout, uint charSet, uint outputPrecision, uint clipPrecision, + uint quality, uint pitchAndFamily, string face); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern nint SelectObject(nint device, nint obj); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + private static extern int GetTextFaceW(nint device, int count, StringBuilder face); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetTextExtentPoint32W(nint device, string text, int count, out TextSize size); + + [DllImport("gdi32.dll", ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetTextMetricsW(nint device, out TextMetrics metrics); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern int DeleteObject(nint obj); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern int DeleteDC(nint device); +} diff --git a/src/RvtIO/Print/CircularAnnotations.cs b/src/RvtIO/Print/CircularAnnotations.cs new file mode 100644 index 00000000..3c30431f --- /dev/null +++ b/src/RvtIO/Print/CircularAnnotations.cs @@ -0,0 +1,89 @@ +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class CircularAnnotations +{ + private const double FeetToMillimetres = 304.8; + private const double PointsToMillimetres = 25.4 / 72; + + internal sealed record Placement(double X, double Y, double Factor, RevitFileInfo.CircularAnnotationStyle Style); + + internal static IReadOnlyList Project(RvtDocument? document, int? viewId, + double[]? right = null, double[]? up = null) + { + if (viewId is not int view || document?.RawData.CircularAnnotations?.GetValueOrDefault(view) is not { } source) + return []; + var result = new List(); + foreach (var (t, style) in source) + if (ProjectTransform(t, right, up) is { } projected) + result.Add(new(projected.X, projected.Y, projected.Factor, style)); + return result; + } + + internal static (double X, double Y, double Factor)? ProjectTransform(double[] t, double[]? right, double[]? up) + { + double scale = Dot(t[0], t[3], t[6], right, t[0]); + double other = Dot(t[1], t[4], t[7], up, t[4]); + if (!(scale is > 0 and <= 100_000) || Math.Abs(scale - other) > scale * 1e-8 + || Math.Abs(Dot(t[0], t[3], t[6], up, t[3])) > scale * 1e-8 + || Math.Abs(Dot(t[1], t[4], t[7], right, t[1])) > scale * 1e-8) return null; + return (Dot(t[9], t[10], t[11], right, t[9]) * FeetToMillimetres, + Dot(t[9], t[10], t[11], up, t[10]) * FeetToMillimetres, scale); + + static double Dot(double x, double y, double z, double[]? axis, double fallback) => + axis == null ? fallback : x * axis[0] + y * axis[1] + z * axis[2]; + } + + internal static void DrawViewport(PdfPage page, RvtDocument document, Element? view, + IReadOnlyList items, double scale, double originX, double originY, + double minX, double minY, ViewCropFrame? crop) + { + if (items.Count == 0) return; + + double ToX(double x) => originX + (x - minX) / scale; + double ToY(double y) => originY + (y - minY) / scale; + + bool clip = crop != null && view?.ViewAnnotationCropActive != false; + if (clip) + { + var (x0, y0, x1, y1) = SheetComposer.CropContentRect(crop!); + var (left, right, top, bottom) = view?.ViewAnnotationCrop ?? (0, 0, 0, 0); + double x = ToX(x0) - left * FeetToMillimetres; + double y = ToY(y0) - bottom * FeetToMillimetres; + page.BeginClip(x, y, ToX(x1) + right * FeetToMillimetres - x, + ToY(y1) + top * FeetToMillimetres - y); + } + Draw(page, document, items, scale, ToX, ToY); + if (clip) page.EndClip(); + } + + internal static void Draw(PdfPage page, RvtDocument? document, IReadOnlyList items, double scale, + Func toX, Func toY) + { + if (document == null || items.Count == 0) return; + var regular = page.Owner.Font; + if (regular != null && items.Any(item => item.Style.Bold)) page.Owner.BoldFont ??= PdfFonts.TryFindBold(); + foreach (var (originX, originY, factor, style) in items) + { + double unit = FeetToMillimetres * factor / scale; + double x = toX(originX), y = toY(originY); + double pen = PenWidths.TryAnnotationWidth(document, style.BorderPen, out double width) ? width : 0.1; + var circle = style.Outline; + page.DrawFilledCircle(x + circle.X * unit, y + circle.Y * unit, circle.Radius * unit, pen, + Rgb(style.FillColor), Rgb(style.BorderColor)); + if (regular == null) continue; + var text = style.Text; + var font = style.Bold ? page.Owner.BoldFont ?? regular : regular; + var alignment = (text.Flags & 0x80) != 0 ? PdfTextAlignment.Center + : (text.Flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; + double size = style.FontPoints * PointsToMillimetres * factor / scale; + double baseline = y + text.Oy * unit - size * font.Ascent / font.UnitsPerEm; + page.DrawStyledText(style.Value, x + text.Ox * unit, baseline, size, alignment, 0, style.Bold, Rgb(style.TextColor)); + } + + static PdfColor Rgb(int color) => new((color & 255) / 255d, ((color >> 8) & 255) / 255d, + ((color >> 16) & 255) / 255d); + } +} diff --git a/src/RvtIO/Print/DetailAnnotations.cs b/src/RvtIO/Print/DetailAnnotations.cs new file mode 100644 index 00000000..8ddcbe98 --- /dev/null +++ b/src/RvtIO/Print/DetailAnnotations.cs @@ -0,0 +1,299 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class DetailAnnotations +{ + private const double FeetToMillimetres = 304.8; + private const double PointsToMillimetres = 25.4 / 72; + + internal sealed record BreakLine(List<(double X, double Y)> Line, List<(double X, double Y)> Mask); + internal sealed record LayerHatch(List<(double X, double Y)> Polygon, + IReadOnlyList Grids, double AnchorX, double AnchorY, double? PenWidth = null); + internal sealed record LayerBoundary((double X, double Y) Start, (double X, double Y) End, int CategoryId); + + internal static void AddClosedHostCutHatches(List output, RvtDocument document, Element host, + List<(double X, double Y)> ring, double[] right, double[] up, double[] viewOrigin, + List? boundaries = null, double? penWidth = null) + { + if (document.GetElement(host.TypeId)?.SerializedHostTypeLayers is [{ RawMaterialId: > 0 } layer]) + { + AddMaterialCutHatch(output, document, layer.RawMaterialId, ring, right, up, viewOrigin, penWidth); + return; + } + // shortcut: split rectangular cuts until the layer bands can be clipped to a nonrectangular ring. + if (ring.Count != 4) return; + var cuts = ring.Select((a, i) => (X1: a.X, Y1: a.Y, X2: ring[(i + 1) % ring.Count].X, + Y2: ring[(i + 1) % ring.Count].Y)).ToArray(); + if (cuts.Any(c => Math.Abs(c.X1 - c.X2) > 1e-5 && Math.Abs(c.Y1 - c.Y2) > 1e-5)) return; + AddLayerHatches(output, document, host, cuts, right, up, viewOrigin, boundaries, penWidth: penWidth); + } + + internal static void AddMaterialCutHatch(List output, RvtDocument document, int materialId, + List<(double X, double Y)> ring, double[] right, double[] up, double[] viewOrigin, double? penWidth = null) + { + if (CutGrids(document, materialId) is { } grids) + output.Add(new(ring, grids, Project(viewOrigin, right), Project(viewOrigin, up), penWidth)); + } + + internal static void AddLayerHatches(List output, RvtDocument document, Element host, + IEnumerable<(double X1, double Y1, double X2, double Y2)> cuts, + double[] right, double[] up, double[] viewOrigin, List? boundaries = null, + List>? wallSections = null, double? penWidth = null) + { + bool horizontalHost = host.CategoryId is (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Ceilings; + if (Math.Abs(up[2] - 1) > 1e-6 + || document.GetElement(host.TypeId)?.SerializedHostTypeLayers is not { Length: > 1 } layers) return; + bool exteriorAtLow = false; + if (!horizontalHost) + { + if (host.CategoryId != (int)BuiltInCategory.OST_Walls + || host.Location is not { CurveType: "Line", Direction: { Length: 3 } axis } + || host.SerializedWallFlipped is not bool flipped + || Math.Abs(axis[0] * right[0] + axis[1] * right[1]) > 1e-6) return; + double normal = (-axis[1] * right[0] + axis[0] * right[1]) * (flipped ? -1 : 1); + if (!(Math.Abs(normal) > 0.999)) return; + exteriorAtLow = normal < 0; + } + else + { + cuts = cuts.Select(c => (c.Y1, c.X1, c.Y2, c.X2)); + } + + var widths = layers.Select(l => BitConverter.Int64BitsToDouble(l.LayerWidthBits) * FeetToMillimetres).ToArray(); + if (widths.Any(w => !(w is >= 0 and < 10000))) return; + var sides = cuts.Where(c => Math.Abs(c.X1 - c.X2) < 0.01 && Math.Abs(c.Y1 - c.Y2) > 0.1) + .Select(c => (X: c.X1, Bottom: Math.Min(c.Y1, c.Y2), Top: Math.Max(c.Y1, c.Y2))).ToArray(); + if (sides.Length < 2) return; + double left = sides.Min(c => c.X), rightmost = sides.Max(c => c.X); + if (Math.Abs(rightmost - left - widths.Sum()) > 0.1) return; + double start = exteriorAtLow ? left : rightmost; + double direction = exteriorAtLow ? 1 : -1; + double anchorX = Project(viewOrigin, right), anchorY = Project(viewOrigin, up); + for (int i = 0; i < layers.Length; i++) + { + double end = start + direction * widths[i]; + if (end != start) + { + var grids = CutGrids(document, layers[i].RawMaterialId); + var layerLines = end > left + 0.01 && end < rightmost - 0.01 ? boundaries : null; + if (wallSections != null) + { + double bandLeft = Math.Min(start, end), bandRight = Math.Max(start, end); + foreach (var section in wallSections) + { + if (grids != null) + { + var band = ElevationPrinter.ClipToWindow(section, bandLeft, bandRight, + double.NegativeInfinity, double.PositiveInfinity); + if (band.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(band)) > 1e-6) + output.Add(new(band, grids, anchorX, anchorY, penWidth)); + } + if (layerLines != null) + { + var ring = section.Select(point => new[] { point.X, point.Y, 0d }).ToList(); + foreach (var (a, b) in ElevationPrinter.CutChords(ring, [end, 0, 0], [1, 0, 0])) + layerLines.Add(new((end, a[1]), (end, b[1]), host.CategoryId!.Value)); + } + } + } + else if (grids != null || layerLines != null) + foreach (var a in sides.Where(c => Math.Abs(c.X - left) < 0.01)) + foreach (var b in sides.Where(c => Math.Abs(c.X - rightmost) < 0.01)) + { + double low = Math.Max(a.Bottom, b.Bottom), high = Math.Min(a.Top, b.Top); + if (high <= low) continue; + if (grids != null) + output.Add(new([Point(start, low), Point(end, low), Point(end, high), Point(start, high)], + grids, anchorX, anchorY, penWidth)); + layerLines?.Add(new(Point(end, low), Point(end, high), host.CategoryId!.Value)); + } + } + start = end; + } + + (double X, double Y) Point(double across, double along) => + horizontalHost ? (along, across) : (across, along); + } + + internal static IReadOnlyList? CutGrids(RvtDocument document, int materialId) + { + if (document.RawData.MaterialPatterns?.TryGetValue(materialId, out var material) != true + || document.RawData.FillPatterns?.TryGetValue(material.CutPatternId, out var pattern) != true + || pattern.Grids.Count == 0 || !pattern.Grids.All(grid => + grid.Target == 0 && double.IsFinite(grid.Angle) && double.IsFinite(grid.Offset) + && Math.Abs(grid.Offset) > 0.0001 && double.IsFinite(grid.OriginX) && double.IsFinite(grid.OriginY) + && double.IsFinite(grid.Shift) && grid.Segments.All(length => length is >= 0 and < 100) + && (grid.Segments.Length == 0 || grid.Segments.Sum() > 0.0001))) return null; + return pattern.Grids; + } + + internal static List BreakLines(RvtDocument document, int viewId, double[] right, double[] up) + { + var result = new List(); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + foreach (var element in document.Elements) + { + if (element.OwnerViewId != viewId || hidden?.Contains(element.Id) == true + || element.FamilyName != "M_Break Line" + || element.Transform is not { Origin.Length: 3, BasisX.Length: 3, BasisY.Length: 3 } transform + || document.GetElement(transform.SymbolId)?.DetailBreak is not { } profile) continue; + var line = profile.Line.Select(p => ToView(p.X, p.Y)).ToList(); + var mask = new List<(double X, double Y)>(line) + { + ToView(profile.Line[^1].X, profile.MaskY), ToView(profile.Line[0].X, profile.MaskY) + }; + result.Add(new(line, mask)); + + (double X, double Y) ToView(double x, double y) + { + double[] world = new double[3]; + for (int k = 0; k < world.Length; k++) + world[k] = transform.Origin[k] + x * transform.BasisX[k] + y * transform.BasisY[k]; + return (Project(world, right), Project(world, up)); + } + } + return result; + } + + internal static IEnumerable BattInsulation( + double ax, double ay, double bx, double by, double width, bool mirrored) + { + double dx = bx - ax, dy = by - ay; + double length = Math.Sqrt(dx * dx + dy * dy); + double radius = width / 6; + double steps = length / radius; + if (!(steps is > 0 and <= 4096)) yield break; + dx /= length; + dy /= length; + for (int i = -1; i < steps; i++) + { + double side = (i % 2 == 0) == mirrored ? 1 : -1; + for (int k = 0; k < 8; k++) + { + double a = Math.PI * k / 8, b = Math.PI * (k + 1) / 8; + if (Stroke(i + 1 - Math.Cos(a), side * (2 + Math.Sin(a)), + i + 1 - Math.Cos(b), side * (2 + Math.Sin(b))) is { } arc) yield return arc; + } + for (int k = 0; k < 6; k++) + { + double a = k / 6.0, b = (k + 1) / 6.0; + if (Stroke(i + Smooth(a), side * (2 - 4 * a), + i + Smooth(b), side * (2 - 4 * b)) is { } bridge) yield return bridge; + } + } + + static double Smooth(double t) => t * t * (3 - 2 * t); + ElevationPrinter.CollectedEdge? Stroke(double x1, double y1, double x2, double y2) + { + if (x2 <= 0 || x1 >= steps) return null; + if (x1 < 0) + { + y1 += (y2 - y1) * (-x1 / (x2 - x1)); + x1 = 0; + } + if (x2 > steps) + { + y2 = y1 + (y2 - y1) * ((steps - x1) / (x2 - x1)); + x2 = steps; + } + return new(ax + radius * (x1 * dx - y1 * dy), ay + radius * (x1 * dy + y1 * dx), + ax + radius * (x2 * dx - y2 * dy), ay + radius * (x2 * dy + y2 * dx), + 0, 0, -1, -1, 0, 0, 0, 0); + } + } + + internal static void DrawCallouts(PdfPage page, RvtDocument document, Element sheet, Element parent, + ViewCropFrame parentCrop, double scale, double originX, double originY) + { + var (x0, y0, x1, y1) = SheetComposer.CropContentRect(parentCrop); + var annotationCrop = parent.ViewAnnotationCrop; + double boundaryPen = Pen(BuiltInCategory.OST_CalloutBoundary, 0.7); + double leaderPen = Pen(BuiltInCategory.OST_CalloutLeaderLine, 0.1); + double headPen = Pen(BuiltInCategory.OST_CalloutHeads, 0.1); + LinePatterns.TryGetDashes(document, (int)BuiltInCategory.OST_CalloutBoundary, out var points); + double[] pattern = points.Select(value => value * PointsToMillimetres).ToArray(); + string number = sheet.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? ""; + foreach (var viewport in document.Elements) + { + if (viewport.OwnerViewId != sheet.Id || viewport.ViewportViewId is not int viewId + || document.GetElement(viewId) is not { SectionCallout: { } callout, ViewCrop: { Active: true } crop } child + || callout.ParentId != parent.Id || !SameAxis(crop.Right, parentCrop.Right) || !SameAxis(crop.Up, parentCrop.Up)) + continue; + if (document.GetElement(child.TypeId)?.LookupParameter(BuiltInParameter.CALLOUT_TAG)?.Value is not int tagId + || document.GetElement(tagId) is not { } tag + || tag.LookupParameter(BuiltInParameter.CALLOUT_CORNER_SHEET_RADIUS)?.Value is not double cornerFeet + || cornerFeet is <= 0 or > 1 + || tag.LookupParameter(BuiltInParameter.CALLOUT_ATTR_HEAD_TAG)?.Value is not int headId + || document.GetElement(headId) is not { FamilyName: "M_Callout Head", BoundingBox: { Length: 6 } box }) + continue; + double headRadius = (box[3] - box[0]) * FeetToMillimetres / 2; + if (!(headRadius is > 0 and <= 100) || Math.Abs(box[3] - box[0] - box[4] + box[1]) > 1e-6) + continue; + var (left, bottom, right, top) = SheetComposer.CropContentRect(crop); + if (right <= left || top <= bottom || right < x0 || top < y0 || left > x1 || bottom > y1) continue; + left = ToX(left); right = ToX(right); bottom = ToY(bottom); top = ToY(top); + double r = Math.Min(cornerFeet * FeetToMillimetres, Math.Min(right - left, top - bottom) / 2); + double hx = ToX(Project(callout.Head, parentCrop.Right)), hy = ToY(Project(callout.Head, parentCrop.Up)); + double qx = Math.Min(Math.Max(hx, left + r), right - r); + double qy = Math.Min(Math.Max(hy, bottom + r), top - r); + double dx = hx - qx, dy = hy - qy; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > r)) continue; + dx /= length; + dy /= length; + double cx = hx + dx * headRadius, cy = hy + dy * headRadius; + if (annotationCrop is { } pad + && (Math.Min(left, cx - headRadius) < ToX(x0) - pad.Left * FeetToMillimetres + || Math.Max(right, cx + headRadius) > ToX(x1) + pad.Right * FeetToMillimetres + || Math.Min(bottom, cy - headRadius) < ToY(y0) - pad.Bottom * FeetToMillimetres + || Math.Max(top, cy + headRadius) > ToY(y1) + pad.Top * FeetToMillimetres)) continue; + + ElevationPrinter.DrawDatumDashes(page, left + r, bottom, right - r, bottom, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, left + r, top, right - r, top, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, left, bottom + r, left, top - r, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, right, bottom + r, right, top - r, pattern, boundaryPen, roundCaps: true); + Arc(right - r, top - r, 0); + Arc(left + r, top - r, 90); + Arc(left + r, bottom + r, 180); + Arc(right - r, bottom + r, 270); + page.DrawLine(qx + dx * r, qy + dy * r, hx, hy, leaderPen); + page.DrawPolyline(Circle(cx, cy, headRadius, 0, 360, 24), headPen, true, 1); + page.DrawLine(cx - headRadius, cy, cx + headRadius, cy, headPen); + string detail = viewport.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? ""; + if (page.Owner.Font != null || detail.All(c => c is >= ' ' and <= '~')) + page.DrawText(detail, cx, cy + 1, 12 * PointsToMillimetres, PdfTextAlignment.Center); + if (page.Owner.Font != null || number.All(c => c is >= ' ' and <= '~')) + page.DrawText(number, cx, cy - 4, 8 * PointsToMillimetres, PdfTextAlignment.Center); + + void Arc(double x, double y, int angle) => + page.DrawPolyline(Circle(x, y, r, angle, 90, 5), boundaryPen); + } + + double Pen(BuiltInCategory category, double fallback) => + PenWidths.TryGetPenNumber(document, (int)category, false, out int pen) + && PenWidths.TryAnnotationWidth(document, pen, out double width) ? width : fallback; + double ToX(double x) => originX + x / scale; + double ToY(double y) => originY + y / scale; + } + + private static (double X, double Y)[] Circle(double x, double y, double radius, double start, double sweep, int segments) + { + var result = new (double X, double Y)[segments + 1]; + for (int i = 0; i <= segments; i++) + { + double angle = (start + sweep * i / segments) * Math.PI / 180; + result[i] = (x + radius * Math.Cos(angle), y + radius * Math.Sin(angle)); + } + return result; + } + + private static bool SameAxis(double[] a, double[] b) => + Math.Abs(a[0] - b[0]) + Math.Abs(a[1] - b[1]) + Math.Abs(a[2] - b[2]) < 1e-6; + + private static double Project(double[] point, double[] axis) => + (point[0] * axis[0] + point[1] * axis[1] + point[2] * axis[2]) * FeetToMillimetres; +} diff --git a/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs b/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs new file mode 100644 index 00000000..5050b489 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs @@ -0,0 +1,313 @@ +using System.Numerics; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + internal sealed record AmbientPatch(PdfRasterImage Image, double X0, double Y0, double X1, double Y1, + PdfRasterImage? ThroughGlass = null, IReadOnlyList? Glass = null); + + internal sealed record AmbientGlass(List Polygon, List>? Holes, double FarDepth); + + internal sealed class AmbientOcclusion(double ambientFraction, (double X0, double Y0, double X1, double Y1) crop, + bool binaryVisibility = false) + { + private const float RayBias = 0.05f; + private const int RayCount = 24; + // shortcut: a local model-space falloff, replace it when the display kernel is available. + private const float AmbientReach = 1500; + private readonly List _occluders = []; + private readonly List<(List Polygon, List>? Holes, Vector3 Origin, Vector3 Normal, + double Gray, bool OrientDirectLight, bool IgnoreStairExitHits, bool IgnoreEdgeOnHits, + bool ExcludeSamplesBehindCut, bool DistanceFalloff, int[]? AttachedRoofIds, + (double Elevation, float Depth)? ExteriorWall, bool ProjectedSlabSide)> _receivers = []; + private readonly List _glass = []; + + private readonly record struct Occluder(Vector3 Origin, Vector3 Normal, Vector3 Min, Vector3 Max, + int Axis, List Outline, List>? Holes, bool FrontFaceOnly, int RoofId); + private sealed record Node(Vector3 Min, Vector3 Max, int Start, int Count, Node? Left, Node? Right); + + internal void AddOccluder(List ring, Vector3 normal, List>? holes = null, + bool frontFaceOnly = false, int roofId = 0) + { + if (ring.Count < 3 || !(normal.LengthSquared() > 0.5f)) return; + Vector3 min = ring[0], max = ring[0]; + foreach (Vector3 point in ring) + { + min = Vector3.Min(min, point); + max = Vector3.Max(max, point); + } + var abs = Vector3.Abs(normal); + int axis = abs.X > abs.Y && abs.X > abs.Z ? 0 : abs.Y > abs.Z ? 1 : 2; + List Flatten(List points) => points.Select(point => Flat(point, axis)).ToList(); + var margin = new Vector3(RayBias); + _occluders.Add(new(ring[0], normal, min - margin, max + margin, axis, Flatten(ring), + holes?.Select(Flatten).ToList(), frontFaceOnly, roofId)); + } + + internal void AddReceiver(List polygon, List>? holes, Vector3 origin, Vector3 normal, + double gray = 1, bool orientDirectLight = false, bool ignoreStairExitHits = false, + bool ignoreEdgeOnHits = false, + bool excludeSamplesBehindCut = false, bool distanceFalloff = false, int[]? attachedRoofIds = null, + (double Elevation, float Depth)? exteriorWall = null, bool projectedSlabSide = false) + { + if (normal.Z < -1e-5f) + _receivers.Add((polygon, holes, origin, Vector3.Normalize(normal), gray, orientDirectLight, + ignoreStairExitHits, ignoreEdgeOnHits, excludeSamplesBehindCut, distanceFalloff, attachedRoofIds, + exteriorWall, projectedSlabSide)); + } + + internal void AddGlazing(List polygon, List>? holes, double farDepth) => + _glass.Add(new(polygon, holes, farDepth)); + + internal IReadOnlyDictionary, AmbientPatch>? Calculate( + IReadOnlyList>? cutCaps = null, double cutDepth = 0) + { + if (_receivers.Count == 0 || _occluders.Count == 0) return null; + var occluders = _occluders.ToArray(); + var tree = Build(occluders, 0, occluders.Length); + var result = new Dictionary, AmbientPatch>(); + Span rays = stackalloc Vector3[RayCount]; + const int gridSize = 3; + Span<(double X, double Y, bool OnFace)> samples = stackalloc (double, double, bool)[gridSize * gridSize]; + Span sampled = stackalloc bool[samples.Length]; + Span behindCut = stackalloc bool[samples.Length]; + float visibleSpan = (float)Math.Min(crop.X1 - crop.X0, crop.Y1 - crop.Y0); + foreach (var (polygon, holes, planeOrigin, normal, gray, orientDirectLight, ignoreStairExitHits, ignoreEdgeOnHits, + excludeSamplesBehindCut, distanceFalloff, attachedRoofIds, exteriorWall, projectedSlabSide) in _receivers) + { + sampled.Clear(); + behindCut.Clear(); + double left = Math.Max(crop.X0, polygon.Min(p => p.X)); + double right = Math.Min(crop.X1, polygon.Max(p => p.X)); + double bottom = Math.Max(crop.Y0, polygon.Min(p => p.Y)); + double top = Math.Min(crop.Y1, polygon.Max(p => p.Y)); + if (left >= right || bottom >= top) continue; + + var tangent = Vector3.Normalize(Vector3.Cross(normal, + Math.Abs(normal.Z) > 0.9f ? Vector3.UnitX : Vector3.UnitZ)); + var bitangent = Vector3.Cross(normal, tangent); + for (int k = 0; k < rays.Length; k++) + { + float radius = MathF.Sqrt((k + 0.5f) / rays.Length); + float angle = k * MathF.PI * (3 - MathF.Sqrt(5)); + rays[k] = normal * MathF.Sqrt(1 - radius * radius) + + radius * (MathF.Cos(angle) * tangent + MathF.Sin(angle) * bitangent); + } + + bool hasSurfaceSample = false; + for (int j = 0; j < gridSize; j++) + for (int i = 0; i < gridSize; i++) + { + double x = left + (right - left) * (i + 0.5) / gridSize; + double y = bottom + (top - bottom) * (j + 0.5) / gridSize; + bool onFace = PointInPolygon(x, y, polygon) + && holes?.Any(hole => PointInPolygon(x, y, hole)) != true; + hasSurfaceSample |= onFace; + samples[(gridSize - 1 - j) * gridSize + i] = (x, y, onFace); + } + + var rgb = new byte[samples.Length * 3]; + byte unshaded = (byte)Math.Round(255 * gray); + double baseLinear = gray <= 0.04045 ? gray / 12.92 : Math.Pow((gray + 0.055) / 1.055, 2.4); + float Depth(double x, double y) => planeOrigin.Z - (normal.X * ((float)x - planeOrigin.X) + + normal.Y * ((float)y - planeOrigin.Y)) / normal.Z; + double directLightLoss = orientDirectLight ? (1 - ambientFraction) * (1 - Math.Clamp(-normal.Z, 0, 1)) : 0; + List? glass = null; + if (directLightLoss > 0 && _glass.Count > 0) + { + glass = []; + foreach (var pane in _glass) + { + if (pane.Polygon.Max(p => p.X) <= left || pane.Polygon.Min(p => p.X) >= right + || pane.Polygon.Max(p => p.Y) <= bottom || pane.Polygon.Min(p => p.Y) >= top) + continue; + + // The wall depth varies across an oblique face. Only the portion behind the pane + // uses the tone for a transmitted view of the wall. + double Gap(Point point) => Depth(point.X, point.Y) - pane.FarDepth - 0.01; + List Clip(List ring) => ClipHalfPlane(ring, p => Gap(p) > 0, Gap); + var mask = Clip(pane.Polygon); + if (mask.Count >= 3) + glass.Add(pane with { Polygon = mask, Holes = pane.Holes?.Select(Clip).Where(h => h.Count >= 3).ToList() }); + } + } + byte[]? throughGlass = glass is { Count: > 0 } ? new byte[rgb.Length] : null; + if (throughGlass != null) Array.Fill(throughGlass, unshaded); + byte unoccluded = directLightLoss > 0 ? ToTone(baseLinear * (1 - directLightLoss)) : unshaded; + Array.Fill(rgb, unoccluded); + bool hasShadow = unoccluded < unshaded; + for (int i = 0; i < samples.Length; i++) + { + var (x, y, onFace) = samples[i]; + if (!onFace) + { + if (hasSurfaceSample) continue; + // A thin frame may fall between every grid point. + var boundary = holes?.Find(hole => PointInPolygon(x, y, hole)) ?? polygon; + (x, y, _) = ClosestPolygonPoint(x, y, boundary); + } + float z = Depth(x, y); + if (excludeSamplesBehindCut && z > cutDepth + RayBias + && cutCaps?.Any(cap => PointInPolygon(x, y, cap)) == true) + { + behindCut[i] = true; + continue; + } + sampled[i] = true; + var receiver = new Vector3((float)x, (float)y, z); + double blocked = 0; + double sectionBlocked = 0; + // The saved crop and cut plane limit how far a buried wall samples its surroundings. + float reach = exteriorWall is { } wall && y < wall.Elevation + ? Math.Clamp(visibleSpan, AmbientReach, Math.Max(AmbientReach, z - wall.Depth)) + : AmbientReach; + float sectionDepth = projectedSlabSide ? z - (float)cutDepth : 0; + foreach (var ray in rays) + { + float rayReach = sectionDepth > reach && ray.Z < -1e-6f ? sectionDepth / -ray.Z : reach; + float distance = rayReach; + if (!FindHit(tree, occluders, receiver + normal * RayBias, ray, ignoreStairExitHits, ignoreEdgeOnHits, + attachedRoofIds, ref distance)) + continue; + if (distance < reach) + { + float relativeDistance = distance / reach; + blocked += binaryVisibility && !distanceFalloff && reach == AmbientReach + ? 1 : 1 - relativeDistance * relativeDistance; + } + if (rayReach > reach) + { + float relativeDistance = distance / rayReach; + sectionBlocked += 1 - relativeDistance * relativeDistance; + } + } + double ambientLoss = ambientFraction * blocked / RayCount; + // Approximate the reduced light through the section opening separately from contact shadows. + double sectionLight = 1 - (1 - ambientFraction) * sectionBlocked / RayCount; + byte tone = ToTone(baseLinear * (1 - ambientLoss - directLightLoss) * sectionLight); + int pixel = i * 3; + rgb[pixel] = rgb[pixel + 1] = rgb[pixel + 2] = tone; + if (throughGlass != null) + throughGlass[pixel] = throughGlass[pixel + 1] = throughGlass[pixel + 2] = + ToTone(baseLinear * (1 - ambientLoss)); + hasShadow |= tone < unshaded; + } + if (hasShadow) + { + // Extend valid tones across the cap in the texture so interpolation uses the visible slab. + for (int i = 0; i < behindCut.Length; i++) + { + if (!behindCut[i]) continue; + int nearest = -1; + double best = double.PositiveInfinity; + for (int j = 0; j < sampled.Length; j++) + { + if (!sampled[j]) continue; + double dx = samples[i].X - samples[j].X; + double dy = samples[i].Y - samples[j].Y; + double distance = dx * dx + dy * dy; + if (distance >= best) continue; + nearest = j; + best = distance; + } + if (nearest < 0) continue; + Array.Copy(rgb, nearest * 3, rgb, i * 3, 3); + if (throughGlass != null) + Array.Copy(throughGlass, nearest * 3, throughGlass, i * 3, 3); + } + result.Add(polygon, new(Raster(rgb), left, bottom, right, top, + throughGlass != null ? Raster(throughGlass) : null, glass)); + } + + static PdfRasterImage Raster(byte[] samples) => new(gridSize, gridSize, samples) { Interpolate = true }; + } + return result.Count > 0 ? result : null; + } + + internal static byte ToTone(double linear) + { + double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.Pow(linear, 1 / 2.4) - 0.055; + return (byte)Math.Round(255 * srgb); + } + + private static Point Flat(Vector3 p, int axis) => axis switch + { + 0 => (p.Y, p.Z), 1 => (p.X, p.Z), _ => (p.X, p.Y) + }; + + private static Node Build(Occluder[] faces, int start, int count) + { + var min = faces[start].Min; + var max = faces[start].Max; + for (int i = start + 1; i < start + count; i++) + { + min = Vector3.Min(min, faces[i].Min); + max = Vector3.Max(max, faces[i].Max); + } + if (count <= 8) return new(min, max, start, count, null, null); + var spread = max - min; + int axis = spread.X > spread.Y && spread.X > spread.Z ? 0 : spread.Y > spread.Z ? 1 : 2; + Array.Sort(faces, start, count, Comparer.Create((a, b) => + (a.Min[axis] + a.Max[axis]).CompareTo(b.Min[axis] + b.Max[axis]))); + int half = count / 2; + return new(min, max, start, 0, Build(faces, start, half), Build(faces, start + half, count - half)); + } + + private static bool FindHit(Node node, Occluder[] faces, Vector3 origin, Vector3 direction, bool ignoreStairExitHits, + bool ignoreEdgeOnHits, + int[]? attachedRoofIds, ref float limit) + { + if (!HitsBounds(node.Min, node.Max, origin, direction, limit)) return false; + if (node.Left != null) + { + bool left = FindHit(node.Left, faces, origin, direction, ignoreStairExitHits, ignoreEdgeOnHits, attachedRoofIds, ref limit); + bool right = FindHit(node.Right!, faces, origin, direction, ignoreStairExitHits, ignoreEdgeOnHits, attachedRoofIds, ref limit); + return left || right; + } + bool found = false; + for (int i = node.Start; i < node.Start + node.Count; i++) + { + ref readonly var face = ref faces[i]; + if (face.RoofId > 0 && attachedRoofIds != null && Array.IndexOf(attachedRoofIds, face.RoofId) >= 0) + continue; + if (ignoreEdgeOnHits && Math.Abs(face.Normal.Z) < 1e-6f) continue; + float dot = Vector3.Dot(face.Normal, direction); + if (Math.Abs(dot) < 1e-6f || ignoreStairExitHits && face.FrontFaceOnly && dot > 0) continue; + float distance = Vector3.Dot(face.Normal, face.Origin - origin) / dot; + if (distance <= RayBias || distance >= limit) continue; + var point = origin + distance * direction; + if (point.X < face.Min.X || point.X > face.Max.X || point.Y < face.Min.Y || point.Y > face.Max.Y + || point.Z < face.Min.Z || point.Z > face.Max.Z) continue; + var (x, y) = Flat(point, face.Axis); + if (PointInPolygon(x, y, face.Outline) && face.Holes?.Any(hole => PointInPolygon(x, y, hole)) != true) + { + limit = distance; + found = true; + } + } + return found; + } + + private static bool HitsBounds(Vector3 min, Vector3 max, Vector3 origin, Vector3 direction, float limit) + { + float near = 0, far = limit; + for (int i = 0; i < 3; i++) + { + if (Math.Abs(direction[i]) < 1e-8f) + { + if (origin[i] < min[i] || origin[i] > max[i]) return false; + continue; + } + float a = (min[i] - origin[i]) / direction[i]; + float b = (max[i] - origin[i]) / direction[i]; + near = Math.Max(near, Math.Min(a, b)); + far = Math.Min(far, Math.Max(a, b)); + if (near > far) return false; + } + return true; + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Billboards.cs b/src/RvtIO/Print/ElevationPrinter.Billboards.cs new file mode 100644 index 00000000..1c0538f4 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Billboards.cs @@ -0,0 +1,93 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private readonly record struct BillboardPlane(double X, double Y, double Offset) + { + internal const double Tolerance = 0.1 / FeetToMillimetres; + + internal bool Contains(double[] point) => Math.Abs(X * point[0] + Y * point[1] - Offset) <= Tolerance; + } + + /// Recognize two perpendicular upright planes, with optional triangles at their base. + private static List? CrossedBillboardPlanes(List faces) + { + const double angleTolerance = 1e-5; + if (faces.Any(face => face.OuterVertices is not { Count: 3 } || !face.PolygonMesh + || face.RenderStyleId != null || face.NestedRenderStyleId != null)) return null; + double baseZ = faces.Min(face => face.OuterVertices!.Min(point => point[2])); + var planes = new List(2); + foreach (var face in faces) + { + var vertices = face.OuterVertices!; + if (vertices.All(point => point[2] - baseZ <= BillboardPlane.Tolerance)) continue; + var normal = face.Normal; + double length = Math.Sqrt(normal[0] * normal[0] + normal[1] * normal[1]); + if (length < angleTolerance || Math.Abs(normal[2]) > length * angleTolerance) return null; + if (planes.Any(plane => vertices.All(plane.Contains))) continue; + double x = normal[0] / length, y = normal[1] / length; + if (planes.Count == 2 || planes.Count == 1 + && Math.Abs(planes[0].X * x + planes[0].Y * y) > angleTolerance) return null; + var plane = new BillboardPlane(x, y, x * vertices[0][0] + y * vertices[0][1]); + if (!vertices.All(plane.Contains)) return null; + planes.Add(plane); + } + return planes.Count == 2 ? planes : null; + } + + private static (List> Rings, List Edges)? ProjectSectionBillboard( + List faces, List planes, double[] horizontal, double[] vertical, double[] view, + double planeDepth) + { + if (Math.Abs(vertical[2] - 1) > 1e-9 || Math.Abs(view[2]) > 1e-9) return null; + var depths = faces.SelectMany(face => face.OuterVertices!).Select(point => Project(point, view)).ToArray(); + if (depths.Min() >= planeDepth || depths.Max() <= planeDepth) return null; + + List>[] panels = [[], []]; + foreach (var face in faces) + { + var vertices = face.OuterVertices!; + var ring = vertices.Select(point => (Project(point, horizontal), Project(point, vertical))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) < 1e-6) continue; + if (area < 0) ring.Reverse(); + int panel = planes.FindIndex(plane => vertices.All(plane.Contains)); + if (panel >= 0) panels[panel].Add(ring); + } + var rings = panels.SelectMany(panel => panel).ToList(); + if (rings.Count == 0) return null; + + const int category = (int)BuiltInCategory.OST_Entourage; + if (panels[0].Count == 0 || panels[1].Count == 0 + || planes.Any(plane => Math.Abs(ViewComponent(plane)) < 1e-9)) + return (rings, OutlineJoinedRings(rings, category, coverOppositeEdges: true).ToList()); + + var (offsetA, slopeA) = ProjectedDepth(planes[0]); + var (offsetB, slopeB) = ProjectedDepth(planes[1]); + // The upright panels exchange depth order at one horizontal coordinate in the section. + var visible = VisiblePanel(0, 1, offsetA - offsetB, slopeA - slopeB).ToList(); + visible.AddRange(VisiblePanel(1, 0, offsetB - offsetA, slopeB - slopeA)); + return (rings, visible); + + (double Offset, double Slope) ProjectedDepth(BillboardPlane plane) + { + double toward = ViewComponent(plane); + double across = plane.X * horizontal[0] + plane.Y * horizontal[1]; + return (plane.Offset * FeetToMillimetres / toward, -across / toward); + } + + double ViewComponent(BillboardPlane plane) => plane.X * view[0] + plane.Y * view[1]; + + IEnumerable VisiblePanel(int current, int other, double offset, double slope) + { + var cover = panels[other].Select(ring => ClipHalfPlane(ring, + point => offset + slope * point.X >= 0, point => offset + slope * point.X)) + .Where(ring => ring.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(ring)) > 1e-6); + return VisibleTerrainEdges(OutlineJoinedRings(panels[current], category, coverOppositeEdges: true), + cover, [], coverBoundary: false, coverOppositeEdges: true); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Glazing.cs b/src/RvtIO/Print/ElevationPrinter.Glazing.cs new file mode 100644 index 00000000..4c0844e6 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Glazing.cs @@ -0,0 +1,99 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + internal sealed class AmbientGlazing(double light, bool detailCallout = false) + { + private const double PlaneTolerance = 0.01; + private readonly Dictionary, Surface> _surfaces = []; + private readonly Dictionary _materials = []; + + private readonly record struct Surface(double Near, double Far, double X0, double Y0, double X1, double Y1, + double? Gray, double Transmission, bool Pane, bool CoversBacking); + + internal bool HasPanes { get; private set; } + + internal void Add(RvtDocument document, List points, double near, double far, int? materialId, + bool glazing, bool coversBacking = false) + { + double? gray = null; + double transmission = 0; + if (materialId is > 0 and int id) + { + if (!_materials.TryGetValue(id, out var appearance)) + { + var material = document.GetElement(id); + if (material is { HasShadingAppearance: true } + && material.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int rgb + && rgb is >= 0 and <= 0xffffff) + appearance.Gray = ((rgb & 255) * 0.2126 + ((rgb >> 8) & 255) * 0.7152 + + ((rgb >> 16) & 255) * 0.0722) / 255; + appearance.Transmission = material?.SerializedMaterialTransparency ?? 0; + _materials.Add(id, appearance); + } + (gray, transmission) = appearance; + } + bool pane = glazing && gray != null && transmission is > 0 and <= 1; + HasPanes |= pane; + _surfaces.Add(points, new(near, far, points.Min(p => p.X), points.Min(p => p.Y), + points.Max(p => p.X), points.Max(p => p.Y), gray, transmission, pane, coversBacking)); + } + + internal bool IsPane(List points) => _surfaces.GetValueOrDefault(points).Pane; + + internal double? AmbientBackgroundGray(List points) + => !detailCallout && _surfaces.TryGetValue(points, out var pane) && pane.Pane + ? BackgroundGray(pane) : null; + + private double BackgroundGray(Surface pane) + { + double tint = (1 - pane.Transmission) * pane.Gray!.Value + pane.Transmission * light; + // Approximate the opaque curtain pane tone using the saved ambient light intensity. + return pane.CoversBacking ? tint * light : tint; + } + + internal void Draw(PdfPage page, ElevationContent content, List points, + IReadOnlyList> paneRings, Func toX, Func toY, + Func, IReadOnlyList>, List>> faceRings) + { + var pane = _surfaces[points]; + double reflection = (1 - pane.Transmission) * pane.Gray!.Value; + if (detailCallout) + { + // shortcut: blend over the opaque page base, until transparent backing is decoded for callouts. + page.FillPolygonUnion(paneRings, reflection + pane.Transmission); + return; + } + page.FillPolygonUnion(paneRings, BackgroundGray(pane)); + page.BeginPolygonClip(paneRings); + if (content.AmbientTones?.GetValueOrDefault(points) is { } background) + { + double x = toX(background.X0), y = toY(background.Y0); + page.DrawImage(background.Image, x, y, toX(background.X1) - x, toY(background.Y1) - y); + } + if (!pane.CoversBacking) + { + foreach (var (back, _, _) in content.Faces) + { + // Only planes wholly behind the pane are repainted. The existing painter's ordering + // and inner rings keep nearer solid infill and empty openings distinct. + if (!_surfaces.TryGetValue(back, out var surface) || surface.Near < pane.Far + PlaneTolerance + || surface.Transmission > 0 || surface.X0 >= pane.X1 || surface.X1 <= pane.X0 + || surface.Y0 >= pane.Y1 || surface.Y1 <= pane.Y0) + continue; + double fill = surface.Gray is double gray ? reflection + pane.Transmission * light * gray : 1; + var projected = back.Select(point => (toX(point.X), toY(point.Y))).ToList(); + if (content.FaceOpenings?.GetValueOrDefault(back) is { } holes) + page.FillPolygonUnion(faceRings(projected, holes), fill); + else + page.DrawPolyline(projected, 0, true, fill); + } + } + page.EndClip(); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs b/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs new file mode 100644 index 00000000..ea2353bc --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs @@ -0,0 +1,85 @@ +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private static List? ProjectSectionMeshSilhouette(GeometryData geometry, + double[] horizontal, double[] vertical, double[] direction, double planeDepth, int elementId, int category, + bool multipleRevolvedNodes, bool cylindricalFurniture) + { + if (geometry is not { BrepSolids.Count: > 0, UnresolvedSymbol: false, PlacedSymbolBox: false, + PlacedSymbolClipped: false, UntriangulatedFaces: 0, MeshNodes: { Count: > 0 } nodes } + || !cylindricalFurniture && geometry.BrepSolids.Count < 2 + || geometry.BrepSolids.Any(solid => !solid.IsClosed) + || nodes.Any(node => node.Ghost || node.Faces.Any(face => + face.SurfaceKind is not (SurfaceKind.Plane or SurfaceKind.Cylinder or SurfaceKind.Revolved))) + || !cylindricalFurniture && (multipleRevolvedNodes + ? nodes.Count < 2 || nodes.Any(node => !node.Faces.Any(face => face.SurfaceKind == SurfaceKind.Revolved)) + : nodes.Count != 1)) + return null; + + var curvedKind = cylindricalFurniture ? SurfaceKind.Cylinder : SurfaceKind.Revolved; + var curvedMarkers = nodes.SelectMany(node => node.Faces.Where(face => face.SurfaceKind == curvedKind) + .Select(face => (node.Node, (uint)face.Marker))).ToHashSet(); + if (!geometry.Faces.Any(face => !face.PlaneSurface + && curvedMarkers.Contains((face.GeometryNode, face.MeshMarker)))) + return null; + + var assigned = geometry.BrepSolids.SelectMany(solid => solid.FaceIndices).ToHashSet(); + if ((!multipleRevolvedNodes && assigned.Count != geometry.Faces.Count) + || assigned.Any(index => (uint)index >= geometry.Faces.Count)) + return null; + + var rings = new List>(); + var depths = new List(); + for (int i = 0; i < geometry.Faces.Count; i++) + { + var face = geometry.Faces[i]; + bool hasOpenings = face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 }; + if (face.CurvedSurface || !cylindricalFurniture && hasOpenings + || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(point => point.Length != 3 || !point.All(double.IsFinite))) + return null; + + var vertexDepths = vertices.Select(point => Project(point, direction)).ToArray(); + if (vertexDepths.Any(depth => depth <= planeDepth + 1e-6)) return null; + var ring = vertices.Select(point => (Project(point, horizontal), Project(point, vertical))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) < 1e-6) continue; + // Unassigned display faces may be edge-on in this view. A visible open face uses the fallback. + if (hasOpenings || !assigned.Contains(i)) return null; + if (area < 0) + { + ring.Reverse(); + Array.Reverse(vertexDepths); + } + rings.Add(ring); + depths.Add(vertexDepths); + } + + var strokes = new List(); + foreach (var edge in OutlineJoinedRings(rings, category, coverOppositeEdges: true, retainSource: true)) + { + var (ringIndex, first) = edge.SourceRingEdge!.Value; + var ring = rings[ringIndex]; + int second = (first + 1) % ring.Count; + var a = ring[first]; + var b = ring[second]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double lengthSquared = dx * dx + dy * dy; + double DepthAt(double x, double y) => depths[ringIndex][first] + + (depths[ringIndex][second] - depths[ringIndex][first]) + * ((x - a.X) * dx + (y - a.Y) * dy) / lengthSquared; + double start = DepthAt(edge.X1, edge.Y1), end = DepthAt(edge.X2, edge.Y2); + double mid = (start + end) / 2; + strokes.Add(edge with + { + Depth = mid, MidDepth = mid, NearDepth = Math.Min(start, end), + SourceRingEdge = null, SilhouetteOwnerId = elementId, + }); + } + return strokes.Count > 0 ? strokes : null; + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs b/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs new file mode 100644 index 00000000..a9a96119 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs @@ -0,0 +1,231 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private static IEnumerable<(GeoFace Face, bool Tube)> SectionFaces(RvtDocument document, Element element, + GeometryData geometry, bool renderTubes, double[] horizontal, double[] vertical, double[] view, double[] origin, + bool renderRoundShafts, double maxElevationTubeDiameter, List elevationTubeEdges) + { + var replaced = new HashSet(); + if (renderRoundShafts) + foreach (var (shaft, facets) in ProjectRoundShafts(document, geometry, horizontal, vertical, view, origin, + element.CategoryId == (int)BuiltInCategory.OST_StructuralColumns)) + { + replaced.UnionWith(facets); + yield return (shaft, true); + } + if ((renderTubes || maxElevationTubeDiameter > 0) && element.SerializedBaseRailingSymbolId is int id + && document.GetElement(id) is { NativeRecordClass: 492, Geometry: { } source } + && geometry.Instances?.Where(instance => instance.SymbolId == id).Take(2).ToArray() + is [{ Transform: { Length: 12 } transform }] + && ElementBuilder.IsRigidPlacement(transform)) + { + // Face handles are local to a GRep. Check the placed vertices as well as the source handle. + var placed = geometry.Faces.Where(face => face.MeshMarker != 0 && face.OuterVertices is { Count: >= 3 }) + .ToLookup(face => (face.MeshMarker, Key(face.OuterVertices![0]))); + var cylinders = source.Faces.Where(face => face.SourceFace != 0 && face.CurvedSurface + && face.AnalyticCylinderOrigin is { Length: 3 } && face.AnalyticCylinderAxis is { Length: 3 } + && face.AnalyticCylinderRadius is > 0 and < double.PositiveInfinity && face.OuterVertices is { Count: >= 3 }) + .GroupBy(face => (face.GeometryNode, Centre: Key(face.AnalyticCylinderOrigin!), + Axis: Key(face.AnalyticCylinderAxis!), face.AnalyticCylinderRadius)); + foreach (var cylinder in cylinders) + { + // shortcut: two paired analytic sides of a straight rail segment. + if (cylinder.Select(face => face.SourceFace).Distinct().Count() != 2 + || !renderTubes && 2 * cylinder.Key.AnalyticCylinderRadius > maxElevationTubeDiameter) continue; + var patches = new List(); + foreach (var face in cylinder) + { + var expected = face.OuterVertices!.Select(point => ElementBuilder.TransformGeometryPoint(point, transform)).ToArray(); + var match = placed[(face.SourceFace, Key(expected[0]))].FirstOrDefault(candidate => + candidate.OuterVertices!.Count == expected.Length + && candidate.OuterVertices.Zip(expected).All(pair => Key(pair.First) == Key(pair.Second))); + if (match == null) break; + patches.Add(match); + } + if (patches.Count != cylinder.Count()) continue; + + if (!renderTubes) + { + var (x, y, z) = cylinder.Key.Axis; + double[] axis = + [ + x * transform[0] + y * transform[1] + z * transform[2], + x * transform[3] + y * transform[4] + z * transform[5], + x * transform[6] + y * transform[7] + z * transform[8], + ]; + if (Math.Abs(Project(axis, horizontal, 1)) <= 1e-9) continue; + var centre = cylinder.Key.Centre; + var placedCentre = ElementBuilder.TransformGeometryPoint([centre.X, centre.Y, centre.Z], transform); + var vertices = patches.SelectMany(patch => patch.OuterVertices!); + double axisLengthSquared = Project(axis, axis, 1); + double centreAlong = Project(placedCentre, axis, 1); + double from = (vertices.Min(point => Project(point, axis, 1)) - centreAlong) / axisLengthSquared; + double to = (vertices.Max(point => Project(point, axis, 1)) - centreAlong) / axisLengthSquared; + double startDepth = Project(placedCentre, view); + double forward = Project(axis, view); + double near = Project(origin, view, 1); + if (forward > 1e-9) from = Math.Max(from, (near - startDepth) / forward); + else if (forward < -1e-9) to = Math.Min(to, (near - startDepth) / forward); + else if (startDepth < near) continue; + if (!(to > from)) continue; + // A tube narrower than its print stroke inks once along the placed analytic axis. + double At(double t, double[] direction) => Project(placedCentre, direction) + t * Project(axis, direction); + double mid = At((from + to) / 2, view); + elevationTubeEdges.Add(new(At(from, horizontal), At(from, vertical), At(to, horizontal), At(to, vertical), + mid, mid, -1, -1, 0, 0, 0, 0, false, element.CategoryId ?? 0, + Math.Min(At(from, view), At(to, view)))); + continue; + } + + var points = patches.SelectMany(patch => + ClipBehind(patch.OuterVertices!.Select(point => + point.Select(value => value * FeetToMillimetres).ToArray()).ToList(), origin, view)); + var hull = ProjectedRailHull(points, horizontal, vertical, view); + if (hull.Count < 3) continue; + replaced.UnionWith(patches); + yield return (new GeoFace + { + OuterVertices = hull.Select(point => point.Select(value => value / FeetToMillimetres).ToArray()).ToList(), + Normal = view, + }, true); + } + } + foreach (var face in geometry.Faces) + if (!replaced.Contains(face)) yield return (face, false); + + static (double X, double Y, double Z) Key(double[] point) => (point[0], point[1], point[2]); + } + + private static IEnumerable<(GeoFace Shaft, GeoFace[] Facets)> ProjectRoundShafts(RvtDocument document, + GeometryData geometry, double[] horizontal, double[] vertical, double[] view, double[] origin, bool column) + { + if (Math.Abs(vertical[2] - 1) > 1e-9 || origin.Length != 3 + || geometry.Instances is not [{ Transform: { Length: 12 } transform } instance] + || !ElementBuilder.IsRigidPlacement(transform) || Math.Abs(Math.Abs(transform[8]) - 1) > 1e-9 + || document.GetElement(instance.SymbolId)?.Geometry is not { BrepSolids: { } solids } symbol + || geometry.Faces.Count != symbol.Faces.Count) yield break; + + foreach (var indices in ShaftFaceIndices()) + { + var native = indices.Select(index => symbol.Faces[index]).ToArray(); + var facets = indices.Select(index => geometry.Faces[index]).ToArray(); + var sides = native.Where(face => face.AnalyticCylinderRadius > 0).ToArray(); + if (sides.Length < 2 || column && (native.Length != sides.Length + 2 + || native.Except(sides).Any(face => !face.PlaneSurface || Math.Abs(face.Normal[2]) < 1 - 1e-9)) + || sides[0] is not { AnalyticCylinderOrigin: { Length: 3 } axisOrigin, + AnalyticCylinderRadius: > 0 and < double.PositiveInfinity and double radius } + || sides.Any(face => face.AnalyticCylinderAxis is not { Length: 3 } axis || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 + || face.AnalyticCylinderRadius != radius || face.AnalyticCylinderOrigin?.SequenceEqual(axisOrigin) != true) + || (facets[0].RenderStyleId ?? facets[0].NestedRenderStyleId) is not (> 0 and int material) + || facets.Any(face => (face.RenderStyleId ?? face.NestedRenderStyleId) != material) + || !native.Zip(facets).All(pair => pair.First.OuterVertices is { Count: >= 3 } source + && pair.Second.OuterVertices is { } placed && source.Count == placed.Count + && source.Zip(placed).All(points => ElementBuilder.TransformGeometryPoint(points.First, transform).Zip(points.Second) + .All(coordinate => Math.Abs(coordinate.First - coordinate.Second) < 1e-6)))) continue; + + var centre = ElementBuilder.TransformGeometryPoint(axisOrigin, transform); + if ((Project(centre, view, 1) - radius) * FeetToMillimetres <= Project(origin, view, 1)) continue; + double bottom = facets.Min(face => face.OuterVertices!.Min(point => point[2])); + double top = facets.Max(face => face.OuterVertices!.Max(point => point[2])); + if (!(top > bottom)) continue; + if (!column && (facets.Any(facet => + Math.Abs(facet.OuterVertices!.Min(p => p[2]) - bottom) > 1e-6 + || Math.Abs(facet.OuterVertices!.Max(p => p[2]) - top) > 1e-6) + || !HasTangent(-1, bottom) || !HasTangent(1, bottom) + || !HasTangent(-1, top) || !HasTangent(1, top))) continue; + // shortcut: the silhouette uses tangent depth, replace it when cylindrical depth tests are supported. + double[] Edge(double offset, double height) => + [centre[0] + horizontal[0] * offset, centre[1] + horizontal[1] * offset, height]; + yield return (new GeoFace + { + OuterVertices = [Edge(-radius, bottom), Edge(radius, bottom), Edge(radius, top), Edge(-radius, top)], + Normal = [-view[0], -view[1], -view[2]], PlaneSurface = true, RenderStyleId = material, + }, facets); + + bool HasTangent(int side, double height) + { + // A trimmed cylinder can omit a tangent. Check that its actual rims span each tangent + // at both ends before replacing the curved sides of a compound solid. + double centreX = Project(centre, horizontal, 1), centreDepth = Project(centre, view, 1); + foreach (var facet in facets) + { + var vertices = facet.OuterVertices!; + for (int i = 0; i < vertices.Count; i++) + { + var a = vertices[i]; + var b = vertices[(i + 1) % vertices.Count]; + if (Math.Abs(a[2] - height) > 1e-6 || Math.Abs(b[2] - height) > 1e-6 + || side * (Project(a, horizontal, 1) - centreX) <= 0 + || side * (Project(b, horizontal, 1) - centreX) <= 0) continue; + double da = Project(a, view, 1) - centreDepth; + double db = Project(b, view, 1) - centreDepth; + if (Math.Min(da, db) <= 1e-6 && Math.Max(da, db) >= -1e-6) return true; + } + } + return false; + } + } + + IEnumerable> ShaftFaceIndices() + { + foreach (var solid in solids.Where(solid => solid.IsClosed)) + { + if (solid.FaceIndices.Any(index => (uint)index >= symbol.Faces.Count)) continue; + if (column) + { + yield return solid.FaceIndices; + continue; + } + var cylinders = solid.FaceIndices.Where(index => symbol.Faces[index] is + { CurvedSurface: true, SourceFace: not 0, AnalyticCylinderRadius: > 0, + AnalyticCylinderOrigin: { Length: 3 }, InnerVertices: not { Count: > 0 }, InnerLoops: not { Count: > 0 } }) + .GroupBy(index => + { + var face = symbol.Faces[index]; + var axis = face.AnalyticCylinderOrigin!; + return (face.GeometryNode, axis[0], axis[1], axis[2], face.AnalyticCylinderRadius); + }); + foreach (var cylinder in cylinders) + if (cylinder.Select(index => symbol.Faces[index].SourceFace).Distinct().Count() == 2) + yield return cylinder.ToArray(); + } + } + } + + private static List ProjectedRailHull(IEnumerable vertices, double[] horizontal, + double[] vertical, double[] view) + { + var points = vertices.Select(point => (X: Dot(point, horizontal), Y: Dot(point, vertical), Point: point)) + .OrderBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => Dot(point.Point, view)) + .DistinctBy(point => (point.X, point.Y)).ToArray(); + if (points.Length < 3) return []; + var hull = new List<(double X, double Y, double[] Point)>(); + AddHalf(points, 0); + hull.RemoveAt(hull.Count - 1); + AddHalf(Enumerable.Reverse(points), hull.Count); + hull.RemoveAt(hull.Count - 1); + return hull.Select(point => point.Point).ToList(); + + void AddHalf(IEnumerable<(double X, double Y, double[] Point)> sorted, int start) + { + foreach (var point in sorted) + { + while (hull.Count > start + 1) + { + var a = hull[^2]; + var b = hull[^1]; + if ((b.X - a.X) * (point.Y - a.Y) > (b.Y - a.Y) * (point.X - a.X)) break; + hull.RemoveAt(hull.Count - 1); + } + hull.Add(point); + } + } + + static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.ScreenShadows.cs b/src/RvtIO/Print/ElevationPrinter.ScreenShadows.cs new file mode 100644 index 00000000..1dce5585 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.ScreenShadows.cs @@ -0,0 +1,165 @@ +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + internal sealed class PaneScreenShadows( + (double X0, double Y0, double X1, double Y1) crop, int scale, double ambientFraction) + { + // Screen-space approximation calibrated on a native wall/pane pair at 1:20, + // with depth offsets and scales 1:30 and 1:40 checked separately. + private const double PaperRadius = 125; + private const double DepthPerScale = 600; + private const double DisplayGain = 247; + private const int SampleCount = 512; + private const int MaxGridSide = 1024; + private const float DepthTolerance = 0.1f; + + internal IReadOnlyDictionary, AmbientPatch>? Calculate( + List<(List Points, double Depth, bool Outline)> faces, + IReadOnlyList owners, + IReadOnlyDictionary, List>> openings, + HashSet paneOwners, + Dictionary, double> receivers, + IReadOnlyDictionary, AmbientPatch>? localTones) + { + if (paneOwners.Count == 0 || receivers.Count == 0 || scale <= 0 || ambientFraction <= 0) + return null; + double spanX = crop.X1 - crop.X0, spanY = crop.Y1 - crop.Y0; + if (!(spanX > 0 && spanY > 0) || !double.IsFinite(spanX) || !double.IsFinite(spanY)) + return null; + double step = Math.Max(scale * 25.4 / 72, Math.Max(spanX, spanY) / MaxGridSide); + // Keep the last pixel centres inside the same saved crop as the PDF. + int width = Math.Clamp((int)Math.Floor(spanX / step + 0.5), 1, MaxGridSide); + int height = Math.Clamp((int)Math.Floor(spanY / step + 0.5), 1, MaxGridSide); + double X(int i) => crop.X0 + (i + 0.5) * step; + double Y(int j) => crop.Y0 + (j + 0.5) * step; + int FirstX(double value) => Math.Clamp((int)Math.Ceiling((value - crop.X0) / step - 0.5), 0, width); + int FirstY(double value) => Math.Clamp((int)Math.Ceiling((value - crop.Y0) / step - 0.5), 0, height); + + var withPanes = new float[width * height]; + var withoutPanes = new float[withPanes.Length]; + Array.Fill(withPanes, float.PositiveInfinity); + Array.Fill(withoutPanes, float.PositiveInfinity); + var crossings = new List(); + foreach (int index in Enumerable.Range(0, faces.Count).OrderByDescending(i => faces[i].Depth)) + { + var (ring, depth, _) = faces[index]; + var holes = openings.GetValueOrDefault(ring); + bool pane = paneOwners.Contains(owners[index]); + int bottom = FirstY(ring.Min(p => p.Y)), top = FirstY(ring.Max(p => p.Y)); + for (int j = bottom; j < top; j++) + { + double y = Y(j); + crossings.Clear(); + AddCrossings(ring, y, crossings); + if (holes != null) + foreach (var hole in holes) AddCrossings(hole, y, crossings); + crossings.Sort(); + for (int k = 0; k + 1 < crossings.Count; k += 2) + { + int left = FirstX(crossings[k]), right = FirstX(crossings[k + 1]); + if (left >= right) continue; + withPanes.AsSpan(j * width + left, right - left).Fill((float)depth); + if (!pane) withoutPanes.AsSpan(j * width + left, right - left).Fill((float)depth); + } + } + } + + double pixelRadius = PaperRadius * scale / step; + float depthRadius = (float)(DepthPerScale * scale); + var samples = new (int X, int Y, float Height)[SampleCount]; + float totalHeight = 0; + double goldenAngle = Math.PI * (3 - Math.Sqrt(5)); + for (int i = 0; i < samples.Length; i++) + { + double part = (i + 0.5) / samples.Length; + double radius = pixelRadius * Math.Sqrt(part), angle = (i + 0.5) * goldenAngle; + float sampleHeight = (float)Math.Sqrt(1 - part); + samples[i] = ((int)Math.Round(radius * Math.Cos(angle)), + (int)Math.Round(radius * Math.Sin(angle)), sampleHeight); + totalHeight += sampleHeight; + } + + var result = new Dictionary, AmbientPatch>(); + foreach (var (wall, depth) in receivers) + { + int left = FirstX(wall.Min(p => p.X)), right = FirstX(wall.Max(p => p.X)); + int bottom = FirstY(wall.Min(p => p.Y)), top = FirstY(wall.Max(p => p.Y)); + int w = right - left, h = top - bottom; + if (w <= 0 || h <= 0) continue; + var pixels = new byte[w * h * 3]; + Array.Fill(pixels, (byte)255); + bool changed = false; + var local = localTones?.GetValueOrDefault(wall); + float wallDepth = (float)depth; + for (int j = bottom; j < top; j++) + for (int i = left; i < right; i++) + { + int pixel = j * width + i; + if (Math.Abs(withPanes[pixel] - wallDepth) > DepthTolerance + || Math.Abs(withoutPanes[pixel] - wallDepth) > DepthTolerance) + continue; + float added = 0; + foreach (var (dx, dy, heightAtSample) in samples) + { + int x = i + dx, y = j + dy; + if ((uint)x >= (uint)width || (uint)y >= (uint)height) continue; + int tap = y * width + x; + if (withPanes[tap] == withoutPanes[tap]) continue; + added += Occupancy((wallDepth - withPanes[tap]) / depthRadius, heightAtSample) + - Occupancy((wallDepth - withoutPanes[tap]) / depthRadius, heightAtSample); + } + if (added <= 0) continue; + double original = LocalGray(local, X(i), Y(j)); + double originalLinear = ToLinear(original); + double available = Math.Max(0, ambientFraction - (1 - originalLinear)); + double screenLoss = 1 - ToLinear(1 - Math.Min(DisplayGain / 255 * added / totalHeight, 1)); + byte gray = AmbientOcclusion.ToTone(originalLinear - screenLoss * available / ambientFraction); + if (gray >= Math.Round(original * 255)) continue; + int destination = ((top - 1 - j) * w + i - left) * 3; + pixels[destination] = pixels[destination + 1] = pixels[destination + 2] = gray; + changed = true; + } + if (changed) + result.Add(wall, new(new PdfRasterImage(w, h, pixels) { TransparentWhite = true }, + crop.X0 + left * step, crop.Y0 + bottom * step, + crop.X0 + right * step, crop.Y0 + top * step)); + } + return result.Count > 0 ? result : null; + } + + private static void AddCrossings(List ring, double y, List crossings) + { + for (int i = 0, j = ring.Count - 1; i < ring.Count; j = i++) + { + var a = ring[j]; + var b = ring[i]; + if ((a.Y > y) != (b.Y > y)) + crossings.Add(a.X + (y - a.Y) * (b.X - a.X) / (b.Y - a.Y)); + } + } + + private static float Occupancy(float depth, float height) + => depth is > 0 and < 1 ? Math.Min(depth, height) * (1 - depth * depth) : 0; + + private static double ToLinear(double gray) + => gray <= 0.04045 ? gray / 12.92 : Math.Pow((gray + 0.055) / 1.055, 2.4); + + private static double LocalGray(AmbientPatch? tone, double x, double y) + { + if (tone == null) return 1; + var image = tone.Image; + double u = Math.Clamp((x - tone.X0) / (tone.X1 - tone.X0) * image.Width - 0.5, 0, image.Width - 1); + double v = Math.Clamp((tone.Y1 - y) / (tone.Y1 - tone.Y0) * image.Height - 0.5, 0, image.Height - 1); + int i = (int)u, j = (int)v; + int nextX = Math.Min(i + 1, image.Width - 1), nextY = Math.Min(j + 1, image.Height - 1); + double Pixel(int a, int b) => image.Rgb[(b * image.Width + a) * 3]; + double top = Pixel(i, j) + (Pixel(nextX, j) - Pixel(i, j)) * (u - i); + double bottom = Pixel(i, nextY) + (Pixel(nextX, nextY) - Pixel(i, nextY)) * (u - i); + return (top + (bottom - top) * (v - j)) / 255; + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Shadows.cs b/src/RvtIO/Print/ElevationPrinter.Shadows.cs new file mode 100644 index 00000000..d7c40e32 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Shadows.cs @@ -0,0 +1,633 @@ +namespace RvtIO.Print; + +using RvtIO.BuiltIns; +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +public static partial class ElevationPrinter +{ + internal sealed record CastShadow(double Light, List> Rings, + List> Openings); + + internal sealed record VisibleSiteFacets(IReadOnlySet> Sources, + List> Rings, List> Shade, double Light); + + internal sealed class ElevationShadows(double[] h, double[] v, double[] d, double shiftX, double shiftY, double light) + { + private const double PlaneTolerance = 0.01; // mm + private readonly List _casters = []; + private readonly List _receivers = []; + private readonly List _visibleFacets = []; + private readonly List _unlitBillboardFacets = []; + private readonly List _terrainFacets = []; + private readonly List _planting = []; + private readonly List _billboards = []; + private readonly List _modelOccluders = []; + private TerrainOcclusion? _terrain; + internal TerrainOcclusion Terrain => _terrain ??= new(h, v, d, _terrainFacets); + private sealed record ShadowCaster(List Outer, List> Holes, + (double X0, double Y0, double X1, double Y1) Bounds, double MinDepth, bool SiteOnly, bool ProjectsToSoilCut, + bool GroundOnly, int? RoofId, bool VerifiedOpaque, bool CastsOnVisiblePlanting); + private sealed record Receiver(List<(double X, double Y)> Face, GeoFace Geometry, + double A, double B, double C, double MaxDepth, bool Site, + (double X0, double Y0, double X1, double Y1) LightBounds, VisibleFacet? Facet = null, bool SoilCut = false, + bool Terrain = false, bool RoundShaft = false, int? RoofId = null, bool MeshFacet = false, + bool ReceivesOffscreenPlantShadows = false); + + internal sealed record VisibleFacet(List<(double X, double Y)> Points, double Dx, double Dy, double Offset, + (double X0, double Y0, double X1, double Y1) Bounds, bool MasksModel = false) + { + internal double DepthAt((double X, double Y) p) => Dx * p.X + Dy * p.Y + Offset; + } + + internal static ElevationShadows? Create((double Azimuth, double Altitude, int GroundLevel, int Intensity)? sun, + double[] h, double[] v, double[] d) + { + // Rays are parameterized by their depth into the view, so the light must come from the front. + if (sun is not { Intensity: > 0 } settings) return null; + double azimuth = settings.Azimuth; + double altitude = settings.Altitude; + double forward = -Math.Cos(azimuth) * Math.Cos(altitude); + if (forward <= 1e-9) return null; + return new(h, v, d, Math.Sin(azimuth) * Math.Cos(altitude) / forward, + Math.Sin(altitude) / forward, 1 - settings.Intensity / 100.0); + } + + internal void AddReceiver(List<(double X, double Y)> points, GeoFace face, double depth, bool roundShaft = false) + { + if (Dot(face.Normal, d) < 0 && (face.InnerLoops is not { Count: > 0 } + || face.InnerVertices is { Count: > 0 })) + _receivers.Add(new(points, face, 0, 0, depth, depth, false, + Bounds(points.Select(p => (p.X + shiftX * depth, p.Y + shiftY * depth))), RoundShaft: roundShaft)); + } + + internal void AddPlanarModelReceiver(List<(double X, double Y)> points, GeoFace face, List corners, + bool meshFacet) + { + if (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }) + AddPlanarReceiver(points, face, corners, null, site: false, meshFacet: meshFacet); + } + + internal void AddRoofReceiver(List<(double X, double Y)> points, GeoFace face, List corners, int roofId) => + AddPlanarReceiver(points, face, corners, null, roofId: roofId, site: false); + + internal void AddTerrainReceiver(List<(double X, double Y)> points, GeoFace face, List corners, + bool placed = true) + { + // shortcut: preserve the existing projection for complex faces until their holes and concave outlines are tessellated. + if (!SupportsTerrainFacet(points, face)) + { + AddPlanarReceiver(points, face, corners, null); + return; + } + + var facet = CreateVisibleFacet(h, v, d, points, face, corners); + if (facet == null) return; + if (placed) facet = facet with { MasksModel = true }; + _terrainFacets.Add(facet); + AddPlanarReceiver(points, face, corners, facet, terrain: true); + } + + private static bool SupportsTerrainFacet(List<(double X, double Y)> points, GeoFace face) => + face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && (points.Count <= 3 || Sides(points).All(side => points.All(point => + side.X * point.X + side.Y * point.Y + side.C >= -PlaneTolerance))); + + internal List<(double X, double Y)>? AddSoilCutReceiver( + (double X0, double Y0, double X1, double Y1) crop, double depth, double baseY) + { + double bottom = Math.Max(baseY, crop.Y0); + if (!(crop.Y1 > bottom && crop.X1 > crop.X0)) return null; + List<(double X, double Y)> ring = + [(crop.X0, bottom), (crop.X1, bottom), (crop.X1, crop.Y1), (crop.X0, crop.Y1)]; + var corners = ring.Select(point => Enumerable.Range(0, 3) + .Select(axis => point.X * h[axis] + point.Y * v[axis] + depth * d[axis]).ToArray()).ToList(); + var face = new GeoFace { Normal = [-d[0], -d[1], -d[2]] }; + AddPlanarReceiver(ring, face, corners, null, soilCut: true); + return ring; + } + + internal void AddVisibleFacet(List<(double X, double Y)> points, GeoFace face, List corners, + bool planting = false, bool twoSidedBillboard = false, bool receivesShadow = true, + bool receivesOffscreenPlantShadows = false) + { + var facet = CreateVisibleFacet(h, v, d, points, face, corners); + if (facet == null) return; + _visibleFacets.Add(facet); + if (planting) _planting.Add(facet); + if (twoSidedBillboard) _billboards.Add(facet); + if (receivesShadow) + AddPlanarReceiver(points, face, corners, facet, twoSidedBillboard: twoSidedBillboard, + receivesOffscreenPlantShadows: receivesOffscreenPlantShadows); + } + + internal static VisibleFacet? CreateVisibleFacet(double[] h, double[] v, double[] d, + List<(double X, double Y)> points, GeoFace face, List corners) + { + double nz = Dot(face.Normal, d); + if (Math.Abs(nz) < 1e-9) return null; + return new(points, -Dot(face.Normal, h) / nz, -Dot(face.Normal, v) / nz, + Dot(face.Normal, corners[0]) / nz, Bounds(points)); + } + + internal static Dictionary>>? VisiblePlantTones( + List facets, Dictionary tones) + { + if (tones.Count == 0) return null; + facets.Sort((left, right) => left.Bounds.X0.CompareTo(right.Bounds.X0)); + var result = new Dictionary>>(); + foreach (var (facet, gray) in tones) + { + var visible = VisibleParts(facet, facets); + if (visible.Count == 0) continue; + if (!result.TryGetValue(gray, out var rings)) result.Add(gray, rings = []); + rings.AddRange(visible); + } + return result; + } + + internal sealed class TerrainOcclusion(double[] h, double[] v, double[] d, List? facets = null) + { + private readonly List _terrain = facets ?? []; + private readonly List _targets = []; + + internal void AddSurface(List<(double X, double Y)> points, GeoFace face, List corners) + { + if (SupportsTerrainFacet(points, face) && CreateVisibleFacet(h, v, d, points, face, corners) is { } facet) + _terrain.Add(facet with { MasksModel = true }); + } + + internal void AddTarget(List<(double X, double Y)> points, GeoFace face, List corners) + { + double origin = Dot(face.Normal, corners[0]); + if (corners.All(corner => Math.Abs(Dot(face.Normal, corner) - origin) < 1e-6) + && CreateVisibleFacet(h, v, d, points, face, corners) is { } facet) + _targets.Add(facet); + } + + internal void Sort() => _terrain.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + + internal Dictionary, List>>? ClippedFaces() + { + var terrain = _terrain.Where(facet => facet.MasksModel).ToList(); + if (terrain.Count == 0) return null; + var result = new Dictionary, List>>(); + foreach (var target in _targets) + { + var visible = VisibleParts(target, terrain); + if (visible.Count != 1 || !ReferenceEquals(visible[0], target.Points)) + result.Add(target.Points, visible); + } + return result.Count > 0 ? result : null; + } + + internal List ClipEdges(List edges, bool cut, bool requireFace = true) + { + if (!_terrain.Any(facet => facet.MasksModel)) return edges; + var result = new List(edges.Count); + foreach (var edge in edges) + { + if (edge.IsCut || requireFace && edge.FaceA < 0 || edge.ViewLineStyleId != 0 || edge.NearDepth is not double depth + || cut && edge.CategoryId is not ((int)BuiltInCategory.OST_BuildingPad + or (int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_StructuralFoundation)) + { + result.Add(edge); + continue; + } + var bounds = (Math.Min(edge.X1, edge.X2), Math.Min(edge.Y1, edge.Y2), + Math.Max(edge.X1, edge.X2), Math.Max(edge.Y1, edge.Y2)); + // shortcut: clip only where terrain is ahead of the entire edge until edge endpoints carry depth. + var covers = TerrainCover(bounds, depth).ToList(); + if (covers.Count == 0) result.Add(edge); + else result.AddRange(VisibleTerrainEdges([edge], covers, [], coverBoundary: false)); + } + return result; + } + + private IEnumerable> TerrainCover( + (double X0, double Y0, double X1, double Y1) bounds, double depth) + { + foreach (var facet in _terrain) + { + var other = facet.Bounds; + if (other.X0 > bounds.X1) break; + if (!facet.MasksModel || other.X1 < bounds.X0 || other.Y1 < bounds.Y0 || other.Y0 > bounds.Y1) + continue; + double Difference((double X, double Y) point) => depth - facet.DepthAt(point) - PlaneTolerance; + var cover = ClipHalfPlane(facet.Points, p => Difference(p) > 0, Difference); + if (HasArea(cover)) yield return cover; + } + } + } + + internal void AddModelOccluder(List<(double X, double Y)> points, double[] normal, + double[] corner, double depth, List>? holes) => + AddOccluder(_modelOccluders, h, v, d, points, normal, corner, depth, holes); + + private static void AddOccluder(List occluders, double[] h, double[] v, double[] d, + List<(double X, double Y)> points, double[] normal, double[] corner, double depth, + List>? holes) + { + double nd = Dot(normal, d); + double dx = 0, dy = 0; + if (Math.Abs(nd) > 1e-10) + { + dx = -Dot(normal, h) / nd; + dy = -Dot(normal, v) / nd; + depth = Dot(normal, corner) / nd; + } + + if (points.Count == 3 && holes is not { Count: > 0 }) + { + occluders.Add(new(points, dx, dy, depth, Bounds(points))); + return; + } + + var vertices = points.ToList(); + var loops = new List { Enumerable.Range(0, points.Count).ToArray() }; + foreach (var hole in holes ?? []) + { + loops.Add(Enumerable.Range(vertices.Count, hole.Count).ToArray()); + vertices.AddRange(hole); + } + var outer = new bool[loops.Count]; + outer[0] = true; + foreach (var (a, b, c) in GeTess.TriangulateProfile(vertices, loops, outer)) + { + var triangle = new List<(double X, double Y)> { vertices[a], vertices[b], vertices[c] }; + occluders.Add(new(triangle, dx, dy, depth, Bounds(triangle))); + } + } + + internal sealed class PlantingOutlines(double[] h, double[] v, double[] d, double viewPlaneDepth, + ElevationShadows? shadows) + { + private readonly List _trees = []; + private readonly List _model = []; + + internal sealed class Mesh(bool clipAtViewPlane) + { + internal bool ClipAtViewPlane { get; } = clipAtViewPlane; + internal readonly List Facets = []; + internal readonly Dictionary<((long, long, long), (long, long, long)), + (double[] A, double[] B, VisibleFacet? Source)> Edges = []; + } + + internal void AddFacet(Mesh tree, List world, List<(double X, double Y)> ring, GeoFace face, + List corners) + { + var facet = HasArea(ring) ? CreateVisibleFacet(h, v, d, ring, face, corners) : null; + if (facet != null) tree.Facets.Add(facet); + for (int i = 0; i < world.Count; i++) + { + var a = world[i]; + var b = world[(i + 1) % world.Count]; + var first = Key(a); + var second = Key(b); + var key = first.CompareTo(second) < 0 ? (first, second) : (second, first); + if (!tree.Edges.TryAdd(key, (a, b, facet))) tree.Edges[key] = default; + } + + static (long, long, long) Key(double[] point) => ((long)Math.Round(point[0] / PlaneTolerance), + (long)Math.Round(point[1] / PlaneTolerance), (long)Math.Round(point[2] / PlaneTolerance)); + } + + internal void AddTree(Mesh tree) + { + if (tree.Facets.Count > 0) _trees.Add(tree); + } + + internal void AddModelOccluder(List<(double X, double Y)> points, double[] normal, + double[] corner, double depth, List>? holes) + { + if (shadows == null) + AddOccluder(_model, h, v, d, points, normal, corner, depth, holes); + } + + internal IEnumerable Project(List> ground) + { + if (_trees.Count == 0) yield break; + var covers = (shadows?._modelOccluders ?? _model).Concat(_trees.SelectMany(tree => tree.Facets)) + .OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var tree in _trees) + foreach (var (a, b, source) in tree.Edges.Values) + { + if (source == null) continue; + double start = Dot(a, d) - viewPlaneDepth, end = Dot(b, d) - viewPlaneDepth; + if (tree.ClipAtViewPlane && start < 0 && end < 0) continue; + double x0 = Dot(a, h), y0 = Dot(a, v), x1 = Dot(b, h), y1 = Dot(b, v); + if (tree.ClipAtViewPlane && (start < 0 || end < 0)) + { + double t = start / (start - end); + double x = x0 + t * (x1 - x0), y = y0 + t * (y1 - y0); + if (start < 0) (x0, y0) = (x, y); + else (x1, y1) = (x, y); + } + var edge = new CollectedEdge(x0, y0, x1, y1, 0, 0, -1, -1, 0, 0, 0, 0, + false, (int)BuiltInCategory.OST_Planting); + foreach (var span in VisibleTerrainEdges([edge], GroundAndCloser(edge, source), [], coverBoundary: false)) + yield return span; + } + + IEnumerable> GroundAndCloser(CollectedEdge edge, VisibleFacet source) + { + foreach (var ring in ground) yield return ring; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double low = Math.Min(edge.Y1, edge.Y2), high = Math.Max(edge.Y1, edge.Y2); + foreach (var cover in covers) + { + if (cover.Bounds.X0 > right) break; + if (ReferenceEquals(source, cover) || cover.Bounds.X1 < left + || cover.Bounds.Y0 > high || cover.Bounds.Y1 < low) continue; + double Difference((double X, double Y) point) => + source.DepthAt(point) - cover.DepthAt(point) - PlaneTolerance; + var mask = ClipHalfPlane(cover.Points, p => Difference(p) > 0, Difference); + if (HasArea(mask)) yield return mask; + } + } + } + } + + internal VisibleSiteFacets? ClipSiteFacetsToModel(Dictionary, CastShadow>? shadows) + { + if ((_planting.Count == 0 && _billboards.Count == 0) || _modelOccluders.Count == 0) return null; + _modelOccluders.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + var sources = new HashSet>(); + var rings = new List>(); + var shade = new List>(); + foreach (var facet in _planting) AddVisible(facet, _modelOccluders); + if (_billboards.Count > 0) + { + var covers = _modelOccluders.Concat(_planting).OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var facet in _billboards) AddVisible(facet, covers); + } + return new(sources, rings, shade, light); + + void AddVisible(VisibleFacet facet, List covers) + { + sources.Add(facet.Points); + var visible = VisibleParts(facet, covers); + rings.AddRange(visible); + if (shadows?.GetValueOrDefault(facet.Points) is { } shadow) + shade.AddRange(visible.Count == 1 && ReferenceEquals(visible[0], facet.Points) + ? shadow.Rings : ClipRings(shadow.Rings, visible)); + } + } + + private void AddPlanarReceiver(List<(double X, double Y)> points, GeoFace face, List corners, + VisibleFacet? facet, bool soilCut = false, bool terrain = false, bool twoSidedBillboard = false, int? roofId = null, + bool site = true, bool meshFacet = false, bool receivesOffscreenPlantShadows = false) + { + double nx = Dot(face.Normal, h), ny = Dot(face.Normal, v); + double viewNormal = Dot(face.Normal, d); + double nz = viewNormal - nx * shiftX - ny * shiftY; + // A two-sided display face receives direct light only from the side visible in the view. + if (twoSidedBillboard && facet != null && (viewNormal < 0 ? nz >= -1e-9 : nz <= 1e-9)) + { + _unlitBillboardFacets.Add(facet); + return; + } + // Foundation mesh facets can receive a verified model shadow from either side. + if (!meshFacet && (facet == null || terrain) ? !(nz < -1e-9) : Math.Abs(nz) < 1e-9) return; + // In light coordinates (u, v, depth), the receiving plane has depth A*u + B*v + C. + var lightRing = corners.Select(point => LightCoordinates(point, 1)).ToList(); + _receivers.Add(new(points, face, -nx / nz, -ny / nz, Dot(face.Normal, corners[0]) / nz, + lightRing.Max(point => point[2]), site, Bounds(lightRing.Select(point => (point[0], point[1]))), + facet, soilCut, terrain, RoofId: roofId, MeshFacet: meshFacet, + ReceivesOffscreenPlantShadows: receivesOffscreenPlantShadows)); + } + + internal void AddCaster(GeoFace face, List corners, bool siteOnly = false, bool planting = false, + bool groundOnly = false, int? roofId = null, bool verifiedOpaque = false, + bool castsOnVisiblePlanting = false, bool castsOnSoilCut = true) + { + if (face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 }) return; + var outer = corners.Select(point => LightCoordinates(point, 1)).ToList(); + if (outer.Any(point => !point.All(double.IsFinite))) return; + var holes = (face.InnerVertices ?? []).Select(ring => + ring.Select(point => LightCoordinates(point, FeetToMillimetres)).ToList()).ToList(); + if (holes.Any(ring => ring.Count < 3 || ring.Any(point => !point.All(double.IsFinite)))) return; + // The foreground faces of the cut's planting projection are the ones facing + // into the view. Edge-on faces can still project along the light direction. + bool projectsToSoilCut = planting && castsOnSoilCut && Dot(face.Normal, d) >= -1e-6; + _casters.Add(new(outer, holes, Bounds(outer.Select(point => (point[0], point[1]))), + outer.Min(point => point[2]), siteOnly, projectsToSoilCut, groundOnly, roofId, verifiedOpaque, + castsOnVisiblePlanting)); + } + + internal Dictionary, CastShadow>? Project(double viewDepth) + { + var result = new Dictionary, CastShadow>(); + var facets = _visibleFacets.OrderBy(facet => facet.Bounds.X0).ToList(); + _terrainFacets.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + var visibleCasters = new List(); + if (facets.Count > 0 || _receivers.Any(receiver => !receiver.Site)) + { + double[] near = [0, 0, viewDepth], away = [0, 0, 1]; + foreach (var caster in _casters) + { + if (caster.GroundOnly) continue; + if (caster.MinDepth >= viewDepth) { visibleCasters.Add(caster); continue; } + var outer = ClipBehind(caster.Outer, near, away); + if (outer.Count < 3) continue; + visibleCasters.Add(caster with + { + Outer = outer, + Holes = caster.Holes.Select(hole => ClipBehind(hole, near, away)).ToList(), + Bounds = Bounds(outer.Select(point => (point[0], point[1]))), + MinDepth = viewDepth, + }); + } + } + List? plantingCasters = null; + foreach (var receiver in _receivers) + { + var (face, geometry, a, b, c, maxDepth, site, lightBounds, facet, soilCut, terrain, roundShaft, roofId, + meshFacet, receivesOffscreenPlantShadows) = receiver; + var bounds = Bounds(face); + double[] limit = [0, 0, c - PlaneTolerance], normal = [a, b, -1]; + var rings = new List>(); + if (roundShaft && shiftX != 0) + { + // Project the point where the horizontal light ray is tangent to the cylinder. + double radius = (bounds.X1 - bounds.X0) / 2; + double terminator = bounds.X0 + radius - Math.CopySign(radius / Math.Sqrt(1 + shiftX * shiftX), shiftX); + var shade = ClipToWindow(face, shiftX > 0 ? bounds.X0 : terminator, + shiftX > 0 ? terminator : bounds.X1, bounds.Y0, bounds.Y1); + if (PlanPrinter.SignedArea(shade) < 0) shade.Reverse(); + if (HasArea(shade)) rings.Add(shade); + } + var casters = site && (facet == null || terrain) ? _casters + : receivesOffscreenPlantShadows + ? plantingCasters ??= visibleCasters.Concat(_casters.Where(caster => caster.CastsOnVisiblePlanting)).ToList() + : visibleCasters; + foreach (var caster in casters) + { + if (caster.RoofId != roofId || meshFacet && !caster.VerifiedOpaque + || soilCut && !caster.ProjectsToSoilCut || caster.SiteOnly && !site + || caster.MinDepth >= maxDepth - PlaneTolerance + || caster.Bounds.X0 >= lightBounds.X1 || caster.Bounds.X1 <= lightBounds.X0 + || caster.Bounds.Y0 >= lightBounds.Y1 || caster.Bounds.Y1 <= lightBounds.Y0) continue; + if (!AddRing(caster.Outer, false)) continue; + foreach (var hole in caster.Holes) AddRing(hole, true); + } + if (rings.Count == 0) continue; + if (facet != null) + { + rings = ClipToVisibleFacet(rings, facet, terrain ? _terrainFacets : facets); + if (rings.Count == 0) continue; + } + var openings = (geometry.InnerVertices ?? []).Select(ring => ring.Select(point => + (Dot(point, h) * FeetToMillimetres, Dot(point, v) * FeetToMillimetres)).ToList()).ToList(); + result.Add(face, new CastShadow(light, rings, openings)); + + bool AddRing(List polygon, bool hole) + { + var ring = ClipBehind(polygon, limit, normal).Select(point => + { + double depth = a * point[0] + b * point[1] + c; + return (point[0] - depth * shiftX, point[1] - depth * shiftY); + }).ToList(); + ring = ClipToWindow(ring, bounds.X0, bounds.X1, bounds.Y0, bounds.Y1); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) <= PlaneTolerance * PlaneTolerance) return false; + if ((area > 0) == hole) ring.Reverse(); + rings.Add(ring); + return true; + } + } + foreach (var facet in _unlitBillboardFacets) + { + var shade = VisibleParts(facet, facets); + if (shade.Count > 0) result.Add(facet.Points, new CastShadow(light, shade, [])); + } + return result.Count > 0 ? result : null; + } + + private static List> ClipToVisibleFacet(List> rings, + VisibleFacet facet, List facets) + { + return ClipRings(rings, VisibleParts(facet, facets)); + } + + internal Dictionary, List>> ClippedReceivers( + IReadOnlySet> targets, IReadOnlyList additionalCovers) + { + var visible = new Dictionary, List>>(); + if (targets.Count == 0) return visible; + var facets = _visibleFacets.Concat(additionalCovers).OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var facet in facets) + { + if (!targets.Contains(facet.Points)) continue; + var parts = VisibleParts(facet, facets); + if (parts.Count != 1 || !ReferenceEquals(parts[0], facet.Points)) + visible.Add(facet.Points, parts); + } + return visible; + } + + private static List> VisibleParts(VisibleFacet facet, + List facets) + { + List> visible = [facet.Points]; + // Intersect each covering facet with the half-plane where it is closer to the view. + foreach (var nearer in facets) + { + if (nearer.Bounds.X0 >= facet.Bounds.X1 || visible.Count == 0) break; + if (ReferenceEquals(facet, nearer) || nearer.Bounds.X1 <= facet.Bounds.X0 + || nearer.Bounds.Y0 >= facet.Bounds.Y1 || nearer.Bounds.Y1 <= facet.Bounds.Y0) continue; + double Difference((double X, double Y) point) => + facet.DepthAt(point) - nearer.DepthAt(point) - PlaneTolerance; + var cover = ClipHalfPlane(nearer.Points, point => Difference(point) > 0, Difference); + if (!HasArea(cover)) continue; + var sides = Sides(cover); + var uncovered = new List>(); + foreach (var polygon in visible) + { + if (!HasArea(ClipConvex(polygon, sides))) + { + uncovered.Add(polygon); + continue; + } + var inside = polygon; + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + var outside = ClipHalfPlane(inside, p => Distance(p) < 0, Distance); + if (HasArea(outside)) uncovered.Add(outside); + inside = ClipHalfPlane(inside, p => Distance(p) >= 0, Distance); + } + } + visible = uncovered; + } + return visible; + } + + private static List> ClipRings(List> rings, + List> visible) + { + var result = new List>(); + foreach (var polygon in visible) + { + var sides = Sides(polygon); + foreach (var ring in rings) + { + var clipped = ClipConvex(ring, sides); + if (HasArea(clipped)) result.Add(clipped); + } + } + return result; + + } + + private static bool HasArea(List<(double X, double Y)> polygon) => + Math.Abs(PlanPrinter.SignedArea(polygon)) > PlaneTolerance * PlaneTolerance; + + private static List<(double X, double Y, double C)> Sides(List<(double X, double Y)> polygon) + { + int winding = Math.Sign(PlanPrinter.SignedArea(polygon)); + var sides = new List<(double X, double Y, double C)>(polygon.Count); + for (int i = 0; i < polygon.Count; i++) + { + var a = polygon[i]; + var b = polygon[(i + 1) % polygon.Count]; + double x = winding * (a.Y - b.Y), y = winding * (b.X - a.X); + sides.Add((x, y, -x * a.X - y * a.Y)); + } + return sides; + } + + private static List<(double X, double Y)> ClipConvex(List<(double X, double Y)> polygon, + List<(double X, double Y, double C)> sides) + { + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + polygon = ClipHalfPlane(polygon, p => Distance(p) >= 0, Distance); + if (polygon.Count < 3) break; + } + return polygon; + } + + private double[] LightCoordinates(double[] point, double units) + { + double depth = Dot(point, d) * units; + return [Dot(point, h) * units + depth * shiftX, Dot(point, v) * units + depth * shiftY, depth]; + } + + private static double Dot(double[] point, double[] axis) => + point[0] * axis[0] + point[1] * axis[1] + point[2] * axis[2]; + + private static (double X0, double Y0, double X1, double Y1) Bounds(IEnumerable<(double X, double Y)> points) + { + double x0 = double.PositiveInfinity, y0 = double.PositiveInfinity; + double x1 = double.NegativeInfinity, y1 = double.NegativeInfinity; + foreach (var (x, y) in points) + { + x0 = Math.Min(x0, x); y0 = Math.Min(y0, y); + x1 = Math.Max(x1, x); y1 = Math.Max(y1, y); + } + return (x0, y0, x1, y1); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.cs b/src/RvtIO/Print/ElevationPrinter.cs index 41ed03f7..d2ec83c4 100644 --- a/src/RvtIO/Print/ElevationPrinter.cs +++ b/src/RvtIO/Print/ElevationPrinter.cs @@ -15,18 +15,8 @@ public sealed record ElevationView(int ViewId, string Name, string Direction, in /// A section trace on a plan: the polyline points in model millimetres and whether they are /// the file's decoded extent (bounded: drawn as-is) or a legacy straight-line mark (a ray through the /// two points, extended to the drawing bounds the way an undecodable trace was always drawn). -internal sealed record SectionMark(List<(double X, double Y)> Points, bool Bounded, string Name); - -/// Per-view corrections to a decoded section trace, in model millimetres, measured on the -/// reference export of the sample; records why they are not -/// derivable from the file. -internal static class MeasuredSectionTraceOffsets -{ - internal static readonly Dictionary ByViewName = new() - { - ["Longitudinal Section"] = (3090, 0), - }; -} +internal sealed record SectionMark(List<(double X, double Y)> Points, bool Bounded, string Name, int ViewId = 0, + bool UsesPlanExtent = false); /// /// Prints an elevation from the 3D geometry the reader decodes: every planar face of the model (walls, floors, roofs, @@ -34,7 +24,7 @@ internal static class MeasuredSectionTraceOffsets /// nearest and outlined when it faces the viewer. The view plane itself is not decoded yet, so the direction is taken /// from the view name (North, South, East, West); a section is not printed (see docs/printing.md). /// -public static class ElevationPrinter +public static partial class ElevationPrinter { private const double FeetToMillimetres = 304.8; @@ -101,9 +91,59 @@ internal sealed record ElevationContent( List<(List<(double X, double Y)> Points, double Depth, bool Outline)> Faces, List<(double Y, string Label, double X0, double X1)> Levels, List<(double X, string Name)> Grids, - List<(List<(double X, double Y)> Points, double Depth)> Context, + List<(List<(double X, double Y)> Points, double Depth, bool Terrain)> Context, List Edges, - double MinX, double MinY, double MaxX, double MaxY); + double MinX, double MinY, double MaxX, double MaxY, + TerrainHatch? GroundHatch = null, + IReadOnlyDictionary? NativeLevels = null, + IReadOnlyDictionary? NativeGrids = null, + List? Insulation = null, + IReadOnlyList? DetailBreaks = null, + IReadOnlyList? LayerHatches = null, + IReadOnlyList? AnnotationSymbols = null, + SurfaceHatches? Hatch = null, + IReadOnlyDictionary, ModelHatch>? ModelHatches = null, + IReadOnlyDictionary, CastShadow>? CastShadows = null, + (int Sky, int Horizon, int? Ground)? SkyGradient = null, + List>? SiteSilhouettes = null, + bool OpaqueSection = false, + IReadOnlyList? SiteOutlines = null, + IReadOnlyDictionary, List>>? FaceOpenings = null, + VisibleSiteFacets? ForegroundSite = null, + IReadOnlyList? SectionBands = null, + IReadOnlyList>? DetailCutFaces = null, + AmbientGlazing? Glazing = null, + IReadOnlyDictionary, AmbientPatch>? AmbientTones = null, + IReadOnlyDictionary, double?>? FaceFills = null, + IReadOnlyDictionary, (double Gray, double Opacity)>? DetailGlass = null, + IReadOnlyDictionary, List>>? TerrainClippedFaces = null, + bool KeepDoorDepths = false, + IReadOnlyList>? SectionBillboards = null, + IReadOnlyDictionary>>? PlantTones = null, + IReadOnlyDictionary, (double BaseY, double Light)>? ExteriorWallTones = null, + IReadOnlyDictionary, AmbientPatch>? PaneTones = null); + + internal sealed record SectionBand(double Left, double Right, ElevationContent Content); + + internal sealed record SurfaceHatches(double AnchorX, double AnchorY, + IReadOnlyDictionary, (Parsing.TfBlockDeserializer.PatternGrid Grid, double Width)> Faces, + IReadOnlyDictionary, IReadOnlyList> DashedFaces, + bool UseClippedLines, + IReadOnlyDictionary, List>? Regions = null); + + internal sealed record SurfaceHatchRegion(Parsing.TfBlockDeserializer.PatternGrid Grid, + List<(double X, double Y)> Outer, List> Holes); + + internal sealed record ModelHatch(IReadOnlyList Grids, + IReadOnlyList> Holes); + + internal sealed record TerrainHatch(double AnchorX, double AnchorY, double BaseY, + IReadOnlyList Profile, IReadOnlyList Grids, + IReadOnlyList>? SectionMasks = null, CastShadow? Shadow = null); + + internal sealed record NativeLevelLine(double Left, double HeadX, double HeadY, double LineEnd, double Radius, + (double X, double Y)? Elbow, int SymbolId = 0); + internal sealed record NativeGridLine(double Bottom, double Top, double Radius); /// Projects the model geometry on the vertical plane of a direction. Null when the model has no face. /// The categories a stair section draws: the stairs, their railings and supports. Treads and @@ -118,12 +158,74 @@ internal sealed record ElevationContent( internal static ElevationContent? Collect(RvtDocument document, string direction, bool stairsOnly = false, Element? planeView = null, (double Width, double Height)? window = null, bool isDetail = false, - (double X0, double Y0, double X1, double Y1)? cropWindow = null) + (double X0, double Y0, double X1, double Y1)? cropWindow = null, int? viewportScale = null) + { + var content = CollectPlane(document, direction, stairsOnly, planeView, window, isDetail, cropWindow, + viewportScale, planeView?.ViewOrigin); + if (direction != "section" || planeView is not + { + SectionViewerId: int viewerId, ViewOrigin: { Length: 3 } origin, + ViewDirection: { Length: 3 } look, ViewHorizontalDirection: { Length: 3 } horizontal, + ViewVerticalDirection: { Length: 3 } vertical, + } || document.RawData.SectionViews?.GetValueOrDefault(viewerId).FrontCut is not { Count: >= 4 } frontCut + || frontCut.Count % 2 != 0) return content; + + const double tolerance = 0.1; // Same model precision as the projected edges. + var points = frontCut.Select(p => (X: Project(p, horizontal), Y: Project(p, vertical), + Depth: Project(p, look))).ToArray(); + if (points[0].X > points[^1].X) Array.Reverse(points); + if (points.Any(p => Math.Abs(p.Y - points[0].Y) > tolerance)) return content; + for (int i = 0; i < points.Length; i += 2) + { + var start = points[i]; + var end = points[i + 1]; + if (end.X - start.X <= tolerance || Math.Abs(end.Depth - start.Depth) > tolerance + || i > 0 && Math.Abs(start.X - points[i - 1].X) > tolerance) return content; + } + + var bands = new List(points.Length / 2); + double originalDepth = Project(origin, look); + for (int i = 0; i < points.Length; i += 2) + { + // A section's end marks bound its plan symbol. The end planes extend to the model crop. + double left = i == 0 ? double.NegativeInfinity : points[i].X; + double right = i + 2 == points.Length ? double.PositiveInfinity : points[i + 2].X; + if (cropWindow is { } crop && (right <= crop.X0 || left >= crop.X1)) continue; + double depthShift = points[i].Depth - originalDepth; + if (Math.Abs(depthShift) <= tolerance) + { + if (cropWindow is { } detail && left <= detail.X0 && right >= detail.X1) return content; + if (content != null) bands.Add(new(left, right, content)); + continue; + } + double delta = depthShift / FeetToMillimetres; + double[] shiftedOrigin = [origin[0] + look[0] * delta, origin[1] + look[1] * delta, + origin[2] + look[2] * delta]; + var bandContent = CollectPlane(document, direction, stairsOnly, planeView, window, isDetail, cropWindow, + viewportScale, shiftedOrigin); + if (bandContent != null) + bands.Add(new(left, right, bandContent with { Edges = TrimProjectedEdgesAtCuts(bandContent.Edges).ToList() })); + } + if (bands.Count == 0) return null; + var frame = content ?? bands[0].Content; + return frame with + { + MinX = Math.Min(frame.MinX, bands.Min(band => band.Content.MinX)), + MinY = Math.Min(frame.MinY, bands.Min(band => band.Content.MinY)), + MaxX = Math.Max(frame.MaxX, bands.Max(band => band.Content.MaxX)), + MaxY = Math.Max(frame.MaxY, bands.Max(band => band.Content.MaxY)), + SectionBands = bands, + }; + } + + private static ElevationContent? CollectPlane(RvtDocument document, string direction, bool stairsOnly, + Element? planeView, (double Width, double Height)? window, bool isDetail, + (double X0, double Y0, double X1, double Y1)? cropWindow, int? viewportScale, double[]? projectionOrigin) { double[] planeOrigin = []; bool cut = false; double[] H, V, D; - if (planeView is { ViewOrigin: { Length: 3 } origin, ViewDirection: { Length: 3 } dir, + if (projectionOrigin is { Length: 3 } origin && planeView is { ViewDirection: { Length: 3 } dir, ViewVerticalDirection: { Length: 3 } vert, ViewHorizontalDirection: { Length: 3 } horiz }) { (H, V, D) = (horiz, vert, dir); @@ -169,14 +271,21 @@ internal sealed record ElevationContent( var faces = new List<(List<(double X, double Y)> Points, double Depth, bool Outline)>(); // The plants, the topography and the site surfaces print as the faded background of an elevation, behind the // building, the way the reference export fades them. - var context = new List<(List<(double X, double Y)> Points, double Depth)>(); + var context = new List<(List<(double X, double Y)> Points, double Depth, bool Terrain)>(); // The outlined faces for the shared-edge pass below, with their 3D rings for midpoint depths // and the category of the element they came from (a cut edge inks with its own category's pen). - var edgeFaces = new List<(List<(double X, double Y)> Points, List Ring, double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId)>(); + var edgeFaces = new List(); // Every face for the occlusion pass below: its smallest corner depth, so an edge hidden // behind nearer mass is not inked even though the painter's fills cover it only visually. A face counts // as nearer when its nearest corner stands nearer, even a face turned away from the view. - var faceMinDepths = new List(); + var faceOccluders = new List<(double MinDepth, int ElementId, int? HostId, int CategoryId, + PlanarOcclusion? Plane)>(); + var roofInsertFaces = new HashSet(); + var stairMasks = new Dictionary>(); + var railingMaskDepths = new Dictionary(); + var topRailEdges = new List(); + var elevationTubeEdges = new List(); + var viewLines = new List(); // The chords where the cut plane slices through a face, in page coordinates: the cut profile of // solids the plane passes through. Transverse faces never outline, so the cut flag never marks their // boundary, yet the plane carves a profile out of them (a wall cross-section in a detail). Outline @@ -185,29 +294,316 @@ internal sealed record ElevationContent( // type's layer boundaries drawn between them. var rawChords = new List<(double X1, double Y1, double X2, double Y2, double Nx, double Ny, double Nz, int TypeId, int CategoryId, double Depth)>(); + var wallChordSources = new Dictionary(); + var wallCutRegions = new List<(int WallId, int MaterialId, List<(double X, double Y)> Ring)>(); + bool detailPath = window != null || isDetail || cropWindow != null; + int viewScale = planeView?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is int scaleValue && scaleValue > 0 + ? scaleValue : 100; + var surfacePatterns = new Dictionary, + (Parsing.TfBlockDeserializer.PatternGrid Grid, double Width)>(); + var modelHatches = new Dictionary, ModelHatch>(); + Dictionary, List>? regionHatches = null; + var faceFills = new Dictionary, double?>(); + var exteriorWallTones = new Dictionary, (double BaseY, double Light)>(); + var roundShaftFaces = new HashSet(); + var paintOpenings = new Dictionary, List>>(); + var dashedSurfacePatterns = new Dictionary, IReadOnlyList>(); + var shadows = !cut && !stairsOnly && planeOrigin.Length == 3 && Math.Abs(V[2] - 1) < 1e-9 + ? ElevationShadows.Create(document.RawData.ViewGroundShadows?.GetValueOrDefault(planeView!.Id), H, V, D) + : null; + var shadowTerrainCrop = shadows != null && planeView?.ViewCrop is { Active: true } terrainCrop + && SheetComposer.ViewBasisMatches(planeView, terrainCrop) ? SheetComposer.CropContentRect(terrainCrop) + : ((double X0, double Y0, double X1, double Y1)?)null; + // shortcut: keep the unlit ground backdrop white until its terrain coverage is decoded. + (int Sky, int Horizon, int? Ground)? skyGradient = !cut && !stairsOnly && planeView is { ViewCrop.Active: true } + && Math.Abs(V[2] - 1) < 1e-9 + && document.RawData.ViewSkyGradients?.TryGetValue(planeView.Id, out var sky) == true + ? (sky.Sky, sky.Horizon, shadowTerrainCrop != null ? sky.Ground : null) + : null; + bool fineSection = cut && viewScale <= 50; + bool keepDoorDepths = fineSection && !detailPath; + int? viewDetail = planeOrigin.Length == 3 + ? planeView?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int? : null; + bool showSurfacePatterns = planeView != null + && document.RawData.OpaqueViewsWithSurfacePatterns?.Contains(planeView.Id) == true; + // shortcut: surface hatching in fine sections, until the view's coarse surface overrides are decoded. + bool showDraftingPatterns = fineSection && showSurfacePatterns; + var datumCrop = isDetail ? cropWindow : null; + if (datumCrop == null && window == null && cut + && planeView is { ViewAnnotationCropActive: true, ViewCrop: { Active: true } viewCrop } + && SheetComposer.ViewBasisMatches(planeView, viewCrop)) + datumCrop = SheetComposer.CropContentRect(viewCrop); + (double X0, double Y0, double X1, double Y1)? sectionAnnotationCrop = null; + if (datumCrop is { } modelCrop && planeView?.ViewAnnotationCrop is { } offsets) + { + double paperToModel = FeetToMillimetres * (viewportScale ?? viewScale); + sectionAnnotationCrop = (modelCrop.X0 - offsets.Left * paperToModel, modelCrop.Y0 - offsets.Bottom * paperToModel, + modelCrop.X1 + offsets.Right * paperToModel, modelCrop.Y1 + offsets.Top * paperToModel); + } + var sectionCrop = cropWindow; + if (fineSection && window == null && sectionCrop == null && planeView?.ViewCrop is { Active: true } sectionViewCrop + && SheetComposer.ViewBasisMatches(planeView, sectionViewCrop)) + sectionCrop = SheetComposer.CropContentRect(sectionViewCrop); + bool drawTerrainCut = planeOrigin.Length == 3 && !stairsOnly && !detailPath && viewScale >= 100; + bool overviewSection = cut && drawTerrainCut; + bool drawGround = drawTerrainCut || cut && !stairsOnly && sectionCrop != null; + bool detailCallout = planeView?.SectionViewerId is int sectionViewer + && document.RawData.SectionViews?.GetValueOrDefault(sectionViewer).ParentViewId is > 0; + // The backing surfaces are available in a full section, outside the detail cut-cap pipeline. + var glazing = fineSection && !detailPath && showSurfacePatterns && planeView != null + && document.RawData.ViewAmbientLight?.TryGetValue(planeView.Id, out double ambientLight) == true + ? new AmbientGlazing(ambientLight, detailCallout) : null; + bool paintDetailCuts = cut && isDetail && cropWindow != null && planeView != null + && document.RawData.OpaquePlanViews?.Contains(planeView.Id) == true; + bool opaqueSection = cut && planeView != null && document.RawData.OpaquePlanViews?.Contains(planeView.Id) == true; + bool opaqueFineSection = opaqueSection && fineSection && sectionCrop != null; + bool regularFineSection = opaqueFineSection && !detailPath && !detailCallout; + bool regularOpaqueSection = regularFineSection || opaqueSection && drawTerrainCut && showSurfacePatterns; + var sectionTerrainCrop = opaqueSection && drawTerrainCut && showSurfacePatterns + && planeView?.ViewCrop is { Active: true } sectionTerrainViewCrop + && SheetComposer.ViewBasisMatches(planeView, sectionTerrainViewCrop) + ? SheetComposer.CropContentRect(sectionTerrainViewCrop) + : ((double X0, double Y0, double X1, double Y1)?)null; + var sectionTerrain = sectionTerrainCrop.HasValue ? new ElevationShadows.TerrainOcclusion(H, V, D) : null; + var terrainOcclusion = shadowTerrainCrop != null ? shadows!.Terrain : sectionTerrain; + var terrainFillCrop = shadowTerrainCrop ?? sectionTerrainCrop; + double ambientFraction = 0; + var ambient = opaqueFineSection && (!detailPath || paintDetailCuts) && sectionCrop is { } lightCrop + && document.RawData.ViewAmbientFractions?.TryGetValue(planeView!.Id, out ambientFraction) == true + ? new AmbientOcclusion(ambientFraction, lightCrop, binaryVisibility: regularFineSection) : null; + bool screenShadows = ambient != null && glazing != null && detailCallout; + var screenPaneOwners = screenShadows ? new HashSet() : null; + var screenWallReceivers = screenShadows ? new Dictionary, double>() : null; + var plantSun = sectionTerrainCrop.HasValue ? SolarStudyOverlay.StillSunDirection(document.RawData, planeView!.Id) : null; + double plantAmbientFraction = plantSun.HasValue + ? document.RawData.ViewAmbientFractions?.GetValueOrDefault(planeView!.Id, 1) ?? 1 : 1; + var plantFacets = new List(); + var plantTones = new Dictionary(); + var detailGlass = paintDetailCuts && ambient != null + ? new Dictionary, (double Gray, double Opacity)>() + : null; + var roofSectionCrop = opaqueFineSection || paintDetailCuts ? sectionCrop : null; + if (roofSectionCrop == null && opaqueSection && viewDetail == 3 && window == null + && planeView?.ViewCrop is { Active: true } roofViewCrop && SheetComposer.ViewBasisMatches(planeView, roofViewCrop)) + roofSectionCrop = SheetComposer.CropContentRect(roofViewCrop); + List>? modelSectionMasks = roofSectionCrop != null && !paintDetailCuts ? [] : null; + List? layerBoundaries = roofSectionCrop != null ? [] : null; + var sectionedLayerChords = new HashSet(); + bool hasSiteProjection = !stairsOnly && planeOrigin.Length == 3; + bool projectSiteMeshes = hasSiteProjection && (!cut || drawTerrainCut); + List>? siteSilhouettes = + projectSiteMeshes || hasSiteProjection && paintDetailCuts ? [] : null; + bool clipSiteContext = cut && !projectSiteMeshes; + var siteObjects = new List<(List Edges, double Near, bool WireMesh)>(); + var sectionBillboards = new List>(); + var plantMasks = new List<(List<(double X, double Y)> Points, double Far)>(); + var siteModelMasks = new List<(List<(double X, double Y)> Points, double Near, double Far)>(); + double[]? towardViewer = drawTerrainCut && !cut ? [-D[0], -D[1], -D[2]] : null; + double viewPlaneDepth = planeOrigin.Length == 3 + ? planeOrigin[0] * D[0] + planeOrigin[1] * D[1] + planeOrigin[2] * D[2] : 0; + var plantingOutlines = drawTerrainCut && showSurfacePatterns + ? new ElevationShadows.PlantingOutlines(H, V, D, viewPlaneDepth, shadows) : null; + var terrainEdges = new List(); + var terrainPads = new List<(double From, double To)>(); + var padProfile = new List(); + var terrainForeground = new List>(); + var terrainSectionMasks = new List>(); + List>? detailRoofCuts = paintDetailCuts ? [] : null; + List>? detailWallCuts = paintDetailCuts ? [] : null; + var sectionWallFaces = new Dictionary(); + var detailWallOccluders = paintDetailCuts ? new List<(List<(double X, double Y)> Points, double Depth)>() : null; + bool roundElevationShafts = !cut && drawTerrainCut && showSurfacePatterns; + var spanOccluders = fineSection || roundElevationShafts + ? new List<(List<(double X, double Y)> Points, double FarDepth, bool ViewAlignedSlabSide)>() : null; + var spanOpenings = roundElevationShafts + ? new Dictionary, List>>() : null; + var elevationCutEdges = new List(); + var meshSilhouettes = new List(); + bool calloutFurnitureMeshes = opaqueFineSection && detailCallout && !detailPath; + var meshCovers = opaqueSection && (drawTerrainCut || regularFineSection || calloutFurnitureMeshes) + ? new List<(List<(double X, double Y)> Points, double FarDepth, int ElementId)>() + : null; + var furnitureCovers = overviewSection && opaqueSection ? new Dictionary() : null; + TerrainHatch? groundHatch = null; + List? layerHatches = sectionCrop != null && (isDetail || fineSection && window == null) + || roofSectionCrop != null && window == null || towardViewer != null && showSurfacePatterns + ? [] : null; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; + double maxElevationTubeDiameter = 0; + if (!cut && drawTerrainCut && showSurfacePatterns) + { + int scale = viewportScale ?? viewScale; + double width = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, false, scale, out double pen) + ? pen : 0.2; + maxElevationTubeDiameter = width * scale / FeetToMillimetres; + } + var hiddenElements = planeView == null ? null : document.RawData.ViewHiddenElements?.GetValueOrDefault(planeView.Id); + var hiddenCategories = regularFineSection || paintDetailCuts + ? document.RawData.ViewHiddenCategories?.GetValueOrDefault(planeView!.Id) : null; foreach (var element in document.Elements) { - if (element.CategoryId is (int)BuiltInCategory.OST_Planting or (int)BuiltInCategory.OST_Topography - or (int)BuiltInCategory.OST_Site or (int)BuiltInCategory.OST_Entourage) + if (hiddenElements?.Contains(element.Id) == true + || element.CategoryId is int category && hiddenCategories?.Contains(category) == true) continue; + if (opaqueFineSection && document.RawData.ElemTableIsExact + && element.SerializedOwningElementId is > 0 and int owner + && document.GetElement(owner)?.RootClassIs("Family") == true) continue; + if (regularFineSection && (element.NativeIsSymbol == true || element.SerializedUnplacedOwnerId is > 0 + || element.RootClassIs("FamilySymbol") || element.RootClassName == "FillPatternElem" + || document.RawData.ElemTableIsExact && element.IsDiscovered)) continue; + if (regularOpaqueSection && document.RawData.ElemTableIsExact + && element.CategoryId is ((int)BuiltInCategory.OST_Casework or (int)BuiltInCategory.OST_StructuralColumns + or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_Furniture + or (int)BuiltInCategory.OST_StructuralFoundation or (int)BuiltInCategory.OST_SpecialityEquipment) + && !PlacedSiteElement(element)) continue; + if (element.CategoryId == (int)BuiltInCategory.OST_Viewports) continue; + if (element.IsDiscovered && element.CategoryId is (int)BuiltInCategory.OST_Materials + or (int)BuiltInCategory.OST_Constraints or (int)BuiltInCategory.OST_CLines + or (int)BuiltInCategory.OST_LightingFixtureSource) continue; + bool siteCategory = element.CategoryId is (int)BuiltInCategory.OST_Planting + or (int)BuiltInCategory.OST_Topography or (int)BuiltInCategory.OST_Site or (int)BuiltInCategory.OST_Entourage; + bool outlineSiteObject = siteSilhouettes != null + && element.CategoryId == (int)BuiltInCategory.OST_Site + && element.RootClassIs("FamilyInstance"); + if (siteSilhouettes != null && (outlineSiteObject || projectSiteMeshes + && element.CategoryId is ((int)BuiltInCategory.OST_Planting or (int)BuiltInCategory.OST_Entourage))) { + if (PlacedSiteElement(element) && element.Geometry is { Faces.Count: > 0 } placedGeometry) + { + int silhouetteStart = siteSilhouettes.Count; + var siteLight = outlineSiteObject ? null : shadows; + bool planting = element.CategoryId == (int)BuiltInCategory.OST_Planting; + // The RPC insertion point determines whether its proxy casts onto visible geometry. + bool rpcPlant = planting && Math.Abs(D[2]) < 1e-9 + && element.InstanceOriginXY != null + && document.GetElement(element.TypeId)?.LookupParameter(BuiltInParameter.RENDER_RPC_FILENAME) + ?.Value is string { Length: > 0 }; + bool groundOnly = rpcPlant && element.InstanceOriginXY is { } insertion + && (insertion.X * D[0] + insertion.Y * D[1]) * FeetToMillimetres < viewPlaneDepth; + bool outlineBeforePlane = groundOnly && HeaderOutlineIsBeforePlane(element, D, viewPlaneDepth); + bool proxyBeforePlane = groundOnly && placedGeometry.Faces.All(face => + face.OuterVertices is { Count: >= 3 } vertices + && vertices.All(point => Project(point, D) < viewPlaneDepth)); + // The saved RPC extent can intersect the view even when its display panels lie in front of it. + bool retainRpcProxy = proxyBeforePlane && !outlineBeforePlane && element.BoundingBoxIsHeaderOutline + && element.BoundingBox is { Length: 6 } outlineBounds && outlineBounds.All(double.IsFinite); + var tree = planting && plantingOutlines != null && placedGeometry.Faces.All(face => + face.PolygonMesh && face.OuterVertices is { Count: 3 }) + ? new ElevationShadows.PlantingOutlines.Mesh(clipAtViewPlane: !retainRpcProxy) : null; + var wireFaces = element.CategoryId == (int)BuiltInCategory.OST_Entourage + && element.RootClassIs("FamilyInstance") + ? new List<(List Points, double Facing)>() : null; + var billboardPlanes = wireFaces != null ? CrossedBillboardPlanes(placedGeometry.Faces) : null; + bool crossedBillboard = billboardPlanes != null; + bool shadePlant = planting && plantAmbientFraction < 1 && CrossedBillboardPlanes(placedGeometry.Faces) != null; + if (billboardPlanes != null && opaqueSection && drawTerrainCut + && ProjectSectionBillboard(placedGeometry.Faces, billboardPlanes, H, V, D, viewPlaneDepth) + is { } billboard) + { + sectionBillboards.AddRange(billboard.Rings); + siteObjects.Add((billboard.Edges, viewPlaneDepth, true)); + continue; + } + double objectNear = double.PositiveInfinity; + foreach (var face in placedGeometry.Faces) + { + if (face.OuterVertices is not { Count: >= 3 } vertices) continue; + var world = vertices.Select(point => new[] { point[0] * FeetToMillimetres, + point[1] * FeetToMillimetres, point[2] * FeetToMillimetres }).ToList(); + if (wireFaces != null && face.PolygonMesh + && face.RenderStyleId == null && face.NestedRenderStyleId == null) + wireFaces.Add((world, Project(face.Normal, D, 1))); + if (face.PlaneSurface || vertices.Count == 3) + siteLight?.AddCaster(face, world, siteOnly: !planting, planting: planting, + groundOnly: groundOnly, castsOnVisiblePlanting: proxyBeforePlane, castsOnSoilCut: !outlineBeforePlane); + var visible = retainRpcProxy ? world : ClipBehind(world, planeOrigin, D); + var ring = visible.Select(point => (Project(point, H, 1), Project(point, V, 1))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (tree != null) plantingOutlines!.AddFacet(tree, world, ring, face, visible); + if (Math.Abs(area) < 1e-6) continue; + if (area < 0) ring.Reverse(); + siteSilhouettes.Add(ring); + if (plantSun is { } sun && plantAmbientFraction < 1 && vertices.Count == 3 && !face.CurvedSurface + && ElevationShadows.CreateVisibleFacet(H, V, D, ring, face, visible) is { } facet) + { + plantFacets.Add(facet); + if (shadePlant) + { + // The untextured proxy uses both sides of its saved display panels. + double incidence = Math.Abs(face.Normal[0] * sun.X + face.Normal[1] * sun.Y + face.Normal[2] * sun.Z); + double linear = Math.Min(1, plantAmbientFraction + (1 - plantAmbientFraction) * incidence); + double gray = linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.Pow(linear, 1 / 2.4) - 0.055; + plantTones.Add(facet, (byte)Math.Round(255 * gray)); + } + } + if (planting) plantMasks.Add((ring, visible.Max(point => Project(point, D, 1)))); + else if (shadows != null || plantingOutlines != null) + { + double siteDepth = visible.Average(point => Project(point, D, 1)); + shadows?.AddModelOccluder(ring, face.Normal, visible[0], siteDepth, null); + plantingOutlines?.AddModelOccluder(ring, face.Normal, visible[0], siteDepth, null); + } + if (outlineSiteObject) objectNear = Math.Min(objectNear, visible.Min(point => Project(point, D, 1))); + if (vertices.Count == 3 && !face.CurvedSurface) + siteLight?.AddVisibleFacet(ring, face, visible, planting, crossedBillboard, + receivesOffscreenPlantShadows: rpcPlant && !groundOnly); + } + if (tree != null) plantingOutlines!.AddTree(tree); + if (outlineSiteObject && siteSilhouettes.Count > silhouetteStart) + { + var outlines = OutlineJoinedRings(siteSilhouettes.Skip(silhouetteStart).ToList(), element.CategoryId!.Value); + siteObjects.Add((outlines.ToList(), objectNear, false)); + } + if (wireFaces is { Count: > 0 }) + { + double near = wireFaces.Min(face => face.Points.Min(point => Project(point, D, 1))); + bool cutMesh = cut && near < viewPlaneDepth; + bool wholeMesh = !cutMesh && wireFaces.Count == placedGeometry.Faces.Count; + bool outlineBillboard = wholeMesh && crossedBillboard; + const int entourageCategory = (int)BuiltInCategory.OST_Entourage; + var entourageEdges = outlineBillboard + ? OutlineJoinedRings(siteSilhouettes.Skip(silhouetteStart).ToList(), + entourageCategory, coverOppositeEdges: true) + : SiteWireEdges(wireFaces, H, V, D, viewPlaneDepth, cutMesh); + // A one-sided mesh can project a silhouette when its facets face away or are edge-on. + if (!outlineBillboard && wholeMesh && wireFaces.All(face => face.Facing >= -1e-6)) + entourageEdges = entourageEdges.Concat(OutlineJoinedRings( + siteSilhouettes.Skip(silhouetteStart).ToList(), entourageCategory)); + siteObjects.Add((entourageEdges.ToList(), Math.Max(near, viewPlaneDepth), true)); + } + } + continue; + } + if (siteCategory) + { + if (clipSiteContext && !PlacedSiteElement(element)) continue; if (element.Geometry is { Faces.Count: > 0 } siteGeometry) { foreach (var siteFace in siteGeometry.Faces) { if (siteFace.OuterVertices is not { Count: >= 3 } siteVertices) continue; - var sitePoints = new List<(double X, double Y)>(siteVertices.Count); - double siteDepth = 0; - foreach (var vertex in siteVertices) + var world = siteVertices.Select(point => new[] { point[0] * FeetToMillimetres, + point[1] * FeetToMillimetres, point[2] * FeetToMillimetres }).ToList(); + bool upwardTerrain = element.CategoryId == (int)BuiltInCategory.OST_Topography + && siteFace.Normal[2] > 0; + if (drawGround && upwardTerrain) { - double x = vertex[0] * FeetToMillimetres, y = vertex[1] * FeetToMillimetres; - double z = vertex[2] * FeetToMillimetres; - sitePoints.Add((x * H[0] + y * H[1] + z * H[2], - x * V[0] + y * V[1] + z * V[2])); - siteDepth += x * D[0] + y * D[1] + z * D[2]; + foreach (var (a, b) in CutChords(world, planeOrigin, D)) + terrainEdges.Add(new CollectedEdge(Project(a, H, 1), Project(a, V, 1), + Project(b, H, 1), Project(b, V, 1), + 0, 0, -1, -1, 0, 0, 0, 0, true, (int)BuiltInCategory.OST_Topography)); } - // The mesh of the ground is tessellated into tens of thousands of triangles: only the larger - // ones shade the background, which keeps the page light. + bool planarTerrain = upwardTerrain && (siteFace.PlaneSurface || siteVertices.Count == 3); + bool placedSectionTerrain = planarTerrain && sectionTerrainCrop != null && PlacedSiteElement(element); + bool clipTerrain = placedSectionTerrain || upwardTerrain && drawTerrainCut && skyGradient?.Ground != null; + var visible = clipSiteContext || clipTerrain + ? ClipBehind(world, planeOrigin, D) : world; + if (visible.Count < 3) continue; + if (regularFineSection && planarTerrain && ambient != null + && (siteFace.InnerLoops is not { Count: > 0 } || siteFace.InnerVertices is { Count: > 0 })) + ambient.AddOccluder(visible.Select(point => AmbientVector(point, 1)).ToList(), + AmbientVector(siteFace.Normal, 1), siteFace.InnerVertices?.Select(ring => + ring.Select(point => AmbientVector(point, FeetToMillimetres)).ToList()).ToList()); + var sitePoints = visible.Select(point => (X: Project(point, H, 1), Y: Project(point, V, 1))).ToList(); double siteArea = 0; for (int i = 0; i < sitePoints.Count; i++) { @@ -215,17 +611,240 @@ internal sealed record ElevationContent( var b = sitePoints[(i + 1) % sitePoints.Count]; siteArea += a.X * b.Y - b.X * a.Y; } - if (Math.Abs(siteArea) / 2 < 500_000 || context.Count >= 3000) continue; - context.Add((sitePoints, siteDepth / siteVertices.Count)); + bool terrainFacet = placedSectionTerrain || planarTerrain && shadowTerrainCrop != null; + if (terrainFacet && terrainFillCrop is { } terrainBounds) + { + if (Math.Abs(siteArea) < 1e-6 || sitePoints.All(p => p.X < terrainBounds.X0) + || sitePoints.All(p => p.X > terrainBounds.X1) || sitePoints.All(p => p.Y < terrainBounds.Y0) + || sitePoints.All(p => p.Y > terrainBounds.Y1)) continue; + } + // Keep the size cutoff for other site context. + else if (Math.Abs(siteArea) / 2 < 500_000 || context.Count >= 3000) continue; + if (placedSectionTerrain) + sectionTerrain!.AddSurface(sitePoints, siteFace, visible); + context.Add((sitePoints, visible.Average(point => Project(point, D, 1)), + element.CategoryId == (int)BuiltInCategory.OST_Topography)); + if (planarTerrain) + shadows?.AddTerrainReceiver(sitePoints, siteFace, visible, PlacedSiteElement(element)); } } continue; } if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; + List>? curtainOpenings = null; + if (element.CategoryId == (int)BuiltInCategory.OST_Walls + && element.SerializedCurtainPanelOrder is { Length: > 0 } panelOrder + && document.GetElement(element.TypeId)?.RootClassIs("NewCurtainWallType") == true) + { + var panels = panelOrder.Select(document.GetElement).OfType().Where(panel => panel is + { IsDiscovered: false, Geometry: { } panelGeometry } + && panel.SerializedHostId == element.Id && panel.NativeIsSymbol != true + && panel.SerializedUnplacedOwnerId is not > 0 + && panelGeometry.Faces.Any(face => !face.CurvedSurface && face.OuterVertices is { Count: >= 3 })).ToList(); + // A fully decoded curtain assembly prints its own panels and mullions. + if (panels.Count == panelOrder.Length) continue; + if (fineSection && showSurfacePatterns && window == null) + { + curtainOpenings = []; + foreach (var panel in panels.Distinct().Where(panel => panel.CategoryId == (int)BuiltInCategory.OST_CurtainWallPanels)) + { + var fronts = panel.Geometry!.Faces.Where(face => face.PlaneSurface && !face.CurvedSurface + && Project(face.Normal, D, 1) < -1 + 1e-9 + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && face.OuterVertices is { Count: 4 } ring + && ring.All(point => point.Length == 3 && point.All(double.IsFinite) + && Project(point, D) >= viewPlaneDepth - 1e-6) + && HasGlazingPattern(face)).Take(2).ToArray(); + if (fronts is [{ OuterVertices: { } vertices }]) + { + var opening = ProjectRing(vertices); + if (IsProjectedRectangle(opening) && !curtainOpenings.Any(other => RectanglesOverlap(opening, other))) + curtainOpenings.Add(opening); + } + } + } + } // A stair section draws the stair, not the building around it. if (stairsOnly && !StairCategories.Contains(element.CategoryId ?? -1)) continue; - foreach (var face in geometry.Faces) + int categoryId = element.CategoryId ?? 0; + bool fineEquipmentMesh = regularFineSection && categoryId == (int)BuiltInCategory.OST_SpecialityEquipment + && element.RootClassIs("FamilyInstance"); + bool fineFurnitureMesh = calloutFurnitureMeshes && categoryId == (int)BuiltInCategory.OST_Furniture + && element.RootClassIs("FamilyInstance"); + var meshSilhouette = PlacedSiteElement(element) && (fineEquipmentMesh || fineFurnitureMesh + || opaqueSection && drawTerrainCut && categoryId == (int)BuiltInCategory.OST_GenericModel) + ? ProjectSectionMeshSilhouette(geometry, H, V, D, viewPlaneDepth, element.Id, categoryId, + multipleRevolvedNodes: fineEquipmentMesh, cylindricalFurniture: fineFurnitureMesh) + : null; + if (meshSilhouette != null) meshSilhouettes.AddRange(meshSilhouette); + bool castColumnShadow = shadows != null && categoryId == (int)BuiltInCategory.OST_StructuralColumns + && PlacedSiteElement(element); + bool shadeDoorFinish = keepDoorDepths && ambient != null && categoryId == (int)BuiltInCategory.OST_Doors + && !element.IsDiscovered && element.NativeIsSymbol != true && element.SerializedUnplacedOwnerId is not > 0 + && !geometry.Faces.Any(face => document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is > 0 and <= 1); + bool physicalOccluder = ambient != null && !element.IsDiscovered && element.NativeIsSymbol != true + && element.SerializedUnplacedOwnerId is not > 0 + && categoryId != (int)BuiltInCategory.OST_LightingFixtureSource + && !(categoryId == (int)BuiltInCategory.OST_Walls + && document.GetElement(element.TypeId)?.RootClassIs("NewCurtainWallType") == true); + bool screenPane = screenPaneOwners != null && PlacedSiteElement(element) + && categoryId == (int)BuiltInCategory.OST_CurtainWallPanels + && geometry.Faces.All(face => document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is > 0 and <= 1); + bool shadeStructuralSlab = regularFineSection && physicalOccluder && categoryId == (int)BuiltInCategory.OST_Floors + && element.LookupParameter(BuiltInParameter.FLOOR_PARAM_IS_STRUCTURAL)?.Value is 1 + && element.LookupParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM)?.Value is > 0 and int slabMaterial + && document.GetElement(slabMaterial) is { HasShadingAppearance: true, + SerializedMaterialUsesRenderAppearance: false, SerializedMaterialTransparency: 0 }; + var wallType = opaqueFineSection && !detailPath && physicalOccluder + && categoryId == (int)BuiltInCategory.OST_Walls + ? document.GetElement(element.TypeId) : null; + var wallFaceLayers = detailCallout ? wallType?.SerializedHostTypeLayers : null; + int? interiorFinish = regularFineSection && wallType?.SerializedBasicWallTypeFunction == 1 + && element.LookupParameter(BuiltInParameter.WALL_TOP_IS_ATTACHED)?.Value is 0 + && wallType.SerializedHostTypeLayers is { Length: > 1 } layers + && layers[^1] is { RawFunction: 4 or 5, RawMaterialId: > 0 and int finishId } + ? finishId : null; + int? structuralWallMaterial = regularFineSection + && wallType is { SerializedBasicWallTypeFunction: 1, + SerializedHostTypeLayers: [{ RawFunction: 1, RawMaterialId: > 0 and int structuralLayer }] } + && element.LookupParameter(BuiltInParameter.WALL_STRUCTURAL_SIGNIFICANT)?.Value is 1 + && element.LookupParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM)?.Value is int wallStructuralId + && wallStructuralId == structuralLayer + && document.GetElement(wallStructuralId) is { HasShadingAppearance: true, SerializedMaterialTransparency: 0 } + ? wallStructuralId : null; + double? structuralWallBaseY = structuralWallMaterial.HasValue && Math.Abs(V[2] - 1) < 1e-9 + && element.LookupParameter(BuiltInParameter.WALL_BASE_CONSTRAINT)?.Value is > 0 and int baseLevelId + && document.GetElement(baseLevelId)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double baseElevation + && double.IsFinite(baseElevation) + ? baseElevation * FeetToMillimetres : null; + int? exposedWallFinish = regularFineSection && wallType?.SerializedBasicWallTypeFunction == 1 + && element.LookupParameter(BuiltInParameter.WALL_TOP_IS_ATTACHED)?.Value is 1 + && wallType.SerializedHostTypeLayers is { Length: > 1 } exteriorLayers + && exteriorLayers[0] is { RawFunction: 4 or 5, RawMaterialId: > 0 and int exteriorMaterial } + && !exteriorLayers.Skip(1).Any(layer => layer.RawMaterialId == exteriorMaterial) + ? exteriorMaterial : null; + int? wallMaterial = paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls + && geometry.Faces[0].RenderStyleId is > 0 and int material + && geometry.Faces.All(face => face.RenderStyleId == material) ? material : null; + if (drawGround && categoryId == (int)BuiltInCategory.OST_BuildingPad) + { + foreach (var padFace in geometry.Faces) + { + // shortcut: leave pads with inner loops alone until their islands are cut as well. + if (padFace.Normal[2] <= 0 || padFace.OuterVertices is not { Count: >= 3 } padVertices + || padFace.InnerVertices is { Count: > 0 }) continue; + var ring = padVertices.Select(v => new[] + { + v[0] * FeetToMillimetres, v[1] * FeetToMillimetres, v[2] * FeetToMillimetres, + }).ToList(); + foreach (var (a, b) in CutChords(ring, planeOrigin, D)) + { + double x0 = a[0] * H[0] + a[1] * H[1] + a[2] * H[2]; + double x1 = b[0] * H[0] + b[1] * H[1] + b[2] * H[2]; + terrainPads.Add((Math.Min(x0, x1), Math.Max(x0, x1))); + padProfile.Add(new CollectedEdge(x0, a[0] * V[0] + a[1] * V[1] + a[2] * V[2], + x1, b[0] * V[0] + b[1] * V[1] + b[2] * V[2], + 0, 0, -1, -1, 0, 0, 0, 0, true, categoryId)); + } + } + } + var roofStack = roofSectionCrop != null && categoryId == (int)BuiltInCategory.OST_Roofs + ? document.GetElement(element.TypeId)?.SerializedHostTypeLayers : null; + bool layeredRoofCut = roofStack is { Length: > 1 }; + List>? wallCutRings = null; + List>? roofCutRings = null; + if ((layeredRoofCut || drawGround && categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors + or (int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_StructuralFoundation)) + && element.BoundingBox is { Length: 6 } bounds + && Enumerable.Range(0, 3).Sum(i => bounds[D[i] < 0 ? i + 3 : i] * D[i]) * FeetToMillimetres < viewPlaneDepth + && Enumerable.Range(0, 3).Sum(i => bounds[D[i] < 0 ? i : i + 3] * D[i]) * FeetToMillimetres > viewPlaneDepth) + { + var rings = layeredRoofCut ? [] : ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V).ToList(); + if (rings.Count == 0 && (layeredRoofCut || paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls)) + rings = ClosedSectionWithOpenings(geometry.Faces, planeOrigin, D, H, V) ?? rings; + if (wallMaterial is int materialId && rings is [var wallRing]) + wallCutRegions.Add((element.Id, materialId, wallRing)); + if (rings.Count > 0) + { + if (layeredRoofCut) roofCutRings = rings; + if (paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls && !HasNestedSectionRings(rings)) + wallCutRings = rings; + if (sectionTerrainCrop.HasValue && viewDetail == 3 && categoryId == (int)BuiltInCategory.OST_Floors + && layerHatches != null && planeView?.ViewOrigin is { Length: 3 } floorViewOrigin + && !HasNestedSectionRings(rings)) + foreach (var ring in rings) + DetailAnnotations.AddClosedHostCutHatches(layerHatches, document, element, ring, H, V, + floorViewOrigin, layerBoundaries, penWidth: 0.1); + bool needsClosedCap = regularFineSection && categoryId == (int)BuiltInCategory.OST_Walls + || opaqueFineSection && detailCallout && categoryId == (int)BuiltInCategory.OST_Floors; + if (needsClosedCap + && geometry.BrepSolids is [{ IsClosed: true }] && rings.Count == 1 + && ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V, requireClosed: true) + .ToList() is [var cap]) + modelSectionMasks?.Add(cap); + } + if (paintDetailCuts && rings.Count > 0 && !HasNestedSectionRings(rings)) + { + if (categoryId == (int)BuiltInCategory.OST_Roofs) detailRoofCuts!.AddRange(rings); + if (categoryId == (int)BuiltInCategory.OST_Walls) detailWallCuts!.AddRange(rings); + } + foreach (var ring in rings) + { + if (!layeredRoofCut || paintDetailCuts) terrainSectionMasks.Add(ring); + if (regularFineSection && categoryId is (int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_Floors) + modelSectionMasks?.Add(ring); + if (cut) continue; + if (layerHatches != null && planeView?.ViewOrigin is { Length: 3 } cutViewOrigin) + DetailAnnotations.AddClosedHostCutHatches(layerHatches, document, element, ring, H, V, cutViewOrigin); + for (int i = 0; i < ring.Count; i++) + { + var (ax, ay) = ring[i]; + var (bx, by) = ring[(i + 1) % ring.Count]; + elevationCutEdges.Add(new(ax, ay, bx, by, viewPlaneDepth, viewPlaneDepth, + -1, -1, 0, 0, 0, 0, true, categoryId)); + } + } + } + bool isRoof = element.CategoryId == (int)BuiltInCategory.OST_Roofs; + bool fineFixture = fineSection && categoryId == (int)BuiltInCategory.OST_LightingFixtures + && !element.IsDiscovered; + bool groupedEquipment = !cut && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_ElectricalEquipment + && element.SerializedGroupId is > 0 && !element.IsGroupTemplate && !element.IsDiscovered + && element.RootClassIs("FamilyInstance"); + bool reachesViewPlane = (towardViewer != null || groupedEquipment) && geometry.Faces.Any(face => + face.OuterVertices?.Any(vertex => Project(vertex, D) >= viewPlaneDepth) == true); + bool visibleEquipment = groupedEquipment && reachesViewPlane; + bool preciseGroupDepth = visibleEquipment || !cut && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_IOSModelGroups; + List<(int Index, GeoFace Face)>? roofLayers = showSurfacePatterns && isRoof + && geometry.BrepSolids is [{ IsClosed: true } shell] && shell.FaceIndices.Count == geometry.Faces.Count + && geometry.Faces.Any(face => face.ModelPattern != null) ? [] : null; + // shortcut: a single prismatic top rail, until segmented native profiles are supported. + bool straightTopRail = fineSection && window == null && element.RootClassName == "TopRail" && geometry.Faces.Count == 6 + && geometry.Faces.All(face => face.PlaneSurface && face.OuterVertices is { Count: 4 } + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }); + int firstChord = rawChords.Count; + int firstFace = faces.Count; + bool isInsert = categoryId is (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + int? hostId = isInsert + && element.SerializedHostId is > 0 ? element.SerializedHostId : null; + int? roofHostId = hostId is int host + && document.GetElement(host)?.CategoryId == (int)BuiltInCategory.OST_Roofs ? host : null; + bool roofInsert = roofHostId.HasValue && (fineSection || !cut && HasEdgeOnRoofGlazing(geometry.Faces)); + bool projectRoundShafts = showSurfacePatterns && PlacedSiteElement(element) + && (regularOpaqueSection && categoryId == (int)BuiltInCategory.OST_StructuralColumns + || roundElevationShafts && categoryId == (int)BuiltInCategory.OST_GenericModel); + bool shadeStair = ambient != null && IsStairBodyCategory(categoryId); + var outwardStairFaces = shadeStair ? OutwardConvexStairFaces(geometry) : null; + bool stairIntersectsCut = shadeStair && SpansSectionPlane(geometry.Faces, D, viewPlaneDepth); + foreach (var (face, projectedSilhouette) in SectionFaces(document, element, geometry, + fineSection || cut && drawTerrainCut, H, V, D, planeOrigin, projectRoundShafts, + maxElevationTubeDiameter, elevationTubeEdges)) { + bool roundShaft = projectRoundShafts && projectedSilhouette; if (face.OuterVertices is not { Count: >= 3 } vertices) continue; if (face.CurvedSurface) continue; var corners = new List(vertices.Count); @@ -233,6 +852,35 @@ internal sealed record ElevationContent( corners.Add([vertex[0] * FeetToMillimetres, vertex[1] * FeetToMillimetres, vertex[2] * FeetToMillimetres]); double facing = Math.Abs(face.Normal[0] * D[0] + face.Normal[1] * D[1] + face.Normal[2] * D[2]); + var paneMaterial = detailGlass != null && face.PlaneSurface && facing > 1 - 1e-9 + && categoryId is ((int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_Windows + or (int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Mass + or (int)BuiltInCategory.OST_MassForm) + ? document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + : null; + (double Gray, double Transmission)? paneStyle = paneMaterial is { HasShadingAppearance: true, + SerializedMaterialTransparency: > 0 and <= 1 and double transmission } + && paneMaterial.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is >= 0 and <= 0xffffff and int color + ? (((color & 255) * 0.2126 + ((color >> 8) & 255) * 0.7152 + (color >> 16) * 0.0722) / 255, transmission) + : null; + bool seeThrough = (preciseGroupDepth || groupedEquipment || roofInsert) + && (face.RenderStyleId ?? face.NestedRenderStyleId) is int faceMaterialId + && document.GetElement(faceMaterialId)?.SerializedMaterialTransparency is > 0; + if (shadows != null && face.PlaneSurface && (categoryId is ((int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Stairs) + || IsRailingCategory(categoryId) && PlacedSiteElement(element) + || castColumnShadow && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0)) + shadows.AddCaster(face, corners, verifiedOpaque: + document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) is + { HasShadingAppearance: true, SerializedMaterialUsesRenderAppearance: false, + SerializedMaterialTransparency: 0 }); + if (!cut && shadows != null && roofHostId is int roof && face.PlaneSurface + && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0) + shadows.AddCaster(face, corners, roofId: roof); + if (groupedEquipment && face.PlaneSurface && !seeThrough) shadows?.AddCaster(face, corners, siteOnly: true); // The chords come from the unclipped ring: clipping moves or drops the plane crossings, and a // window-clipped polygon loses the vertex correspondence entirely. They are projected and kept // below, next to the face they were carved from. @@ -267,22 +915,47 @@ internal sealed record ElevationContent( double nl = Math.Sqrt(face.Normal[0] * face.Normal[0] + face.Normal[1] * face.Normal[1] + face.Normal[2] * face.Normal[2]); double nnx = 0, nny = 0, nnz = 0; if (nl > 1e-12) { nnx = face.Normal[0] / nl; nny = face.Normal[1] / nl; nnz = face.Normal[2] / nl; } + if (wallMaterial is int chordMaterial) + wallChordSources.Add(rawChords.Count, (element.Id, chordMaterial)); rawChords.Add((ax, ay, bx, by, nnx, nny, nnz, element.TypeId, element.CategoryId ?? 0, planeDepth)); minX = Math.Min(minX, Math.Min(ax, bx)); maxX = Math.Max(maxX, Math.Max(ax, bx)); minY = Math.Min(minY, Math.Min(ay, by)); maxY = Math.Max(maxY, Math.Max(ay, by)); } } - if (cut && planeOrigin.Length == 3) + if (towardViewer != null && reachesViewPlane && corners.Any(point => Project(point, D, 1) < viewPlaneDepth)) + { + var foreground = ClipBehind(corners, planeOrigin, towardViewer); + var mask = foreground.Select(point => (X: Project(point, H, 1), Y: Project(point, V, 1))).ToList(); + if (mask.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(mask)) >= 2000) terrainForeground.Add(mask); + } + if ((cut || visibleEquipment || drawTerrainCut) && planeOrigin.Length == 3) { corners = ClipBehind(corners, planeOrigin, D); if (corners.Count < 3) continue; } + bool ambientBlocker = physicalOccluder && !roundShaft + && (face.PlaneSurface || regularFineSection && corners.All(corner => + Math.Abs(Project(corner, face.Normal, 1) - Project(corners[0], face.Normal, 1)) < 1e-6)) + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }) + && ((face.RenderStyleId ?? face.NestedRenderStyleId) is not (> 0 and int ambientMaterial) + || document.GetElement(ambientMaterial)?.SerializedMaterialTransparency is not > 0); + System.Numerics.Vector3 ambientNormal = default, ambientOrigin = default; + if (ambientBlocker) + { + ambientNormal = AmbientVector(face.Normal, 1); + ambientOrigin = AmbientVector(corners[0], 1); + ambient!.AddOccluder(corners.Select(point => AmbientVector(point, 1)).ToList(), ambientNormal, + face.InnerVertices?.Select(ring => ring.Select(point => AmbientVector(point, FeetToMillimetres)).ToList()).ToList(), + frontFaceOnly: outwardStairFaces?.Contains(face) == true, roofId: isRoof ? element.Id : 0); + } var points = new List<(double X, double Y)>(corners.Count); double depth = 0, minDepth = double.PositiveInfinity; foreach (var corner in corners) points.Add((corner[0] * H[0] + corner[1] * H[1] + corner[2] * H[2], corner[0] * V[0] + corner[1] * V[1] + corner[2] * V[2])); + var railBoundary = straightTopRail && Math.Abs(facing - 1) < 1e-9 ? points : null; + bool[]? incomingEdges = null; if (window is { } detail && cut && planeOrigin.Length == 3) { // A detail section shows the part of the cut around the point of its plane, at the height its kind @@ -306,7 +979,7 @@ internal sealed record ElevationContent( // The clip runs on the 3D ring and projects afterwards: clipping the projected points alone // broke the one-to-one correspondence with the ring, and `isCut` (which reads the ring) was // never computed, so every detail view lost its cut profile. - corners = ClipToWindow3(corners, H, V, cropRect.X0, cropRect.X1, cropRect.Y0, cropRect.Y1); + (corners, incomingEdges) = ClipToWindow3(corners, H, V, cropRect.X0, cropRect.X1, cropRect.Y0, cropRect.Y1); if (corners.Count < 3) continue; points = corners.Select(corner => ( corner[0] * H[0] + corner[1] * H[1] + corner[2] * H[2], @@ -325,32 +998,394 @@ internal sealed record ElevationContent( var b = points[(i + 1) % points.Count]; projected += a.X * b.Y - b.X * a.Y; } - if (Math.Abs(projected) / 2 < 2000) continue; + bool fineFace = visibleEquipment && face.PlaneSurface + || fineFixture && facing > 0.5 && (face.PlaneSurface + || corners.All(corner => Math.Abs(Project(corner, face.Normal, 1) + - Project(corners[0], face.Normal, 1)) < 1e-6)); + if (Math.Abs(projected) < (projectedSilhouette || fineFace ? 1e-6 : 4000)) continue; depth /= corners.Count; foreach (var (x, y) in points) { minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); } - bool outline = facing > 0.5; + if ((roundShaft || drawTerrainCut && showSurfacePatterns && categoryId == (int)BuiltInCategory.OST_Walls) + && face.PlaneSurface && Project(face.Normal, D, 1) < 0 + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.RenderStyleId is int surfaceMaterialId + && document.RawData.MaterialPatterns?.TryGetValue(surfaceMaterialId, out var surfaceMaterial) == true + && surfaceMaterial.SurfacePatternColor == 0 + && document.RawData.FillPatterns?.TryGetValue(surfaceMaterial.SurfacePatternId, out var surfacePattern) == true + && surfacePattern.Grids.Count > 0 + && surfacePattern.Grids.All(grid => grid is { Target: 0, Orientation: 0, Segments.Length: > 0 })) + dashedSurfacePatterns.Add(points, surfacePattern.Grids); + bool outline = facing > 0.5 || fineFace || dashedSurfacePatterns.ContainsKey(points); + if (roundShaft) roundShaftFaces.Add(faces.Count); faces.Add((points, depth, outline)); - faceMinDepths.Add(minDepth); + bool projectedSlabSide = shadeStructuralSlab && face.PlaneSurface && facing > 0.5 + && Math.Abs(face.Normal[2]) <= 1e-6; + double? sideGray = null; + if (structuralWallBaseY is double baseY && ambientBlocker + && face.RenderStyleId == structuralWallMaterial && Project(face.Normal, D, 1) < -1 + 1e-9 + && minDepth > viewPlaneDepth && points.Any(point => point.Y > baseY) + && document.RawData.ViewAmbientLight?.TryGetValue(planeView!.Id, out double wallLight) == true) + exteriorWallTones.Add(points, (baseY, wallLight)); + if (wallFaceLayers != null && face.PlaneSurface && outline && Math.Abs(facing - 1) < 1e-9 + && face.RenderStyleId is > 0 and int wallFaceFinish + && wallFaceLayers.Any(layer => layer.RawFunction is 4 or 5 && layer.RawMaterialId == wallFaceFinish) + && document.GetElement(wallFaceFinish) is { HasShadingAppearance: true, + SerializedMaterialUsesRenderAppearance: false, SerializedMaterialTransparency: 0 } wallFinish + && wallFinish.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int wallColour + and >= 0 and <= 0xffffff) + sideGray = (0.2126 * (wallColour & 255) + 0.7152 * ((wallColour >> 8) & 255) + + 0.0722 * ((wallColour >> 16) & 255)) / 255; + if (regularFineSection && fineFixture && ambientBlocker && face.PlaneSurface && outline + && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) is + { HasShadingAppearance: true, SerializedMaterialUsesRenderAppearance: false, + SerializedMaterialTransparency: 0 } fixtureFinish + && fixtureFinish.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int fixtureColour + and >= 0 and <= 0xffffff) + sideGray = (0.2126 * (fixtureColour & 255) + 0.7152 * ((fixtureColour >> 8) & 255) + + 0.0722 * ((fixtureColour >> 16) & 255)) / 255; + if (sideGray.HasValue) faceFills.Add(points, sideGray); + if (paneStyle is { } pane) + { + double opacity = Project(face.Normal, D, 1) < 0 ? 1 - pane.Transmission : 0; + detailGlass!.Add(points, (pane.Gray, opacity)); + } + if ((visibleEquipment || roundShaft && regularFineSection || shadeDoorFinish) && face.PlaneSurface + && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) is { } faceMaterialElement) + { + // shortcut: transparent equipment covers keep their edges until their appearance is composited. + if (seeThrough) faceFills.Add(points, null); + else if (faceMaterialElement.HasShadingAppearance + && (roundShaft || faceMaterialElement.SerializedMaterialUsesRenderAppearance == false) + && (!shadeDoorFinish || faceMaterialElement.SerializedMaterialTransparency == 0) + && faceMaterialElement.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is int colour and >= 0 and <= 0xffffff) + faceFills.Add(points, (0.2126 * (colour & 255) + 0.7152 * ((colour >> 8) & 255) + + 0.0722 * ((colour >> 16) & 255)) / 255); + } + if (fineSection && IsStairBodyCategory(categoryId) && face.PlaneSurface + && Math.Abs(facing - 1) < 1e-9 && Math.Abs(minDepth - depth) < 1e-6 + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + stairMasks.Add(faces.Count - 1, points); + if (fineSection && (IsRailingCategory(categoryId) || categoryId == (int)BuiltInCategory.OST_StairsRailingBaluster) + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + railingMaskDepths.Add(faces.Count - 1, corners.Max(point => Project(point, D, 1))); + if (siteSilhouettes != null) + siteModelMasks.Add((points, minDepth, corners.Max(point => Project(point, D, 1)))); + if (shadows != null && face.PlaneSurface && Math.Abs(facing - 1) < 1e-9) + shadows.AddReceiver(points, face, depth, roundShaft: roundShaft); + else if (!cut && shadows != null && Math.Abs(face.Normal[2]) <= 1e-6 + && Project(face.Normal, D, 1) < -1e-9 + && (categoryId == (int)BuiltInCategory.OST_Walls && face.PlaneSurface + || categoryId == (int)BuiltInCategory.OST_StructuralFoundation && PlacedSiteElement(element) + && face.MeshMarker != 0 && !face.CurvedSurface && corners.All(corner => + Math.Abs(Project(corner, face.Normal, 1) - Project(corners[0], face.Normal, 1)) < 1e-6))) + shadows.AddPlanarModelReceiver(points, face, corners, + meshFacet: categoryId == (int)BuiltInCategory.OST_StructuralFoundation); + else if (!cut && shadows != null && isRoof && face.PlaneSurface + && face.Normal[2] > 1e-9 && Project(face.Normal, D, 1) < -1e-9 + && face.InnerVertices is { Count: > 0 }) + shadows.AddRoofReceiver(points, face, corners, element.Id); + if (face.PlaneSurface) roofLayers?.Add((faces.Count - 1, face)); + bool exteriorDraftingPattern = !cut && showSurfacePatterns && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_Walls && face.PlaneSurface + && minDepth >= viewPlaneDepth - 1e-6 && Project(face.Normal, D, 1) < 0 + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }); + if (outline && (exteriorDraftingPattern || showDraftingPatterns + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + && face.RenderStyleId is int materialId + && document.RawData.MaterialPatterns?.TryGetValue(materialId, out var faceMaterial) == true + && faceMaterial.SurfacePatternColor == 0 + && document.RawData.FillPatterns?.TryGetValue(faceMaterial.SurfacePatternId, out var pattern) == true + && pattern.Grids is [{ Target: 0, Orientation: 0, Segments.Length: 0, Offset: > 0 } grid] + && double.IsFinite(grid.Angle) && double.IsFinite(grid.OriginX) && double.IsFinite(grid.OriginY) + && double.IsFinite(grid.Offset)) + { + int patternCategory = categoryId switch + { + (int)BuiltInCategory.OST_Walls => (int)BuiltInCategory.OST_WallsSurfacePattern, + (int)BuiltInCategory.OST_Floors => (int)BuiltInCategory.OST_FloorsSurfacePattern, + (int)BuiltInCategory.OST_Roofs => (int)BuiltInCategory.OST_RoofsSurfacePattern, + (int)BuiltInCategory.OST_Ceilings => (int)BuiltInCategory.OST_CeilingsSurfacePattern, + _ => 0, + }; + double width = fineSection && drawGround && !detailPath && patternCategory != 0 + && PenWidths.TryGetWidth(document, patternCategory, false, viewportScale ?? viewScale, out double savedWidth) + ? savedWidth : 0.1; + surfacePatterns.Add(points, (grid, width)); + } + if (outline && showSurfacePatterns && face.PlaneSurface + && categoryId == (int)BuiltInCategory.OST_Walls && Project(face.Normal, D, 1) < 0 + && face.SurfaceRegions is { Count: > 0 } + && document.RawData.MaterialPatterns?.GetValueOrDefault(face.RenderStyleId ?? -1).SurfacePatternId is not > 0) + { + foreach (var region in face.SurfaceRegions) + { + if (document.RawData.MaterialPatterns?.GetValueOrDefault(region.MaterialId) is not { SurfacePatternColor: 0 } paint + || document.RawData.FillPatterns?.GetValueOrDefault(paint.SurfacePatternId).Grids + is not [{ Target: 0, Orientation: 0, Segments.Length: 0, Offset: > 0 } paintGrid]) + continue; + var outer = ProjectRing(region.Outer); + if (outer.Count < 3 || Math.Abs(PlanPrinter.SignedArea(outer)) <= 1e-6) continue; + var regionHoles = region.Holes.Select(ProjectRing).Where(ring => ring.Count >= 3).ToList(); + regionHatches ??= []; + if (!regionHatches.TryGetValue(points, out var hatches)) regionHatches.Add(points, hatches = []); + hatches.Add(new(paintGrid, outer, regionHoles)); + } + } + bool glazedFace = outline && Project(face.Normal, D, 1) < 0 + && categoryId is ((int)BuiltInCategory.OST_CurtainWallPanels or + (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors) + && HasGlazingPattern(face); + glazing?.Add(document, points, minDepth, corners.Max(point => Project(point, D, 1)), + face.RenderStyleId ?? face.NestedRenderStyleId, glazedFace, + coversBacking: regularFineSection && categoryId == (int)BuiltInCategory.OST_CurtainWallPanels); + if (screenPane && face.PlaneSurface && Math.Abs(facing - 1) < 1e-9 && glazing?.IsPane(points) == true) + screenPaneOwners!.Add(element.Id); + if (showSurfacePatterns && (isRoof || glazedFace) && window == null && planeOrigin.Length == 3 + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }) + && face.InnerVertices?.All(hole => hole.Count >= 3 + && hole.All(point => point.Length == 3 && point.All(double.IsFinite))) != false) + { + (double X, double Y) InView(double[] p) => (Project(p, H), Project(p, V)); + IReadOnlyList? hatchGrids = isRoof + ? FillHatch.ProjectModelGrid(document, face, InView) is { } modelGrid ? [modelGrid] : null + : FillHatch.ProjectDashedModelGrids(document, face, InView); + if (hatchGrids != null) + modelHatches.Add(points, new ModelHatch(hatchGrids, ProjectOpenings(face).ToList())); + } + bool hasPaintOpenings = face.PlaneSurface && face.InnerVertices is { Count: > 0 } + && (categoryId == (int)BuiltInCategory.OST_Walls || !cut && isInsert); + if (hasPaintOpenings) + { + var openings = ProjectOpenings(face).ToList(); + if (openings.Count > 0) paintOpenings.Add(points, openings); + } + if (curtainOpenings is { Count: > 0 } && face.PlaneSurface && Math.Abs(facing - 1) < 1e-9 + && (face.RenderStyleId ?? face.NestedRenderStyleId) is not > 0 + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && IsProjectedRectangle(points)) + { + // Clear the fallback only over the saved panes, leaving unresolved cells covered. + var openings = curtainOpenings.Where(ring => ring.All(point => + PointInPolygon(point.X, point.Y, points) || DistToPolygon(point.X, point.Y, points) < 1e-6)).ToList(); + if (openings.Count > 0) paintOpenings.Add(points, openings); + } + var faceOpenings = paintOpenings.GetValueOrDefault(points); + if (detailGlass?.GetValueOrDefault(points).Opacity is > 0) + ambient!.AddGlazing(points, faceOpenings, corners.Max(point => Project(point, D, 1))); + if (ambientBlocker && face.PlaneSurface && !glazedFace + && !(shadeDoorFinish && faceFills.ContainsKey(points))) + { + if (screenWallReceivers != null && categoryId == (int)BuiltInCategory.OST_Walls + && sideGray == null && Project(face.Normal, D, 1) < -1 + 1e-9) + screenWallReceivers.Add(points, depth); + bool exposedFinish = exposedWallFinish is int finishMaterial + && face.RenderStyleId == finishMaterial && Math.Abs(facing - 1) < 1e-9; + ambient!.AddReceiver(points, faceOpenings, ambientOrigin, ambientNormal, sideGray ?? 1, + orientDirectLight: paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls, + ignoreStairExitHits: IsStairBodyCategory(categoryId), + // An edge-on blocker has no surface in the projected view. + ignoreEdgeOnHits: (stairIntersectsCut || interiorFinish is int inside + && face.RenderStyleId == inside) && Math.Abs(facing - 1) < 1e-9 + && Math.Abs(face.Normal[2]) <= 1e-6, + distanceFalloff: exposedFinish, + attachedRoofIds: exposedFinish ? element.SerializedWallTopAttachmentTargets : null, + excludeSamplesBehindCut: paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Floors + && Math.Abs(face.Normal[2]) <= 1e-6, + exteriorWall: exteriorWallTones.TryGetValue(points, out var exteriorTone) + ? (exteriorTone.BaseY, (float)viewPlaneDepth) : null, + projectedSlabSide: projectedSlabSide); + } + else if (regularFineSection && face.PlaneSurface && ambient != null + && glazing?.AmbientBackgroundGray(points) is double glazedBackground) + ambient.AddReceiver(points, faceOpenings, AmbientVector(corners[0], 1), AmbientVector(face.Normal, 1), + glazedBackground); + shadows?.AddModelOccluder(points, face.Normal, corners[0], depth, faceOpenings); + plantingOutlines?.AddModelOccluder(points, face.Normal, corners[0], depth, faceOpenings); + if (!cut || categoryId is ((int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_StructuralFoundation)) + terrainOcclusion?.AddTarget(points, face, corners); + faceOpenings ??= (isRoof || preciseGroupDepth) && face.InnerVertices is { Count: > 0 } holes + ? holes.Where(hole => hole.Count >= 3).Select(hole => hole.Select(p => ( + (p[0] * H[0] + p[1] * H[1] + p[2] * H[2]) * FeetToMillimetres, + (p[0] * V[0] + p[1] * V[1] + p[2] * V[2]) * FeetToMillimetres)).ToList()).ToList() + : null; + PlanarOcclusion? occludingPlane = null; + bool verifiedDetailPlane = paintDetailCuts + && (IsStairBodyCategory(categoryId) + || categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors)) + && corners.All(corner => Math.Abs(Project(corner, face.Normal, 1) + - Project(corners[0], face.Normal, 1)) < 1e-6); + bool exactStairProjectionDepth = overviewSection && face.PlaneSurface + && (IsStairBodyCategory(categoryId) || categoryId == (int)BuiltInCategory.OST_Walls); + if (isRoof || verifiedDetailPlane || exactStairProjectionDepth + || face.PlaneSurface && (preciseGroupDepth || hasPaintOpenings || faceOpenings != null || roofInsert)) + { + var normal = face.Normal; + double nd = normal[0] * D[0] + normal[1] * D[1] + normal[2] * D[2]; + if (Math.Abs(nd) > 1e-10) + { + var corner = corners[0]; + occludingPlane = new PlanarOcclusion( + -(normal[0] * H[0] + normal[1] * H[1] + normal[2] * H[2]) / nd, + -(normal[0] * V[0] + normal[1] * V[1] + normal[2] * V[2]) / nd, + (normal[0] * corner[0] + normal[1] * corner[1] + normal[2] * corner[2]) / nd, + faceOpenings, seeThrough, exactStairProjectionDepth); + } + } + faceOccluders.Add((minDepth, element.Id, hostId, categoryId, occludingPlane)); + if (meshCovers != null && face.PlaneSurface && !seeThrough && !glazedFace + && faceOpenings is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.InnerVertices is not { Count: > 0 }) + { + double farDepth = corners.Max(point => Project(point, D, 1)); + meshCovers.Add((points, farDepth, element.Id)); + if (furnitureCovers != null && categoryId == (int)BuiltInCategory.OST_Furniture + && !element.IsDiscovered && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0) + furnitureCovers.Add(faces.Count - 1, farDepth); + } + if (spanOccluders != null && face.PlaneSurface && !element.IsDiscovered + && (face.InnerLoops is not { Count: > 0 } loops || roundElevationShafts + && Math.Max(face.InnerVertices?.Count ?? 0, faceOpenings?.Count ?? 0) >= loops.Count) + && (roundElevationShafts || face.InnerVertices is not { Count: > 0 } && faceOpenings is not { Count: > 0 }) + && ((face.RenderStyleId ?? face.NestedRenderStyleId) is not (> 0 and int spanMaskMaterial) + || document.GetElement(spanMaskMaterial)?.SerializedMaterialTransparency is not > 0)) + { + bool viewAlignedSlabSide = categoryId == (int)BuiltInCategory.OST_Floors + && Math.Abs(face.Normal[2]) < 1e-6 && Project(face.Normal, D, 1) < -1 + 1e-9; + spanOccluders.Add((points, corners.Max(point => Project(point, D, 1)), viewAlignedSlabSide)); + if (spanOpenings != null) + { + var openings = faceOpenings; + if (face.InnerVertices is { Count: > 0 } inner) + openings = [.. openings ?? [], .. inner.Where(ring => ring.Count >= 3) + .Select(ring => ring.Select(p => (Project(p, H), Project(p, V))).ToList())]; + if (openings is { Count: > 0 }) spanOpenings.Add(points, openings); + } + } + if (detailWallOccluders != null && categoryId == (int)BuiltInCategory.OST_Walls && !seeThrough + && Math.Abs(depth - minDepth) < 1e-6 && faceOpenings is not { Count: > 0 } + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 }) + detailWallOccluders.Add((points, minDepth)); if (outline) { + if (roofInsert) roofInsertFaces.Add(faces.Count - 1); + if (sectionTerrainCrop.HasValue && categoryId == (int)BuiltInCategory.OST_Walls + && element.TypeId > 0 && PlacedSiteElement(element) && face.PlaneSurface + && Math.Abs(Project(face.Normal, D, 1) + 1) < 1e-9 + && faceOpenings is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.InnerVertices is not { Count: > 0 } + && (face.RenderStyleId ?? face.NestedRenderStyleId) is > 0 and int wallFaceMaterial + && document.GetElement(wallFaceMaterial)?.SerializedMaterialTransparency is not > 0 + && corners.All(point => Math.Abs(Project(point, D, 1) - minDepth) < 1e-6)) + sectionWallFaces.Add(faces.Count - 1, (element.TypeId, wallFaceMaterial, minDepth)); // The plane of the face for edge sharing: a triangulation diagonal is the edge of two // coplanar faces, a crease or silhouette the edge of two different planes. double nx = face.Normal[0], ny = face.Normal[1], nz = face.Normal[2]; double length = Math.Sqrt(nx * nx + ny * ny + nz * nz); if (length > 1e-12) { nx /= length; ny /= length; nz /= length; } var corner = corners[0]; - edgeFaces.Add((points, corners, depth, + edgeFaces.Add(new ProjectionFace(points, corners, depth, (long)Math.Round(nx * 1000), (long)Math.Round(ny * 1000), (long)Math.Round(nz * 1000), (long)Math.Round((nx * corner[0] + ny * corner[1] + nz * corner[2]) * 2.0), - faces.Count - 1, element.CategoryId ?? 0)); + faces.Count - 1, element.CategoryId ?? 0, incomingEdges)); + if (railBoundary != null) + { + for (int i = 0; i < railBoundary.Count; i++) + { + var (x1, y1) = railBoundary[i]; + var (x2, y2) = railBoundary[(i + 1) % railBoundary.Count]; + if (sectionCrop is { } railCrop && !ClipSegment(x1, y1, x2, y2, + railCrop.X0, railCrop.Y0, railCrop.X1, railCrop.Y1, out x1, out y1, out x2, out y2)) continue; + var key = ProjectedEdgeKey(x1, y1, x2, y2); + if (key.Ax == key.Bx && key.Ay == key.By) continue; + topRailEdges.Add(new CollectedEdge(x1, y1, x2, y2, depth, depth, + faces.Count - 1, -1, 0, 0, 0, 0, false, element.CategoryId ?? 0)); + } + } + } + } + if (opaqueFineSection && !isDetail && layerHatches != null && rawChords.Count > firstChord + && categoryId == (int)BuiltInCategory.OST_Stairs && planeView?.ViewOrigin is { Length: 3 } stairViewOrigin + && (geometry.Faces[0].RenderStyleId ?? geometry.Faces[0].NestedRenderStyleId) is > 0 and int stairMaterial + && geometry.Faces.All(face => (face.RenderStyleId ?? face.NestedRenderStyleId) == stairMaterial + && !face.CurvedSurface && face.OuterVertices is { Count: >= 3 })) + { + var stairCut = ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V, requireClosed: true).ToList(); + if (!HasNestedSectionRings(stairCut)) + { + if (geometry.BrepSolids is { Count: > 0 } stairSolids && stairSolids.All(solid => solid.IsClosed)) + modelSectionMasks?.AddRange(stairCut); + foreach (var ring in stairCut) + DetailAnnotations.AddMaterialCutHatch(layerHatches, document, stairMaterial, ring, H, V, stairViewOrigin); + } + } + if (roofCutRings != null && layerBoundaries != null && roofSectionCrop is { } roofCrop && roofStack != null) + { + int prior = layerBoundaries.Count; + AddRoofLayers(layerBoundaries, rawChords.Skip(firstChord), roofCutRings, roofStack, H, V, D, roofCrop, + document, !isDetail ? layerHatches : null, planeView?.ViewOrigin); + if (layerBoundaries.Count > prior) modelSectionMasks?.AddRange(roofCutRings); + } + if (layerHatches != null && (!cut || sectionCrop != null) && rawChords.Count > firstChord + && planeView?.ViewOrigin is { Length: 3 } viewOrigin) + { + if (!isDetail && opaqueFineSection && categoryId == (int)BuiltInCategory.OST_Walls) + wallCutRings = ClosedSectionWithOpenings(geometry.Faces, planeOrigin, D, H, V); + + int priorBoundaries = layerBoundaries?.Count ?? 0; + DetailAnnotations.AddLayerHatches(layerHatches, document, element, + rawChords.Skip(firstChord).Select(c => (c.X1, c.Y1, c.X2, c.Y2)), H, V, viewOrigin, + paintDetailCuts ? layerBoundaries : null, wallCutRings); + if (layerBoundaries?.Count > priorBoundaries) + for (int i = firstChord; i < rawChords.Count; i++) sectionedLayerChords.Add(i); + } + if (planeOrigin.Length == 3 && firstFace < faces.Count + && isInsert + && !element.IsDiscovered && element.NativeIsSymbol != true && !element.RootClassIs("FamilySymbol") + && element.SerializedUnplacedOwnerId is not > 0 && geometry.ViewFacingLines is { Count: > 0 } lines) + { + foreach (var line in lines) + { + if (Project(line.Axis, D, 1) < 1 - 1e-9 || line.DetailCondition is { } detail + && (viewDetail is not (>= 1 and <= 3) + || !Parsing.GRepParserV2.CompareSerializedInteger(viewDetail.Value, detail.Comparison, detail.Level))) continue; + double startDepth = Project(line.Start, D), endDepth = Project(line.End, D); + if (Math.Min(startDepth, endDepth) < viewPlaneDepth - 1e-6) continue; + double depth = (startDepth + endDepth) / 2; + viewLines.Add(new CollectedEdge(Project(line.Start, H), Project(line.Start, V), + Project(line.End, H), Project(line.End, V), depth, depth, firstFace, -1, 0, 0, 0, 0, + CategoryId: categoryId, NearDepth: Math.Min(startDepth, endDepth)) { ViewLineStyleId = line.StyleId }); } } + if (roofLayers is { Count: > 1 }) + OrderRoofLayerPaint(roofLayers); + } + if (sectionBillboards.Count > 0) + foreach (var (x, y) in sectionBillboards.SelectMany(ring => ring)) + { + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } + if (faces.Count == 0 && rawChords.Count == 0 && sectionBillboards.Count == 0 && elevationTubeEdges.Count == 0) + { + if (towardViewer == null || siteSilhouettes is not { Count: > 0 }) return null; + foreach (var (x, y) in siteSilhouettes.SelectMany(ring => ring)) + { + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } } - if (faces.Count == 0 && rawChords.Count == 0) return null; + if (elevationTubeEdges.Count > 0) + foreach (var edge in elevationTubeEdges) + { + minX = Math.Min(minX, Math.Min(edge.X1, edge.X2)); maxX = Math.Max(maxX, Math.Max(edge.X1, edge.X2)); + minY = Math.Min(minY, Math.Min(edge.Y1, edge.Y2)); maxY = Math.Max(maxY, Math.Max(edge.Y1, edge.Y2)); + } // The chords become inked edges on the cutting plane's own key, so the same line coming from two // solids sharing the cut surface merges into one below. var cutChords = new List(); @@ -362,36 +1397,227 @@ internal sealed record ElevationContent( pnz = (long)Math.Round(D[2] * 1000); poff = (long)Math.Round((planeOrigin[0] * D[0] + planeOrigin[1] * D[1] + planeOrigin[2] * D[2]) * 2.0); } - foreach (var chord in rawChords) - cutChords.Add(new CollectedEdge(chord.X1, chord.Y1, chord.X2, chord.Y2, - chord.Depth, chord.Depth, -1, -1, pnx, pny, pnz, poff, true, chord.CategoryId)); - // Layer boundaries subdivide the cross-section, but only in a detail at a fine scale: a 1:100 section - // draws the coarse single outline the reference draws, while a 1:50/1:20/1:10 detail draws every layer. - bool detailPath = window != null || isDetail || cropWindow != null; - int viewScale = planeView?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is int scaleValue && scaleValue > 0 - ? scaleValue : 100; + for (int i = 0; i < rawChords.Count; i++) + { + var chord = rawChords[i]; + var edge = new CollectedEdge(chord.X1, chord.Y1, chord.X2, chord.Y2, + chord.Depth, chord.Depth, -1, -1, pnx, pny, pnz, poff, true, chord.CategoryId); + if (wallChordSources.TryGetValue(i, out var source) && wallCutRegions.Count > 0) + { + // Only interior spans are hidden. Coincident contours and material changes still ink. + var covers = wallCutRegions.Where(region => region.WallId != source.WallId + && region.MaterialId == source.MaterialId).Select(region => region.Ring); + cutChords.AddRange(VisibleTerrainEdges([edge], covers, [], coverBoundary: false)); + } + else + { + cutChords.Add(edge); + } + } + // Layer boundaries share the exact material bands and keep any spans left by an authored cut edge. + List? roofLayerEdges = null; + if (layerBoundaries is { Count: > 0 }) + { + var sections = new List(cutChords); + foreach (var layer in layerBoundaries.Distinct()) + sections.Add(new(layer.Start.X, layer.Start.Y, layer.End.X, layer.End.Y, + viewPlaneDepth, viewPlaneDepth, -1, -1, pnx, pny, pnz, poff, false, layer.CategoryId)); + var boundaries = TrimProjectedEdgesAtCuts(sections).Where(edge => !edge.IsCut); + if (paintDetailCuts) cutChords.AddRange(boundaries); + else roofLayerEdges = boundaries.ToList(); + } if (detailPath && viewScale <= 50 && rawChords.Count > 0) - AddLayerLines(rawChords, document, cutChords, D, H, V, pnx, pny, pnz, poff); - var deduped = DedupeEdges(edgeFaces, D, cut ? planeOrigin : null); + AddLayerLines(rawChords, document, cutChords, D, H, V, pnx, pny, pnz, poff, sectionedLayerChords); + HashSet<(long Ax, long Ay, long Bx, long By)>? railSeams = fineSection ? [] : null; + // Coincident nosing edges can lie at different depths. Keep the front candidate through occlusion. + bool keepStairDepths = paintDetailCuts || overviewSection; + var deduped = DedupeEdges(edgeFaces, D, cut ? planeOrigin : null, keepComponentDepths: drawTerrainCut, + fineSection: fineSection, keepStairDepths: keepStairDepths, railSeams: railSeams, + keepDoorDepths: keepDoorDepths, keepDetailProfileDepths: paintDetailCuts); + foreach (var shaftIndex in roundShaftFaces) + { + var shaft = faces[shaftIndex]; + // Only the edges behind the full cylinder can be clipped at its whole silhouette. + double far = shaft.Depth + (shaft.Points.Max(p => p.X) - shaft.Points.Min(p => p.X)) / 2; + bool BehindShaft(CollectedEdge edge) => !edge.IsCut && edge.NearDepth is double near + && near > far + 1 && Math.Abs(near - edge.MidDepth) < 1e-6; + if (faceOccluders[shaftIndex].CategoryId == (int)BuiltInCategory.OST_GenericModel) + { + deduped = deduped.SelectMany(edge => BehindShaft(edge) + ? VisibleTerrainEdges([edge], [shaft.Points], [], coverBoundary: false) + : [edge]).ToList(); + continue; + } + var behind = deduped.Where(BehindShaft).ToList(); + deduped.RemoveAll(BehindShaft); + deduped.AddRange(VisibleTerrainEdges(behind, [shaft.Points], [], coverBoundary: false)); + } // The carved chords join the shared-edge pass late on purpose: they are already de-duplicated by // construction (one span per inside interval), and the merge below still unions the same line coming // from two solids sharing the cut surface. deduped.AddRange(cutChords); - var occluded = OccludeEdges(faces, faceMinDepths, deduped); - List edges = MergeOverlaps(occluded); + if (paintDetailCuts) + { + // Coincident constant-depth copies have the same projected endpoints. + // Keep the nearest copy before splitting it around solid covers. + var nearestProfiles = deduped.Where(IsConstantDepthDetailProfile) + .GroupBy(edge => (ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), + IsMullion: edge.CategoryId == (int)BuiltInCategory.OST_CurtainWallMullions)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + deduped.RemoveAll(IsConstantDepthDetailProfile); + deduped.AddRange(nearestProfiles); + } + if (detailWallOccluders is { Count: > 0 }) + { + // Split a horizontal wall edge at nearer opaque faces before testing the remaining midpoints. + deduped = deduped.SelectMany(edge => ClipDetailWallEdge(edge, detailWallOccluders)).ToList(); + } + var calloutWallSpans = new List(); + var clippedCalloutWalls = new HashSet<((long Ax, long Ay, long Bx, long By) Edge, double Depth)>(); + if (spanOccluders is { Count: > 0 }) + { + // A nearer face can cover the midpoint of an edge with visible spans on either side. + var projectedSpans = deduped.Where(NeedsSpanClipping).GroupBy(edge => edge.MidDepth).ToList(); + deduped.RemoveAll(NeedsSpanClipping); + foreach (var group in projectedSpans) + deduped.AddRange(VisibleTerrainEdges(group, + spanOccluders.Where(mask => mask.FarDepth < group.Key - 1).Select(mask => mask.Points), [], + openings: spanOpenings)); + if (opaqueFineSection && !detailPath) + { + var slabs = spanOccluders.Where(mask => mask.ViewAlignedSlabSide).ToList(); + if (slabs.Count > 0) + { + // A projected slab can hide the middle of a wall or railing upright while leaving both ends visible. + var uprights = deduped.Where(IsSlabCoveredProfile).GroupBy(edge => edge.NearDepth!.Value).ToList(); + deduped.RemoveAll(IsSlabCoveredProfile); + foreach (var group in uprights) + deduped.AddRange(VisibleTerrainEdges(group, + slabs.Where(mask => mask.FarDepth < group.Key - 1).Select(mask => mask.Points), [], + coverBoundary: false)); + } + } + if (opaqueFineSection && !regularFineSection) + foreach (var group in deduped.Where(IsSlopingWall).GroupBy(edge => edge.MidDepth)) + { + var masks = spanOccluders.Where(mask => mask.FarDepth < group.Key - 1) + .Select(mask => mask.Points).ToList(); + foreach (var edge in group) + { + var spans = VisibleTerrainEdges([edge], masks, []).ToList(); + var key = ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2); + if (spans is [var span] && key == ProjectedEdgeKey(span.X1, span.Y1, span.X2, span.Y2)) + continue; + clippedCalloutWalls.Add((key, edge.MidDepth)); + calloutWallSpans.AddRange(spans); + } + } + } + bool NeedsSpanClipping(CollectedEdge edge) => + !edge.IsCut && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && (fineSection && edge.CategoryId == (int)BuiltInCategory.OST_LightingFixtures + || roundShaftFaces.Contains(edge.FaceA) || roundShaftFaces.Contains(edge.FaceB) + || regularFineSection && IsSlopingWall(edge) + || paintDetailCuts && IsVerticalDetailProfile(edge.CategoryId, edge.X1, edge.X2)); + + static bool IsSlabCoveredProfile(CollectedEdge edge) => + !edge.IsCut && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && (IsVerticalDetailProfile(edge.CategoryId, edge.X1, edge.X2) + || edge.CategoryId == (int)BuiltInCategory.OST_Walls && Math.Abs(edge.X1 - edge.X2) < 1e-6); + + static bool IsConstantDepthDetailProfile(CollectedEdge edge) => + !edge.IsCut && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && IsVerticalDetailProfile(edge.CategoryId, edge.X1, edge.X2); + + static bool IsSlopingWall(CollectedEdge edge) => + !edge.IsCut && edge.CategoryId == (int)BuiltInCategory.OST_Walls + && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && Math.Abs(edge.X1 - edge.X2) > 1e-6 && Math.Abs(edge.Y1 - edge.Y2) > 1e-6; + + IEnumerable ClipDetailWallEdge(CollectedEdge edge, + List<(List<(double X, double Y)> Points, double Depth)> masks) + { + if (edge.IsCut || edge.CategoryId != (int)BuiltInCategory.OST_Walls + || Math.Abs(edge.Y1 - edge.Y2) >= 1e-6 || edge.NearDepth is not double depth) + return [edge]; + var plane = edge.FaceA >= 0 ? faceOccluders[edge.FaceA].Plane : null; + if (plane == null && Math.Abs(depth - edge.MidDepth) >= 1e-6) + return [edge]; + return VisibleTerrainEdges([edge], masks.Where(face => face.Depth < depth - 1).Select(face => face.Points), []) + .Select(span => plane == null ? span : span with + { + MidDepth = plane.DepthAt((span.X1 + span.X2) / 2, (span.Y1 + span.Y2) / 2), + NearDepth = Math.Min(plane.DepthAt(span.X1, span.Y1), plane.DepthAt(span.X2, span.Y2)), + }); + } + var behindRailings = new List(); + var occluded = OccludeEdges(faces, faceOccluders, deduped, !detailPath && viewScale >= 100, + stairMaskFaces: stairMasks.Count > 0 ? stairMasks : null, + railingMaskDepths: railingMaskDepths.Count > 0 ? railingMaskDepths : null, + behindRailings: behindRailings, useDetailPlaneDepth: detailWallOccluders != null, + stairAssembly: overviewSection ? StairAssembly : null, furnitureCovers: furnitureCovers); + if (keepStairDepths) + { + var stairEdges = occluded.Where(edge => IsStairBodyCategory(edge.CategoryId) && !edge.IsCut) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + occluded.RemoveAll(edge => IsStairBodyCategory(edge.CategoryId) && !edge.IsCut); + occluded.AddRange(stairEdges); + } + if (viewLines.Count > 0) + viewLines = OccludeEdges(faces, faceOccluders, viewLines, keepWindowJambs: false, + furnitureCovers: furnitureCovers); + if (drawTerrainCut) + { + var visibleComponentEdges = occluded.Where(edge => HasCoincidentComponents(edge.CategoryId, !cut)) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + occluded.RemoveAll(edge => HasCoincidentComponents(edge.CategoryId, !cut)); + foreach (var group in visibleComponentEdges.GroupBy(edge => edge.NearDepth)) + occluded.AddRange(group.Key is double depth + ? VisibleTerrainEdges(group, plantMasks.Where(mask => mask.Far < depth).Select(mask => mask.Points), []) + : group); + } + if (stairMasks.Count > 0) + { + // Trim visible edges that continue behind the stair. + occluded = occluded.SelectMany(ClipAtStairs).ToList(); + } + IEnumerable ClipAtStairs(CollectedEdge edge) => + stairMasks.Count > 0 && !edge.IsCut && !IsStairBodyCategory(edge.CategoryId) && edge.NearDepth is double near + ? VisibleTerrainEdges([edge], stairMasks.Where(mask => faceOccluders[mask.Key].MinDepth < near - 1) + .Select(mask => mask.Value), []) + : new[] { edge }; + bool IsRoundElevationEdge(CollectedEdge edge) => + edge.CategoryId == (int)BuiltInCategory.OST_GenericModel + && (roundShaftFaces.Contains(edge.FaceA) || roundShaftFaces.Contains(edge.FaceB)); + var roundElevationEdges = !cut && roundShaftFaces.Count > 0 + ? occluded.Where(IsRoundElevationEdge).ToList() : null; + if (roundElevationEdges is { Count: > 0 }) occluded.RemoveAll(IsRoundElevationEdge); + int sectionPenScale = viewportScale ?? viewScale; + double wallCutWidth = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, true, + sectionPenScale, out double wallPen) ? wallPen : 0.2; + double CutWidth(CollectedEdge edge) => + PenWidths.TryGetWidth(document, edge.CategoryId, true, sectionPenScale, out double width) + ? width : wallCutWidth; + if (detailRoofCuts is { Count: > 0 } && detailWallCuts is { Count: > 0 }) + occluded = ResolveRoofWallCutJoins(occluded, detailRoofCuts, detailWallCuts, + viewPlaneDepth, (pnx, pny, pnz, poff)); + List edges = MergeOverlaps(occluded, paintDetailCuts ? CutWidth : null); // Every visible edge inks, horizontals included: the reference prints the wall top, the slab and roof // outlines and the ground line. (An earlier rule dropped model horizontals because the reference's vector - // layer lacks them — but on A101/A103/A104/A105 the reference carries the drawing as a raster image and only + // layer lacks them — but on A101/A103/A104/A105 the reference carries the drawing as a raster image and only // the annotation as vector, so that comparison measured an export artifact.) // A detail's own annotation curves: Revit stores detail and insulation lines of a view as curve // elements that name the view as their owner (OST_Lines, OST_InsulationLines), with their points in - // model feet — they lie on the view plane and belong to no solid, so no face ever reaches them. + // model feet — they lie on the view plane and belong to no solid, so no face ever reaches them. + List? insulationLines = null; if (planeView != null) { foreach (var element in document.Elements) { - if (element.OwnerViewId != planeView.Id || element.Location is not { CurveType: "Line" } curve) - continue; + if (element.OwnerViewId != planeView.Id || hiddenElements?.Contains(element.Id) == true + || element.Location is not { CurveType: "Line" } curve) continue; if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_InsulationLines or (int)BuiltInCategory.OST_SketchLines)) continue; @@ -403,6 +1629,18 @@ internal sealed record ElevationContent( double bx = (b[0] * H[0] + b[1] * H[1] + b[2] * H[2]) * FeetToMillimetres; double by = (b[0] * V[0] + b[1] * V[1] + b[2] * V[2]) * FeetToMillimetres; if (Math.Abs(bx - ax) + Math.Abs(by - ay) < 1e-6) continue; + if (isDetail && cropWindow != null && element.DetailInsulation is { } insulation + // shortcut: unit-scale batt profile; retain the curve until non-unit scaling is verified. + && Math.Abs(insulation.Scale - 1) < 1e-9) + { + var strokes = DetailAnnotations.BattInsulation(ax, ay, bx, by, + insulation.Width * FeetToMillimetres, insulation.Mirrored).ToList(); + if (strokes.Count > 0) + { + (insulationLines ??= []).AddRange(strokes); + continue; + } + } // The file keeps annotation the viewport does not show (a line drawn past the crop edge): // only the part inside the crop is printed, and it does not stretch the drawing's frame. if (cropWindow is { } curveCrop) @@ -419,7 +1657,191 @@ internal sealed record ElevationContent( } // A detail keeps its fine construction lines; anywhere else coincident modeling // (a railing family drawing the same board four times) inks once. - if (window == null && !isDetail) edges = ConsolidateCoincident(edges); + if (window == null && !isDetail) + { + double elevationRailPenWidth = 0; + if (!cut && planeOrigin.Length == 3) + { + int scale = viewportScale ?? viewScale; + double outlinePen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, + false, scale, out double width) ? width : DefaultOutlinePen; + elevationRailPenWidth = scale * outlinePen; + } + edges = ConsolidateCoincident(edges, keepFineSectionProfiles: fineSection, + elevationRailPenWidth: elevationRailPenWidth); + } + if (roundElevationEdges is { Count: > 0 }) + { + // Both sides of a round shaft are distinct even when they are closer than the merge tolerance. + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in roundElevationEdges) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (roofInsertFaces.Count > 0) + { + // Resolve the two sides of roof inserts before reducing them to projected lines. + var roofEdges = DedupeEdges(edgeFaces.Where(face => roofInsertFaces.Contains(face.FaceIndex)).ToList(), + D, cut ? planeOrigin : null, roofInsertFaces: roofInsertFaces); + var visibleRoofEdges = OccludeEdges(faces, faceOccluders, roofEdges, false, roofInsertFaces) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + edges.RemoveAll(edge => roofInsertFaces.Contains(edge.FaceA)); + edges.AddRange(window == null && !isDetail ? ConsolidateCoincident(visibleRoofEdges) : visibleRoofEdges); + } + if (topRailEdges.Count > 0) + { + // Projected duplicates are resolved after visibility; a back face can share the visible face's boundary. + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + var visible = OccludeEdges(faces, faceOccluders, topRailEdges, keepWindowJambs: false); + foreach (var edge in visible) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (railingMaskDepths.Count > 0) + { + // Consolidate the original strokes first so subdividing jambs cannot change which rail edges survive. + edges = edges.SelectMany(ClipAtRailings).ToList(); + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + var restored = MergeOverlaps(behindRailings.SelectMany(ClipAtStairs).SelectMany(ClipAtRailings).ToList()); + // Fine railing profiles can have two visible edges just millimetres apart. + var jambs = ConsolidateCoincident(restored.FindAll(edge => !IsRailingCategory(edge.CategoryId))); + foreach (var edge in jambs.Concat(restored.Where(edge => IsRailingCategory(edge.CategoryId)))) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + IEnumerable ClipAtRailings(CollectedEdge edge) => + RailingClipDepth(edge) is double near + ? VisibleTerrainEdges([edge], railingMaskDepths.Where(mask => mask.Value < near + && ClipsAtBaluster(edge, faceOccluders[mask.Key].CategoryId)) + .Select(mask => faces[mask.Key].Points), [], coverBoundary: false) + : new[] { edge }; + if (meshCovers != null && meshSilhouettes.Count > 0) + { + // Replace the owning mesh's strokes after resolving the adjacent model's edge candidates. + var meshOwners = meshSilhouettes.Select(edge => edge.SilhouetteOwnerId).ToHashSet(); + edges.RemoveAll(edge => !edge.IsCut && edge.FaceA >= 0 + && meshOwners.Contains(faceOccluders[edge.FaceA].ElementId)); + var spans = new List(); + foreach (var group in meshSilhouettes.GroupBy(edge => (edge.NearDepth, edge.SilhouetteOwnerId))) + { + var covers = meshCovers.Where(face => face.ElementId != group.Key.SilhouetteOwnerId + && face.FarDepth < group.Key.NearDepth - 1).Select(face => face.Points); + if (modelSectionMasks != null) covers = covers.Concat(modelSectionMasks); + spans.AddRange(VisibleTerrainEdges(group, covers, [], coverBoundary: false)); + } + edges.AddRange(MergeOverlaps(OccludeEdges(faces, faceOccluders, spans, keepWindowJambs: false))); + } + if (terrainEdges.Count > 0) + { + var terrainMasks = !cut ? terrainForeground + : terrainSectionMasks.Count > 0 ? terrainSectionMasks : faces.Select(face => face.Points); + var terrainProfile = MergeOverlaps(terrainEdges); + var visibleGrade = VisibleTerrainEdges(terrainProfile, terrainMasks, terrainPads).ToList(); + if (cropWindow is { } gradeCrop) + { + foreach (var edge in visibleGrade) + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, gradeCrop.X0, gradeCrop.Y0, + gradeCrop.X1, gradeCrop.Y1, out double x1, out double y1, out double x2, out double y2)) + edges.Add(edge with { X1 = x1, Y1 = y1, X2 = x2, Y2 = y2 }); + } + else + { + edges.AddRange(visibleGrade); + } + if (document.RawData.SiteCutGraphics is { } site + && document.RawData.MaterialPatterns?.TryGetValue(site.MaterialId, out var material) == true + && document.RawData.FillPatterns?.TryGetValue(material.CutPatternId, out var pattern) == true + && pattern.Grids.Count > 0) + { + var hatchProfile = cut ? VisibleTerrainEdges(terrainProfile, [], terrainPads) : visibleGrade; + // Drafting grids share the stored view origin across the profile and pad spans. + groundHatch = new TerrainHatch( + planeOrigin[0] * H[0] + planeOrigin[1] * H[1] + planeOrigin[2] * H[2], + planeOrigin[0] * V[0] + planeOrigin[1] * V[1] + planeOrigin[2] * V[2], + site.BaseFeet * FeetToMillimetres, hatchProfile.Concat(padProfile).ToList(), pattern.Grids, + terrainSectionMasks.Count > 0 ? terrainSectionMasks : null); + if ((!cut || groundHatch.SectionMasks != null) && FillHatch.DraftingTiles(pattern.Grids, 0, 0, 0.1) is { Count: > 0 }) + { + bool BehindGround(CollectedEdge edge) => + !edge.IsCut && edge.FaceA >= 0 && edge.MidDepth > viewPlaneDepth + 1; + var covers = GroundSpans(groundHatch, groundHatch.BaseY); + if (!cut) covers = covers.Concat(terrainSectionMasks); + var projected = edges.Where(BehindGround).ToList(); + var visible = VisibleTerrainEdges(projected, covers, [], coverBoundary: false).ToList(); + if (!cut && spanOccluders is { Count: > 0 }) + { + // The original midpoint can be outside a nearer face even when the grade only leaves a span behind it. + var originalSpans = projected.ToHashSet(); + bool NeedsModelClip(CollectedEdge edge) => edge.NearDepth.HasValue + && edge.CategoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_StructuralFoundation) + && (!originalSpans.Contains(edge) || WithinPadCut(edge)); + bool WithinPadCut(CollectedEdge edge) + { + if (Math.Abs(edge.X1 - edge.X2) >= 1e-6) return false; + double x = edge.X1; + return terrainPads.Any(pad => x > pad.From && x < pad.To) + && terrainProfile.Any(grade => x >= Math.Min(grade.X1, grade.X2) + && x <= Math.Max(grade.X1, grade.X2) && grade.X1 != grade.X2 + && Math.Min(edge.Y1, edge.Y2) < grade.Y1 + + (x - grade.X1) * (grade.Y2 - grade.Y1) / (grade.X2 - grade.X1)); + } + var trimmed = visible.Where(NeedsModelClip).GroupBy(edge => edge.NearDepth!.Value).ToList(); + visible.RemoveAll(NeedsModelClip); + foreach (var group in trimmed) + visible.AddRange(VisibleTerrainEdges(group, + spanOccluders.Where(mask => mask.FarDepth < group.Key - 1).Select(mask => mask.Points), [], + coverBoundary: false, openings: spanOpenings)); + } + edges.RemoveAll(edge => BehindGround(edge)); + edges.AddRange(visible); + } + } + } + edges.AddRange(elevationCutEdges); + // Clip after merging so the selection of other coincident edges stays independent of these spans. + if (sectionWallFaces.Count > 1) + { + var wallFacesByFinish = sectionWallFaces.ToLookup(face => (face.Value.TypeId, face.Value.MaterialId)); + var trimmedSpans = new List(); + edges = edges.SelectMany(ClipWallOverlap).ToList(); + if (trimmedSpans.Count > 0) + { + var visible = OccludeEdges(faces, faceOccluders, trimmedSpans, keepWindowJambs: false); + var hidden = trimmedSpans.Except(visible).ToHashSet(); + edges.RemoveAll(hidden.Contains); + } + + IEnumerable ClipWallOverlap(CollectedEdge edge) + { + if (edge.IsCut || edge.ViewLineStyleId != 0 || edge.NearDepth is not double near + || Math.Abs(edge.MidDepth - near) >= 1e-6 + || !sectionWallFaces.TryGetValue(edge.FaceA, out var wall)) return [edge]; + + int elementId = faceOccluders[edge.FaceA].ElementId; + var covers = wallFacesByFinish[(wall.TypeId, wall.MaterialId)] + .Where(face => faceOccluders[face.Key].ElementId != elementId + && Math.Abs(face.Value.Depth - wall.Depth) < 1e-6) + .Select(face => faces[face.Key].Points).ToList(); + if (covers.Count == 0) return [edge]; + var spans = VisibleTerrainEdges([edge], covers, [], coverBoundary: false).ToList(); + if (spans is [var span] && Math.Abs(span.X2 - edge.X2) < 1e-6 && Math.Abs(span.Y2 - edge.Y2) < 1e-6 + && Math.Abs(span.X1 - edge.X1) < 1e-6 && Math.Abs(span.Y1 - edge.Y1) < 1e-6) return [edge]; + trimmedSpans.AddRange(spans); + return spans; + } + } + if (sectionWallFaces.Count > 0) + edges = edges.SelectMany(ClipSlopingRailBehindWall).ToList(); + + IEnumerable ClipSlopingRailBehindWall(CollectedEdge edge) + { + if (edge.IsCut || edge.ViewLineStyleId != 0 || !IsRailingCategory(edge.CategoryId) + || edge.NearDepth is not double near || Math.Abs(near - edge.MidDepth) >= 1e-6 + || Math.Abs(edge.X1 - edge.X2) < 1e-6 || Math.Abs(edge.Y1 - edge.Y2) < 1e-6) + return [edge]; + + var covers = sectionWallFaces.Where(face => face.Value.Depth < near - 1) + .Select(face => faces[face.Key].Points); + return VisibleTerrainEdges([edge], covers, [], coverBoundary: false); + } // The site around the building is drawn, but it does not decide the frame: the building does, with a little // air around it for the trees and the ground. Context beyond that air (a tree far down the site) is dropped, // so the drawing stays the size of the building. @@ -428,23 +1850,21 @@ internal sealed record ElevationContent( double breadth = maxX - minX, heightExtent = maxY - minY; double keepLeft = minX - breadth * 0.25, keepRight = maxX + breadth * 0.25; double keepBottom = minY - heightExtent * 0.08, keepTop = maxY + heightExtent * 0.08; - context.RemoveAll(shape => shape.Points.Any(point => point.X < keepLeft || point.X > keepRight - || point.Y < keepBottom || point.Y > keepTop)); + context.RemoveAll(shape => (!shape.Terrain || terrainFillCrop == null) && + shape.Points.Any(point => point.X < keepLeft || point.X > keepRight + || point.Y < keepBottom || point.Y > keepTop)); minX -= breadth * 0.02; maxX += breadth * 0.02; minY -= heightExtent * 0.02; maxY += heightExtent * 0.02; } - // Far to near: painter's algorithm, so a nearer wall hides the one behind it. - faces.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - // The levels of the model and the grids that stand across the view are drawn dashed, as an elevation prints // them, with the level name and the grid bubble. Only the level records of the project count: the families // each carry their own reference levels (dozens sharing the category), which no project view shows. var levels = new List<(double Y, string Label, Element Plane)>(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Levels) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Levels || hiddenElements?.Contains(element.Id) == true) continue; if (element.RootClassName != "Level") continue; if (element.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double elevation) continue; levels.Add((elevation * FeetToMillimetres, element.Name ?? "", element)); @@ -454,6 +1874,12 @@ internal sealed record ElevationContent( // once, with the first name it finds. The line of a level runs to its datum envelope projected on the // view's right axis (rvt-prt datums.py); without a decoded plane it spans the content like before. var distinctLevels = new List<(double Y, string Label, double X0, double X1)>(); + var nativeLevels = new Dictionary(); + var defaultLevelHeads = new List<(double Y, int Type, double Left, double Right, double Radius, int SymbolId)>(); + var savedModelExtentHeads = new List<(int Type, double Left, double Right, double Head)>(); + var datumExtents = planeView != null ? document.RawData.DatumExtents?.GetValueOrDefault(planeView.Id) : null; + if (datumExtents != null && Math.Abs(datumExtents.Normal[0] * D[0] + datumExtents.Normal[1] * D[1] + + datumExtents.Normal[2] * D[2] - 1) > 1e-6) datumExtents = null; foreach (var level in levels) { if (distinctLevels.Count > 0 && Math.Abs(distinctLevels[^1].Y - level.Y) < 1.0) @@ -483,11 +1909,67 @@ internal sealed record ElevationContent( } } distinctLevels.Add((level.Y, level.Label, x0, x1)); + if (level.Plane.LevelPlane is not { Origin: var levelOrigin } + || document.RawData.DatumHeads?.GetValueOrDefault(level.Plane.TypeId) is not { } head + || CircleHeadRadius(document, head.SymbolId, "M_Level Head - Circle") is not double radius) continue; + var extent = datumExtents?.Datums.GetValueOrDefault(level.Plane.Id); + if (extent == null && sectionAnnotationCrop is { } annotation) + { + double left = Math.Max(x0, annotation.X0), right = Math.Min(x1, annotation.X1); + if (right > left) + nativeLevels.Add(level.Y, new NativeLevelLine(left, right, level.Y, right, radius, null, head.SymbolId)); + } + else if (extent == null && datumExtents != null) + { + defaultLevelHeads.Add((level.Y, level.Plane.TypeId, x0, x1, radius, head.SymbolId)); + } + // shortcut: support the authored right head until left and dual heads are decoded. + else if (extent is { Overrides: 0 or 0x20 or 0x30, FreeEndLeader: null } + && (extent.Overrides == 0x30 ? extent.FreeEnd : extent.FreeEnd3d) is double freeEnd + && double.IsFinite(freeEnd)) + { + double datumOrigin = Project(levelOrigin, H); + double left = datumOrigin + freeEnd * FeetToMillimetres; + // A leader remains authored when both endpoints use the model extent. + if (extent is { Overrides: 0, BubbleLeader: null }) continue; + double headX = extent.Overrides == 0 + ? Project(extent.BubbleLeader!.Anchor, H) + : datumOrigin + extent.BubbleEnd * FeetToMillimetres; + if (!(headX > left)) continue; + var line = new NativeLevelLine(left, headX, level.Y, headX, radius, null, head.SymbolId); + if (extent.BubbleLeader is { } leader) + { + double endX = Project(leader.End, H); + double endY = Project(leader.End, V); + var elbow = (X: Project(leader.Elbow, H), Y: Project(leader.Elbow, V)); + double headY = Project(leader.Anchor, V); + if (Math.Abs(endY - level.Y) > 1 || Math.Abs(Project(leader.Anchor, H) - headX) > 1 + || endX < left || elbow.X < endX || headX < elbow.X) continue; + if (Math.Abs(headY - level.Y) > 1 || Math.Abs(elbow.Y - level.Y) > 1) + line = line with { HeadY = headY, LineEnd = endX, Elbow = elbow }; + } + nativeLevels.Add(level.Y, line); + if (extent.Overrides == 0 && extent.BubbleEnd3d is double modelRight + && headX <= x1 && Math.Abs(left - x0) <= 1 + && Math.Abs(datumOrigin + modelRight * FeetToMillimetres - x1) <= 1) + savedModelExtentHeads.Add((level.Plane.TypeId, x0, x1, headX)); + } + } + foreach (var level in defaultLevelHeads) + { + // Model-extent leaders can expose the shared head column even when straight levels have no view record. + var heads = savedModelExtentHeads.Where(head => head.Type == level.Type + && Math.Abs(head.Left - level.Left) <= 1 && Math.Abs(head.Right - level.Right) <= 1) + .Select(head => head.Head).ToList(); + if (heads.Count >= 2 && heads.Max() - heads.Min() <= 1) + nativeLevels.Add(level.Y, new NativeLevelLine(level.Left, heads[0], level.Y, heads[0], + level.Radius, null, level.SymbolId)); } var grids = new List<(double X, string Name)>(); + var nativeGrids = new Dictionary(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Grids) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Grids || hiddenElements?.Contains(element.Id) == true) continue; if (element.Location is not { CurveType: "Line" } line) continue; double dx = line.EndPoint[0] - line.StartPoint[0], dy = line.EndPoint[1] - line.StartPoint[1]; double length = Math.Sqrt(dx * dx + dy * dy); @@ -495,82 +1977,369 @@ internal sealed record ElevationContent( if (Math.Abs(dx / length * H[0] + dy / length * H[1]) > 0.2) continue; double x = (line.StartPoint[0] * H[0] + line.StartPoint[1] * H[1]) * FeetToMillimetres; grids.Add((x, element.Name ?? "")); + if (planeView is { ViewOrigin.Length: 3 } && V[2] > 0.999 + && element.GridPlane is { Envelope.Length: 4 } gridPlane + && document.RawData.DatumHeads?.GetValueOrDefault(element.TypeId) is { GridBubblePosition: 2 } head + && CircleHeadRadius(document, head.SymbolId, "M_Grid Head - Circle") is double radius) + { + var extent = datumExtents?.Datums.GetValueOrDefault(element.Id); + bool authored = extent is { Overrides: 0x20 or 0x30, BubbleLeader: null, FreeEndLeader: null, + FreeEnd3d: not null, BubbleEnd3d: not null }; + bool unboundedSection = fineSection && !detailPath && !stairsOnly && sectionCrop != null + && planeView.ViewAnnotationCropActive is false && extent == null; + if (!authored && !unboundedSection && (detailPath || stairsOnly || viewScale < 100) + && (sectionAnnotationCrop == null || extent != null)) continue; + var e = gridPlane.Envelope; + double datumOrigin = Project(gridPlane.Origin, V); + double u = Project(gridPlane.XVector, V); + double v = Project(gridPlane.YVector, V); + double bottom = datumOrigin + Math.Min(u * e[0], u * e[2]) + Math.Min(v * e[1], v * e[3]); + double top = datumOrigin + Math.Max(u * e[0], u * e[2]) + Math.Max(v * e[1], v * e[3]); + if (authored) + { + // The stored 2D and 3D values share an origin, even when the detail view itself moved. + top += (extent!.BubbleEnd - extent.BubbleEnd3d!.Value) * FeetToMillimetres; + if (extent.Overrides == 0x30) + bottom += (extent.FreeEnd - extent.FreeEnd3d!.Value) * FeetToMillimetres; + } + else if (sectionAnnotationCrop is { } annotation) + { + bottom = Math.Max(bottom, annotation.Y0); + top = Math.Min(top, annotation.Y1); + } + else if (unboundedSection) + { + // The default grid envelope includes the head above the end of the line. + top -= 2 * radius * (viewportScale ?? viewScale); + } + if (double.IsFinite(bottom) && double.IsFinite(top) && top > bottom) + nativeGrids.TryAdd(x, new NativeGridLine(bottom, top, radius)); + } } grids.Sort((left, right) => left.X.CompareTo(right.X)); context.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - // A detail carries no grid bubbles (none of the reference details shows one), and a windowed - // detail without a file crop carries no level lines either. But a crop-drawn detail keeps the levels - // whose height falls in its crop — the reference details draw their own level rows with markers - // (Typ. Wall Section shows all six), and DrawContent already clips rows to the crop height. + // Detail datums need authored ends or a decoded annotation crop. A detail without a model crop + // also omits the level rows because their visible height is unknown. if (window != null || isDetail) { if (cropWindow == null) distinctLevels.Clear(); - grids.Clear(); + grids.RemoveAll(grid => !nativeGrids.ContainsKey(grid.X)); } // The grid bubbles print above the frame: without grids (a windowed detail) the frame ends at the model. if (grids.Count > 0) maxY += 4500; - return new ElevationContent(faces, distinctLevels, grids, context, edges, minX, minY, maxX, maxY); - } - - /// A projected edge for inking: its ends in view millimetres, the painter's depth of its face, - /// the depth of its midpoint for occlusion, the incident faces (FaceB is -1 when single), its plane key - /// for coplanar merging, whether the section cut created it (inked with its own category's cut pen; - /// other edges use the projection pen), and the category of the face it came from. - internal sealed record CollectedEdge(double X1, double Y1, double X2, double Y2, double Depth, double MidDepth, - int FaceA, int FaceB, long Nx, long Ny, long Nz, long Off, bool IsCut = false, int CategoryId = 0); - - /// Visible edges of the projected faces: an edge shared by exactly two coplanar faces is a - /// triangulation diagonal inside a flat surface and is not inked; every other edge is drawn once, so a + var detailBreaks = isDetail && cropWindow != null && planeView != null + ? DetailAnnotations.BreakLines(document, planeView.Id, H, V) : null; + var surfaceHatches = surfacePatterns.Count == 0 && dashedSurfacePatterns.Count == 0 && regionHatches == null + ? null : new SurfaceHatches( + planeOrigin[0] * H[0] + planeOrigin[1] * H[1] + planeOrigin[2] * H[2], + planeOrigin[0] * V[0] + planeOrigin[1] * V[1] + planeOrigin[2] * V[2], surfacePatterns, dashedSurfacePatterns, + UseClippedLines: opaqueFineSection && !detailPath, Regions: regionHatches); + // shortcut: use wholly nearer masks for site meshes until their edges carry per-point depths. + foreach (var group in viewLines.GroupBy(edge => edge.NearDepth)) + edges.AddRange(VisibleTerrainEdges(group, plantMasks.Where(mask => mask.Far < group.Key).Select(mask => mask.Points), [])); + // Keep regular section layer edges out of the selection of coincident model edges. + if (roofLayerEdges != null) edges.AddRange(roofLayerEdges); + if (clippedCalloutWalls.Count > 0) + { + // Adding the split spans earlier can change the selection of unrelated coincident edges. + edges.RemoveAll(edge => IsSlopingWall(edge) + && clippedCalloutWalls.Contains((ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), edge.MidDepth))); + var visibleSlopes = OccludeEdges(faces, faceOccluders, calloutWallSpans, keepWindowJambs: false, + useDetailPlaneDepth: detailWallOccluders != null); + edges.AddRange(MergeOverlaps(visibleSlopes.SelectMany(ClipAtStairs).SelectMany(ClipAtRailings).ToList())); + } + var cutFaces = paintDetailCuts ? terrainSectionMasks : modelSectionMasks; + if (cutFaces is { Count: > 0 }) + { + bool BehindCap(CollectedEdge edge) => + edge.FaceA >= 0 && !edge.IsCut && edge.NearDepth > viewPlaneDepth + 1; + var visible = VisibleTerrainEdges(edges.Where(BehindCap), cutFaces, [], coverBoundary: false).ToList(); + edges.RemoveAll(edge => BehindCap(edge)); + edges.AddRange(visible); + } + List<(double X, double Y)>? soilReceiver = null; + if (shadows != null && groundHatch != null && shadowTerrainCrop is { } soilBounds) + soilReceiver = shadows.AddSoilCutReceiver(soilBounds, viewPlaneDepth, groundHatch.BaseY); + var castShadows = shadows?.Project(viewPlaneDepth); + if (groundHatch != null && soilReceiver != null && castShadows?.Remove(soilReceiver, out var soilShadow) == true) + groundHatch = groundHatch with { Shadow = soilShadow }; + if (terrainOcclusion != null) + { + sectionTerrain?.Sort(); + edges = terrainOcclusion.ClipEdges(edges, cut); + } + if (!cut && drawTerrainCut && showSurfacePatterns) + { + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + // A projected stair edge may have lost its nearer copy during ordinary mesh edge selection. + var missing = deduped.Where(edge => IsStairBodyCategory(edge.CategoryId) + && !inked.Contains(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .ToDictionary(group => group.Key, group => group.Min(edge => edge.MidDepth)); + if (missing.Count > 0) + { + var nearer = DedupeEdges(edgeFaces.Where(face => IsStairBodyCategory(face.CategoryId)).ToList(), + D, keepStairDepths: true) + .Where(edge => missing.TryGetValue(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), + out double farDepth) && edge.MidDepth < farDepth - 1).ToList(); + var visible = OccludeEdges(faces, faceOccluders, nearer, keepWindowJambs: false); + if (terrainOcclusion != null) visible = terrainOcclusion.ClipEdges(visible, cut: false); + foreach (var edge in ConsolidateCoincident(visible)) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + } + if (elevationTubeEdges.Count > 0) + { + var visible = OccludeEdges(faces, faceOccluders, elevationTubeEdges, keepWindowJambs: false); + if (terrainOcclusion != null) visible = terrainOcclusion.ClipEdges(visible, cut: false, requireFace: false); + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in ConsolidateCoincident(visible)) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (sectionBillboards.Count > 0) + { + var points = sectionBillboards.SelectMany(ring => ring).ToArray(); + double left = points.Min(point => point.X), right = points.Max(point => point.X); + double bottom = points.Min(point => point.Y), top = points.Max(point => point.Y); + bool BehindBillboard(CollectedEdge edge) => edge.FaceA >= 0 && !edge.IsCut + && edge.ViewLineStyleId == 0 && edge.MidDepth >= viewPlaneDepth + && Math.Min(edge.X1, edge.X2) < right && Math.Max(edge.X1, edge.X2) > left + && Math.Min(edge.Y1, edge.Y2) < top && Math.Max(edge.Y1, edge.Y2) > bottom; + var visible = VisibleTerrainEdges(edges.Where(BehindBillboard), sectionBillboards, [], + coverBoundary: false).ToList(); + edges.RemoveAll(edge => BehindBillboard(edge)); + edges.AddRange(visible); + } + // Removing seams earlier can change which other coincident model edge is selected. + if (railSeams is { Count: > 0 }) + edges.RemoveAll(edge => !edge.IsCut && edge.ViewLineStyleId == 0 && IsRailingCategory(edge.CategoryId) + && railSeams.Contains(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))); + var siteOutlines = siteObjects.Count == 0 ? null : siteObjects.SelectMany(site => + VisibleTerrainEdges(site.Edges, plantMasks.Where(mask => mask.Far < site.Near).Select(mask => mask.Points) + .Concat(site.WireMesh + ? siteModelMasks.Where(mask => mask.Near >= viewPlaneDepth && mask.Far < site.Near) + .Select(mask => mask.Points) + : faces.Select(face => face.Points)), [])).ToList(); + if (plantingOutlines != null) + { + var ground = groundHatch != null ? GroundSpans(groundHatch, groundHatch.BaseY).ToList() : []; + var outlines = plantingOutlines.Project(ground).ToList(); + if (outlines.Count > 0) (siteOutlines ??= []).AddRange(outlines); + } + if (cropWindow is { } finalCrop) + { + // Layer boundaries and roof-wall seams can be derived from full host rings after the faces were clipped. + edges = edges.Select(edge => ClipCollectedEdge(edge, finalCrop)).OfType().ToList(); + } + var ambientTones = ambient?.Calculate(paintDetailCuts ? cutFaces : null, viewPlaneDepth); + var paneTones = screenPaneOwners is { Count: > 0 } && screenWallReceivers is { Count: > 0 } + && sectionCrop is { } screenCrop + ? new PaneScreenShadows(screenCrop, viewportScale ?? viewScale, ambientFraction) + .Calculate(faces, faceOccluders.Select(owner => owner.ElementId).ToArray(), paintOpenings, + screenPaneOwners, screenWallReceivers, ambientTones) + : null; + // Visibility uses face indices in collection order. Reorder the fills only for painting. + faces.Sort((left, right) => right.Depth.CompareTo(left.Depth)); + return new ElevationContent(faces, distinctLevels, grids, context, edges, minX, minY, maxX, maxY, + groundHatch, nativeLevels, nativeGrids, insulationLines, detailBreaks, layerHatches, + CircularAnnotations.Project(document, planeView?.Id, H, V), surfaceHatches, + modelHatches.Count > 0 ? modelHatches : null, castShadows, skyGradient, + siteSilhouettes is { Count: > 0 } ? siteSilhouettes : null, + opaqueSection && (drawGround && !detailPath || paintDetailCuts && ambient != null), + siteOutlines, + paintOpenings.Count > 0 ? paintOpenings : null, shadows?.ClipSiteFacetsToModel(castShadows), + DetailCutFaces: cutFaces is { Count: > 0 } ? cutFaces : null, + Glazing: glazing is { HasPanes: true } ? glazing : null, + AmbientTones: ambientTones, + FaceFills: faceFills.Count > 0 ? faceFills : null, + DetailGlass: detailGlass is { Count: > 0 } ? detailGlass : null, + TerrainClippedFaces: terrainOcclusion?.ClippedFaces(), + KeepDoorDepths: keepDoorDepths, + SectionBillboards: sectionBillboards.Count > 0 ? sectionBillboards : null, + PlantTones: ElevationShadows.VisiblePlantTones(plantFacets, plantTones), + ExteriorWallTones: exteriorWallTones.Count > 0 ? exteriorWallTones : null, + PaneTones: paneTones); + + System.Numerics.Vector3 AmbientVector(double[] point, double units) => + new((float)Project(point, H, units), (float)Project(point, V, units), (float)Project(point, D, units)); + + int StairAssembly(int id) => + document.GetElement(id)?.SerializedOwningElementId is > 0 and int owner + && document.GetElement(owner)?.CategoryId == (int)BuiltInCategory.OST_Stairs ? owner : id; + + static bool PlacedSiteElement(Element element) => !element.IsDiscovered + && element.SerializedUnplacedOwnerId is not > 0 && element.NativeIsSymbol != true + && !element.RootClassIs("FamilySymbol"); + + bool HasEdgeOnRoofGlazing(List geometryFaces) + { + bool hasPane = false; + foreach (var face in geometryFaces) + { + // The thickness of the pane has vertical faces even when the pane itself is seen edge-on. + if (!face.PlaneSurface || Math.Abs(face.Normal[2]) <= 1e-9 + || document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0) + continue; + if (Math.Abs(Project(face.Normal, D, 1)) > 1e-9) return false; + hasPane = true; + } + return hasPane; + } + + bool HasGlazingPattern(GeoFace face) => + (face.RenderStyleId ?? face.NestedRenderStyleId) is > 0 and int material + && document.GetElement(material)?.SerializedMaterialTransparency is > 0 + && document.RawData.MaterialPatterns?.TryGetValue(material, out var pattern) == true + && pattern.SurfacePatternColor == 0 && pattern.SurfacePatternId == face.ModelPattern?.PatternId; + + static bool IsProjectedRectangle(List<(double X, double Y)> points) => + points.Count == 4 && Math.Abs(PlanPrinter.SignedArea(points)) > 1e-6 + && points.Zip(points.Skip(1).Append(points[0])).All(edge => + Math.Abs(edge.First.X - edge.Second.X) < 1e-6 || Math.Abs(edge.First.Y - edge.Second.Y) < 1e-6); + + static bool RectanglesOverlap(List<(double X, double Y)> a, List<(double X, double Y)> b) => + Math.Min(a.Max(point => point.X), b.Max(point => point.X)) + - Math.Max(a.Min(point => point.X), b.Min(point => point.X)) > 1e-6 + && Math.Min(a.Max(point => point.Y), b.Max(point => point.Y)) + - Math.Max(a.Min(point => point.Y), b.Min(point => point.Y)) > 1e-6; + + List<(double X, double Y)> ProjectRing(List vertices) + { + var ring = vertices.Select(p => p.Select(value => value * FeetToMillimetres).ToArray()).ToList(); + if (cut || drawTerrainCut) ring = ClipBehind(ring, planeOrigin, D); + var points = ring.Select(p => (X: Project(p, H, 1), Y: Project(p, V, 1))).ToList(); + return cropWindow is { } crop ? ClipToWindow(points, crop.X0, crop.X1, crop.Y0, crop.Y1) : points; + } + + IEnumerable> ProjectOpenings(GeoFace face) + { + foreach (var hole in face.InnerVertices ?? []) + { + if (hole.Count < 3 || hole.Any(point => point.Length != 3 || !point.All(double.IsFinite))) continue; + var points = ProjectRing(hole); + if (points.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(points)) > 1e-6) yield return points; + } + } + + void OrderRoofLayerPaint(List<(int Index, GeoFace Face)> roofLayers) + { + foreach (var (index, exterior) in roofLayers) + { + var patterned = faces[index]; + if (!modelHatches.ContainsKey(patterned.Points) || exterior.GeometryNode == 0) continue; + double nd = Project(D, exterior.Normal, 1); + if (Math.Abs(nd) < 1e-6) continue; + double exteriorPlane = Project(exterior.OuterVertices![0], exterior.Normal); + foreach (var (otherIndex, other) in roofLayers) + { + if (other.GeometryNode != exterior.GeometryNode + || Math.Abs(other.Normal[0] + exterior.Normal[0]) + + Math.Abs(other.Normal[1] + exterior.Normal[1]) + + Math.Abs(other.Normal[2] + exterior.Normal[2]) > 1e-6) continue; + double gap = (Project(other.OuterVertices![0], exterior.Normal) - exteriorPlane) / nd; + var underside = faces[otherIndex]; + if (gap <= 1 || underside.Depth > patterned.Depth) continue; + // Different extents can reverse the mean depths of parallel skins of the same solid. + faces[otherIndex] = (underside.Points, patterned.Depth + gap, underside.Outline); + } + } + } + } + + internal static double? CircleHeadRadius(RvtDocument document, int symbolId, string familyName) + { + var family = document.GetElement(symbolId); + if (family is not { FamilyName: var name, BoundingBox: { Length: 6 } box } || name != familyName) return null; + double width = (box[3] - box[0]) * FeetToMillimetres; + double height = (box[4] - box[1]) * FeetToMillimetres; + return height > 0 && Math.Abs(width - height) < 0.01 ? height / 2 : null; + } + + /// A projected edge for inking: its ends in view millimetres, the painter's depth of its face, + /// the depth of its midpoint for occlusion, the incident faces (FaceB is -1 when single), its plane key + /// for coplanar merging, whether the section cut created it (inked with its own category's cut pen; + /// other edges use the projection pen), and the category of the face it came from. + internal sealed record CollectedEdge(double X1, double Y1, double X2, double Y2, double Depth, double MidDepth, + int FaceA, int FaceB, long Nx, long Ny, long Nz, long Off, bool IsCut = false, int CategoryId = 0, + double? NearDepth = null) + { + internal int ViewLineStyleId { get; init; } + internal CollectedEdge? UnclippedViewLine { get; init; } + internal (int Ring, int Segment)? SourceRingEdge { get; init; } + internal int? SilhouetteOwnerId { get; init; } + } + + internal static (long Ax, long Ay, long Bx, long By) ProjectedEdgeKey(double x1, double y1, double x2, double y2) + { + long ax = (long)Math.Round(x1 * 10), ay = (long)Math.Round(y1 * 10); + long bx = (long)Math.Round(x2 * 10), by = (long)Math.Round(y2 * 10); + return (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); + } + + /// Visible edges of the projected faces: an edge shared by exactly two coplanar faces is a + /// triangulation diagonal inside a flat surface and is not inked; every other edge is drawn once, so a /// crease shared by two faces is not inked twice. Endpoints quantize to 0.1 mm, plane normals to 0.001 /// and plane offsets to 0.5 mm. Each edge carries its 3D midpoint depth and its incident faces. An edge /// both of whose 3D ends lie on the cut plane (within a millimetre) is cut-created. - internal static List DedupeEdges( - List<(List<(double X, double Y)> Points, List Ring, double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId)> edgeFaces, - double[] viewDir, double[]? cutOrigin = null) + private sealed record ProjectionFace(List<(double X, double Y)> Points, List Ring, + double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId, bool[]? IncomingEdges); + + private static List DedupeEdges( + List edgeFaces, + double[] viewDir, double[]? cutOrigin = null, bool keepComponentDepths = false, + IReadOnlySet? roofInsertFaces = null, bool fineSection = false, bool keepStairDepths = false, + HashSet<(long Ax, long Ay, long Bx, long By)>? railSeams = null, bool keepDoorDepths = false, + bool keepDetailProfileDepths = false) { - var byEdge = new Dictionary<(long Ax, long Ay, long Bx, long By), List>(); + var byEdge = new Dictionary<((long Ax, long Ay, long Bx, long By) Edge, long Start, long End), + List<(int Face, int Vertex)>>(); for (int f = 0; f < edgeFaces.Count; f++) { - var points = edgeFaces[f].Points; - for (int i = 0; i < points.Count; i++) + var face = edgeFaces[f]; + for (int i = 0; i < face.Points.Count; i++) { - var a = points[i]; - var b = points[(i + 1) % points.Count]; - long ax = (long)Math.Round(a.X * 10), ay = (long)Math.Round(a.Y * 10); - long bx = (long)Math.Round(b.X * 10), by = (long)Math.Round(b.Y * 10); - if (ax == bx && ay == by) continue; - var key = (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); - if (!byEdge.TryGetValue(key, out var members)) byEdge[key] = members = new List(); - members.Add(f); + if (face.IncomingEdges?[(i + 1) % face.Points.Count] == false) continue; + var key = EdgeKey(face.Points, face.Ring, PreserveDepth(face, i), i); + if (key.Edge.Ax == key.Edge.Bx && key.Edge.Ay == key.Edge.By) continue; + if (!byEdge.TryGetValue(key, out var members)) byEdge[key] = members = []; + members.Add((f, i)); } } var edges = new List(); - var seen = new HashSet<(long Ax, long Ay, long Bx, long By)>(); + var seen = new HashSet<((long Ax, long Ay, long Bx, long By) Edge, long Start, long End)>(); for (int f = 0; f < edgeFaces.Count; f++) { - var (points, ring, depth, nx, ny, nz, off, faceIndex, categoryId) = edgeFaces[f]; + var (points, ring, depth, nx, ny, nz, off, faceIndex, categoryId, incomingEdges) = edgeFaces[f]; // Window-clipped polygons lose the one-to-one vertex correspondence with the 3D ring; // those small details fall back to the face-average depth. bool hasRing = ring.Count == points.Count; for (int i = 0; i < points.Count; i++) { + int next = (i + 1) % points.Count; + if (incomingEdges?[next] == false) continue; var a = points[i]; - var b = points[(i + 1) % points.Count]; - long ax = (long)Math.Round(a.X * 10), ay = (long)Math.Round(a.Y * 10); - long bx = (long)Math.Round(b.X * 10), by = (long)Math.Round(b.Y * 10); - if (ax == bx && ay == by) continue; - var key = (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); + var b = points[next]; + var key = EdgeKey(points, ring, PreserveDepth(edgeFaces[f], i), i); + if (key.Edge.Ax == key.Edge.Bx && key.Edge.Ay == key.Edge.By) continue; if (!seen.Add(key)) continue; var members = byEdge[key]; - int other = members.Count == 2 ? (members[0] == f ? members[1] : members[0]) : -1; + if (railSeams != null && IsRailingCategory(categoryId) && members.Count > 2 && IsProjectedRailSeam(members, a, b)) + railSeams.Add(key.Edge); + int other = members.Count == 2 ? (members[0].Face == f ? members[1].Face : members[0].Face) : -1; int otherFace = -1; if (other >= 0) { var o = edgeFaces[other]; - if (o.Nx == nx && o.Ny == ny && o.Nz == nz && o.Off == off) continue; + // Opposite sides form a seam. Same-side copies can belong to the same native face. + if (o.Nx == nx && o.Ny == ny && o.Nz == nz && o.Off == off + && (!UsesDetailProfileDepth(edgeFaces[f], i) + || ProjectedSide(a, b, points) * ProjectedSide(a, b, o.Points) == -1)) + continue; otherFace = o.FaceIndex; } double midDepth = depth; + double? nearDepth = null; bool isCut = false; if (hasRing) { @@ -578,23 +2347,137 @@ internal static List DedupeEdges( var cb = ring[(i + 1) % ring.Count]; midDepth = ((ca[0] + cb[0]) / 2) * viewDir[0] + ((ca[1] + cb[1]) / 2) * viewDir[1] + ((ca[2] + cb[2]) / 2) * viewDir[2]; - if (cutOrigin != null) - { - double da = (ca[0] - cutOrigin[0]) * viewDir[0] + (ca[1] - cutOrigin[1]) * viewDir[1] - + (ca[2] - cutOrigin[2]) * viewDir[2]; - double db = (cb[0] - cutOrigin[0]) * viewDir[0] + (cb[1] - cutOrigin[1]) * viewDir[1] - + (cb[2] - cutOrigin[2]) * viewDir[2]; - isCut = Math.Abs(da) <= 1.0 && Math.Abs(db) <= 1.0; - } + nearDepth = Math.Min(Project(ca, viewDir, 1), Project(cb, viewDir, 1)); + isCut = IsCutEdge(ca, cb); } // A horizontal face projects to a horizontal line, so it is seen edge-on and the edge along it is not // inked (the reference draws the wall top as the ends of its boards, without a line across them). // A section keeps the edges its own cut created - those are the cut profile of a horizontal slab. - edges.Add(new CollectedEdge(a.X, a.Y, b.X, b.Y, depth, midDepth, faceIndex, otherFace, nx, ny, nz, off, isCut, categoryId)); + edges.Add(new CollectedEdge(a.X, a.Y, b.X, b.Y, depth, midDepth, faceIndex, otherFace, nx, ny, nz, off, + isCut, categoryId, nearDepth)); } } + // A railing repeats every bar in the element and in the nested symbol it places. The copies land within a + // millimetre of each other on the sheet, so the exact-key dedupe keeps them all and they ink twice. Group the + // horizontal bars within a one-millimetre tolerance and keep the copy nearest the viewer; a second bar more + // than 20 mm behind stays a line of its own. + var railLines = new List<(List Members, double Y, double X0, double X1)>(); + for (int e = 0; e < edges.Count; e++) + { + var edge = edges[e]; + if (edge.IsCut || !IsRailingCategory(edge.CategoryId) || Math.Abs(edge.Y1 - edge.Y2) > 1e-6) continue; + double x0 = Math.Min(edge.X1, edge.X2), x1 = Math.Max(edge.X1, edge.X2); + int found = railLines.FindIndex(line => Math.Abs(line.Y - edge.Y1) <= 1 + && Math.Abs(line.X0 - x0) <= 1 && Math.Abs(line.X1 - x1) <= 1); + if (found < 0) railLines.Add(([e], edge.Y1, x0, x1)); + else railLines[found].Members.Add(e); + } + if (railLines.Count > 0) + { + var drop = new HashSet(); + foreach (var line in railLines) + { + double keptDepth = double.NegativeInfinity; + foreach (int e in line.Members.OrderBy(index => edges[index].MidDepth)) + { + if (keptDepth == double.NegativeInfinity || Math.Abs(edges[e].MidDepth - keptDepth) > 20) + keptDepth = edges[e].MidDepth; + else drop.Add(e); + } + } + if (drop.Count > 0) edges = edges.Where((_, index) => !drop.Contains(index)).ToList(); + } edges.Sort((left, right) => right.Depth.CompareTo(left.Depth)); return edges; + + bool PreserveDepth(ProjectionFace face, int index) => roofInsertFaces?.Contains(face.FaceIndex) == true + || fineSection && face.CategoryId == (int)BuiltInCategory.OST_LightingFixtures + || keepDoorDepths && face.CategoryId == (int)BuiltInCategory.OST_Doors + || keepStairDepths && IsStairBodyCategory(face.CategoryId) + || keepComponentDepths && HasCoincidentComponents(face.CategoryId, cutOrigin == null) + || UsesDetailProfileDepth(face, index); + + bool UsesDetailProfileDepth(ProjectionFace face, int index) + { + int next = (index + 1) % face.Points.Count; + // Cut edges still share the cut-plane key and use the existing cut pens. + return keepDetailProfileDepths && face.Ring.Count == face.Points.Count + && IsVerticalDetailProfile(face.CategoryId, face.Points[index].X, face.Points[next].X) + && !IsCutEdge(face.Ring[index], face.Ring[next]); + } + + bool IsCutEdge(double[] a, double[] b) + { + if (cutOrigin == null) return false; + double da = (a[0] - cutOrigin[0]) * viewDir[0] + (a[1] - cutOrigin[1]) * viewDir[1] + + (a[2] - cutOrigin[2]) * viewDir[2]; + double db = (b[0] - cutOrigin[0]) * viewDir[0] + (b[1] - cutOrigin[1]) * viewDir[1] + + (b[2] - cutOrigin[2]) * viewDir[2]; + return Math.Abs(da) <= 1.0 && Math.Abs(db) <= 1.0; + } + + bool IsProjectedRailSeam(List<(int Face, int Vertex)> members, (double X, double Y) start, + (double X, double Y) end) => + members.All(member => IsRailingCategory(edgeFaces[member.Face].CategoryId)) + && members.GroupBy(member => + { + var face = edgeFaces[member.Face]; + return EdgeKey(face.Points, face.Ring, true, member.Vertex); + }).All(group => + { + var faces = group.Select(member => edgeFaces[member.Face]).ToArray(); + var first = faces[0]; + if (faces.Any(face => (face.Nx, face.Ny, face.Nz, face.Off) != (first.Nx, first.Ny, first.Nz, first.Off))) + return false; + // A railing and its embedded components can repeat both faces of one joint. + var sides = faces.Select(face => ProjectedSide(start, end, face.Points)).ToArray(); + return sides.Contains(-1) && sides.Contains(1); + }); + + ((long Ax, long Ay, long Bx, long By) Edge, long Start, long End) EdgeKey( + List<(double X, double Y)> points, List ring, bool preserveDepth, int index) + { + int next = (index + 1) % points.Count; + var a = points[index]; + var b = points[next]; + var edge = ProjectedEdgeKey(a.X, a.Y, b.X, b.Y); + if (!preserveDepth || ring.Count != points.Count) return (edge, 0, 0); + + // A far component can share a projection with a nearer one that covers it. + long da = (long)Math.Round(Project(ring[index], viewDir, 1) * 10); + long db = (long)Math.Round(Project(ring[next], viewDir, 1) * 10); + return edge.Ax == (long)Math.Round(a.X * 10) && edge.Ay == (long)Math.Round(a.Y * 10) + ? (edge, da, db) : (edge, db, da); + } + } + + private static bool IsRailingCategory(int categoryId) => + categoryId is (int)BuiltInCategory.OST_StairsRailing or (int)BuiltInCategory.OST_RailingTopRail; + + private static bool IsVerticalDetailProfile(int categoryId, double x1, double x2) => + Math.Abs(x1 - x2) < 1e-6 + && (IsRailingCategory(categoryId) + || categoryId is (int)BuiltInCategory.OST_StairsRailingBaluster or (int)BuiltInCategory.OST_CurtainWallMullions); + + private static bool ClipsAtBaluster(CollectedEdge edge, int maskCategory) => + maskCategory != (int)BuiltInCategory.OST_StairsRailingBaluster || IsRailingCategory(edge.CategoryId); + + private static bool HasCoincidentComponents(int categoryId, bool elevation) => + IsRailingCategory(categoryId) + || categoryId is (int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_CurtainWallMullions + || elevation && categoryId is (int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + + private static double? RailingClipDepth(CollectedEdge edge) => + !edge.IsCut && edge.ViewLineStyleId == 0 + && (IsRailingCategory(edge.CategoryId) + || edge.CategoryId is ((int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors)) + ? edge.NearDepth - 1 : null; + + private sealed record PlanarOcclusion(double Dx, double Dy, double OriginDepth, + List>? Openings, bool Transparent, bool ExactStairProjectionDepth) + { + internal double DepthAt(double x, double y) => OriginDepth + Dx * x + Dy * y; } /// Edges with their midpoint hidden behind nearer mass removed: an edge whose midpoint lies inside @@ -603,10 +2486,15 @@ internal static List DedupeEdges( /// on the boundary of the nearer face counts as inside (half a millimetre): stacked wall layers and window /// frames project their edges onto the silhouette of the mass in front, and the reference draws that /// silhouette once. - internal static List OccludeEdges( + private static List OccludeEdges( List<(List<(double X, double Y)> Points, double Depth, bool Outline)> faces, - List faceMinDepths, - List edges) + List<(double MinDepth, int ElementId, int? HostId, int CategoryId, + PlanarOcclusion? Plane)> faceOccluders, + List edges, bool keepWindowJambs, IReadOnlySet? roofInsertFaces = null, + IReadOnlyDictionary>? stairMaskFaces = null, + IReadOnlyDictionary? railingMaskDepths = null, + List? behindRailings = null, bool useDetailPlaneDepth = false, Func? stairAssembly = null, + IReadOnlyDictionary? furnitureCovers = null) { const int Cells = 128; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -642,35 +2530,143 @@ internal static List OccludeEdges( int gx = Math.Clamp((int)((mx - minX) / cellW), 0, Cells - 1); int gy = Math.Clamp((int)((my - minY) / cellH), 0, Cells - 1); bool hidden = false; + bool hiddenByRail = false; + var source = edge.FaceA >= 0 ? faceOccluders[edge.FaceA] : default; + bool isInsert = edge.CategoryId is (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + bool roofInsert = roofInsertFaces?.Contains(edge.FaceA) == true; + bool stairBody = IsStairBodyCategory(edge.CategoryId); + bool stairProjection = !edge.IsCut && (stairBody || IsRailingCategory(edge.CategoryId) + || edge.CategoryId == (int)BuiltInCategory.OST_StairsRailingBaluster); + bool horizontalTread = stairBody && !edge.IsCut && Math.Abs(edge.Y1 - edge.Y2) < 1e-6; + int assembly = horizontalTread ? stairAssembly?.Invoke(source.ElementId) ?? source.ElementId : 0; + double? stairDepth = !edge.IsCut && edge.ViewLineStyleId == 0 && !stairBody + ? edge.NearDepth : null; + double? railingDepth = railingMaskDepths != null ? RailingClipDepth(edge) : null; + double? furnitureDepth = furnitureCovers is { Count: > 0 } ? FurnitureClipDepth(edge) : null; var candidates = grid[gy * Cells + gx]; if (candidates != null) { foreach (int f in candidates) { if (f == edge.FaceA || f == edge.FaceB) continue; - // A window or door sits inside its host wall: the wall face in front of it (up to half a - // metre, the deepest realistic inset) must not hide it, or no window would ever ink — the - // hole is not decoded in the wall face. A genuinely separate mass further in front still - // hides it. - double clearance = 1.0; - if (edge.CategoryId == (int)BuiltInCategory.OST_Windows - || edge.CategoryId == (int)BuiltInCategory.OST_Doors) - clearance = 500.0; - if (faceMinDepths[f] >= edge.MidDepth - clearance) continue; - if (PointInPolygon(mx, my, faces[f].Points) - || DistToPolygon(mx, my, faces[f].Points) <= 0.5) { hidden = true; break; } + if (furnitureDepth is double lineDepth && furnitureCovers!.TryGetValue(f, out double farDepth) + && farDepth < lineDepth - 1) continue; + var (coverDepth, elementId, hostId, categoryId, plane) = faceOccluders[f]; + // The projected union already resolves overlaps within this mesh. + if (edge.SilhouetteOwnerId == elementId) continue; + if (stairDepth is double near && coverDepth < near - 1 && stairMaskFaces?.ContainsKey(f) == true) + continue; // This face clips the span after midpoint occlusion. + if (plane != null && (roofInsert && elementId == source.ElementId + || source.Plane != null && source.CategoryId == (int)BuiltInCategory.OST_ElectricalEquipment + && categoryId is ((int)BuiltInCategory.OST_ElectricalEquipment or (int)BuiltInCategory.OST_IOSModelGroups))) + { + if (plane.Transparent || plane.Openings?.Any(hole => PointInPolygon(mx, my, hole)) == true) continue; + coverDepth = plane.DepthAt(mx, my); + } + if (categoryId is (int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Windows + or (int)BuiltInCategory.OST_Doors && plane?.Openings is { Count: > 0 } openings) + { + if (openings.Any(hole => PointInPolygon(mx, my, hole))) continue; + coverDepth = plane.DepthAt(mx, my); + } + if (plane != null && (stairProjection && plane.ExactStairProjectionDepth + && (categoryId == (int)BuiltInCategory.OST_Walls + || assembly > 0 && Math.Abs(plane.Dx) > 1e-6 && Math.Abs(plane.Dy) < 1e-6 + && (elementId == source.ElementId || stairAssembly?.Invoke(elementId) == assembly)) + || useDetailPlaneDepth + && (IsStairBodyCategory(categoryId) + || categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors)))) + coverDepth = plane.DepthAt(mx, my); + if (elementId == source.HostId) + { + // shortcut: exempt the host wall until its openings are projected. + if (categoryId == (int)BuiltInCategory.OST_Walls || plane?.Openings?.Any(hole => PointInPolygon(mx, my, hole)) == true) continue; + if (plane != null) coverDepth = plane.DepthAt(mx, my); + } + // shortcut: keep the insert's inset detail until the occlusion pass handles glazing materials. + double clearance = !roofInsert && isInsert && elementId == source.ElementId ? 500.0 : 1.0; + if (coverDepth >= edge.MidDepth - clearance) continue; + var polygon = faces[f].Points; + if (!PointInPolygon(mx, my, polygon) && DistToPolygon(mx, my, polygon) > 0.5) continue; + // Ganged windows touch at a projected jamb, so the adjacent pane cannot hide that edge. + if (keepWindowJambs && edge.CategoryId == (int)BuiltInCategory.OST_Windows + && Math.Abs(edge.X2 - edge.X1) <= 0.1 + && categoryId == edge.CategoryId && elementId != source.ElementId + && hostId.HasValue && hostId == source.HostId + && ProjectedSide((edge.X1, edge.Y1), (edge.X2, edge.Y2), polygon) + * ProjectedSide((edge.X1, edge.Y1), (edge.X2, edge.Y2), faces[edge.FaceA].Points) == -1) + continue; + if (railingDepth is double limit && railingMaskDepths!.TryGetValue(f, out var far) + && far < limit && ClipsAtBaluster(edge, categoryId)) + { + hiddenByRail = true; + continue; + } + hidden = true; + break; } } - if (!hidden) kept.Add(edge); + if (hidden) continue; + if (hiddenByRail) behindRailings!.Add(edge); + else kept.Add(edge); } kept.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - return kept; + if (furnitureCovers is not { Count: > 0 }) return kept; + + // Keep the original order of coincident edges for the later merge. Only replace a jamb + // or opening mark when it encounters a nearer furniture face. + var furnitureMasks = furnitureCovers.Select(mask => + { + var polygon = faces[mask.Key].Points; + return (mask.Value, Polygon: polygon, Left: polygon.Min(p => p.X), Right: polygon.Max(p => p.X), + Bottom: polygon.Min(p => p.Y), Top: polygon.Max(p => p.Y)); + }).ToArray(); + return kept.SelectMany(ClipAtFurniture).ToList(); + + IEnumerable ClipAtFurniture(CollectedEdge edge) + { + if (FurnitureClipDepth(edge) is not double depth) return [edge]; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double bottom = Math.Min(edge.Y1, edge.Y2), top = Math.Max(edge.Y1, edge.Y2); + var covers = furnitureMasks.Where(mask => mask.Value < depth - 1 + && mask.Left <= right && mask.Right >= left && mask.Bottom <= top && mask.Top >= bottom) + .Select(mask => mask.Polygon).ToList(); + return covers.Count == 0 ? [edge] : VisibleTerrainEdges([edge], covers, [], + coverBoundary: false, preserveDashOrigin: true); + } + } + + private static double? FurnitureClipDepth(CollectedEdge edge) + { + if (edge.IsCut || edge.NearDepth is not double depth) return null; + if (edge.ViewLineStyleId > 0 || edge.CategoryId == (int)BuiltInCategory.OST_Windows + && Math.Abs(edge.X1 - edge.X2) < 1e-6 && Math.Abs(depth - edge.MidDepth) < 1e-6) + return depth; + return null; + } + + private static int ProjectedSide((double X, double Y) start, (double X, double Y) end, + List<(double X, double Y)> polygon) + { + double dx = end.X - start.X, dy = end.Y - start.Y; + double tolerance = 0.1 * Math.Sqrt(dx * dx + dy * dy); + int side = 0; + foreach (var (x, y) in polygon) + { + double cross = dx * (y - start.Y) - dy * (x - start.X); + int vertexSide = cross > tolerance ? 1 : cross < -tolerance ? -1 : 0; + if (vertexSide == 0) continue; + if (side != 0 && side != vertexSide) return 0; + side = vertexSide; + } + return side; } /// Merges overlapping collinear edges on one plane into their union: stacked wall layers and /// coincident faces ink the same stretch several times, while the reference draws it once. Only true /// overlaps merge (touching ends stay separate); the plane key keeps different depths apart. - internal static List MergeOverlaps(List edges) + internal static List MergeOverlaps(List edges, + Func? cutWidth = null) { var groups = new Dictionary<(long Ang, long Off, long Nx, long Ny, long Nz, long Pln), List>(); foreach (var edge in edges) @@ -699,6 +2695,28 @@ internal static List MergeOverlaps(List edges) double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); spans.Add((lo, hi, edge)); } + if (cutWidth != null && list.All(edge => edge.IsCut && edge.ViewLineStyleId == 0)) + { + var cuts = spans.Select(span => (span.Lo, span.Hi, span.Edge, Width: cutWidth(span.Edge))) + .OrderByDescending(span => span.Width).ToArray(); + if (cuts[0].Width > cuts[^1].Width) + { + // A wider pen covers only the part supplied by that cut, not the whole joined edge. + var ends = cuts.SelectMany(span => new[] { span.Lo, span.Hi }).Distinct().Order().ToArray(); + int owner = -1, start = 0; + for (int i = 0; i < ends.Length; i++) + { + int next = i + 1 == ends.Length ? -1 + : Array.FindIndex(cuts, span => span.Lo <= ends[i] && span.Hi >= ends[i + 1]); + if (next == owner) continue; + if (owner >= 0) + merged.Add(WithSpan(cuts[owner].Edge, ends[start], ends[i], horizontal)); + owner = next; + start = i; + } + continue; + } + } spans.Sort((a, b) => a.Lo.CompareTo(b.Lo)); double curLo = spans[0].Lo, curHi = spans[0].Hi, curDepth = spans[0].Edge.Depth; var cur = spans[0].Edge; @@ -727,61 +2745,652 @@ internal static List MergeOverlaps(List edges) /// drawing one board four times, a window jamb doubled by its frame). Only full duplicates collapse: a short /// edge on a long one stays (a head on a wall top), lines at different depths stay (a rail in front of its /// wall), and staggered layers stay. The nearest edge survives, the way the reference inks the visible one. - internal static List ConsolidateCoincident(List edges) + internal static List ConsolidateCoincident(List edges, + bool keepFineSectionProfiles = false, double elevationRailPenWidth = 0) + { + const double ToleranceMillimetres = 50.0; + var survivors = new List(edges.Count); + List? fineProfiles = null; + foreach (var edge in edges.OrderBy(e => e.MidDepth)) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double len = Math.Sqrt(dx * dx + dy * dy); + if (!(len > 1e-9)) continue; + bool horizontal = Math.Abs(dy) <= Math.Abs(dx); + double lo = horizontal ? Math.Min(edge.X1, edge.X2) : Math.Min(edge.Y1, edge.Y2); + double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); + bool absorbed = false; + foreach (var kept in survivors) + { + double kdx = kept.X2 - kept.X1, kdy = kept.Y2 - kept.Y1; + double klen = Math.Sqrt(kdx * kdx + kdy * kdy); + if (!(klen > 1e-9)) continue; + bool kHorizontal = Math.Abs(kdy) <= Math.Abs(kdx); + if (kHorizontal != horizontal) continue; + // Parallel within the tolerance: the perpendicular distance of both ends. + double sep = horizontal + ? Math.Max(Math.Abs(edge.Y1 - kept.Y1), Math.Abs(edge.Y2 - kept.Y2)) + : Math.Max(Math.Abs(edge.X1 - kept.X1), Math.Abs(edge.X2 - kept.X2)); + if (sep > ToleranceMillimetres) continue; + // The two sides of a cut tread or riser can be only 50 mm apart. + if (sep > 0.1 && keepFineSectionProfiles + && (edge.IsCut && IsStairBodyCategory(edge.CategoryId) || kept.IsCut && IsStairBodyCategory(kept.CategoryId))) continue; + if (Math.Abs(edge.MidDepth - kept.MidDepth) > ToleranceMillimetres) continue; + double klo = horizontal ? Math.Min(kept.X1, kept.X2) : Math.Min(kept.Y1, kept.Y2); + double khi = horizontal ? Math.Max(kept.X1, kept.X2) : Math.Max(kept.Y1, kept.Y2); + double overlap = Math.Min(hi, khi) - Math.Max(lo, klo); + double shorter = Math.Min(len, klen); + if (overlap < 0.8 * shorter) continue; + if (Math.Min(len, klen) < 0.8 * Math.Max(len, klen)) continue; + // At elevation scale, sub-pen-width boundaries of a rail read as one stroke. + bool separateElevationRail = elevationRailPenWidth > 0 && sep > elevationRailPenWidth + && (Math.Abs(dx) < 1e-6 && Math.Abs(kdx) < 1e-6 + || Math.Abs(dy) < 1e-6 && Math.Abs(kdy) < 1e-6); + if (sep > 0.1 && !edge.IsCut && !kept.IsCut + && (keepFineSectionProfiles && edge.CategoryId == (int)BuiltInCategory.OST_Doors + || IsRailingCategory(edge.CategoryId) && (keepFineSectionProfiles || separateElevationRail)) + && kept.CategoryId == edge.CategoryId + && edge.FaceA >= 0 && kept.FaceA >= 0 + && (edge.FaceA == kept.FaceA || edge.FaceA == kept.FaceB + || edge.FaceB >= 0 && (edge.FaceB == kept.FaceA || edge.FaceB == kept.FaceB))) + (fineProfiles ??= []).Add(edge); + absorbed = true; + break; + } + if (!absorbed) survivors.Add(edge); + } + survivors.Sort((left, right) => right.Depth.CompareTo(left.Depth)); + if (fineProfiles != null) + { + // Recover both edges of the same profile face without changing the model edge selection. + var inked = survivors.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in fineProfiles) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) + survivors.Add(edge); + } + return survivors; + } + + internal static bool HeaderOutlineIsBeforePlane(Element element, double[] direction, double planeDepth) + // An RPC outline can reach the view plane even when all its proxy triangles lie in front of it. + => element.BoundingBoxIsHeaderOutline && element.BoundingBox is { Length: 6 } bounds + && bounds.All(double.IsFinite) + && Enumerable.Range(0, 3).Sum(i => bounds[direction[i] < 0 ? i : i + 3] * direction[i]) + * FeetToMillimetres < planeDepth; + + internal static bool SpansSectionPlane(List faces, double[] direction, double planeDepth) + { + foreach (var face in faces) + { + if (face.OuterVertices is not { Count: >= 3 } vertices) continue; + bool before = false, beyond = false; + foreach (var vertex in vertices) + { + double depth = Project(vertex, direction); + before |= depth < planeDepth - 1e-6; + beyond |= depth > planeDepth + 1e-6; + if (before && beyond) return true; + } + } + return false; + } + + private static bool IsStairBodyCategory(int category) => category is + (int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRuns or (int)BuiltInCategory.OST_StairsTrisers; + + private static void AddRoofLayers(List output, + IEnumerable<(double X1, double Y1, double X2, double Y2, double Nx, double Ny, double Nz, + int TypeId, int CategoryId, double Depth)> chords, + List> rings, Internal.RawCompoundStructureLayer[] layers, + double[] right, double[] up, double[] direction, (double X0, double Y0, double X1, double Y1) crop, + RvtDocument document, List? hatches, double[]? viewOrigin) + { + var sides = chords.ToArray(); + var tops = sides.Where(side => side.Nz > 0.01).Take(3).ToArray(); + if (tops.Length is 0 or > 2) return; + // A common high end and eaves on opposite sides identify a single ridge. + if (tops is [var first, var second]) + { + if (rings.Count != 1) return; + double ridgeY = Math.Max(first.Y1, first.Y2); + double ridgeX = first.Y1 > first.Y2 ? first.X1 : first.X2; + double secondRidgeY = Math.Max(second.Y1, second.Y2); + double secondRidgeX = second.Y1 > second.Y2 ? second.X1 : second.X2; + if (Math.Abs(ridgeX - secondRidgeX) > 0.1 || Math.Abs(ridgeY - secondRidgeY) > 0.1 + || Math.Min(first.Y1, first.Y2) >= ridgeY - 0.1 + || Math.Min(second.Y1, second.Y2) >= ridgeY - 0.1 + || (first.X1 + first.X2 - 2 * ridgeX) * (second.X1 + second.X2 - 2 * ridgeX) >= 0) + return; + } + + var widths = layers.Select(layer => BitConverter.Int64BitsToDouble(layer.LayerWidthBits) + * FeetToMillimetres).ToArray(); + if (widths.Any(width => !(width is >= 0 and < 10000))) return; + double thickness = widths.Sum(); + var planes = new List<(double[] Normal, double Distance)>(); + foreach (var top in tops) + { + if (Math.Abs(top.Nx * direction[0] + top.Ny * direction[1] + top.Nz * direction[2]) >= 1e-6 + || sides.Where(bottom => top.Nx * bottom.Nx + top.Ny * bottom.Ny + top.Nz * bottom.Nz < -1 + 1e-6) + .Take(2).ToArray() is not [var bottom]) + return; + var normal = new[] { top.Nx * right[0] + top.Ny * right[1] + top.Nz * right[2], + top.Nx * up[0] + top.Ny * up[1] + top.Nz * up[2], 0d }; + double measured = (top.X1 - bottom.X1) * normal[0] + (top.Y1 - bottom.Y1) * normal[1]; + if (Math.Abs(thickness - measured) >= 0.1) return; + planes.Add((normal, top.X1 * normal[0] + top.Y1 * normal[1])); + } + + foreach (var ring in rings) + { + var profile = ring.Select(point => new[] { point.X, point.Y, 0d }).ToList(); + double offset = 0; + for (int layer = 0; layer < widths.Length; layer++) + { + double start = offset, width = widths[layer]; + offset += width; + if (width <= 0) continue; + + bool drawBoundary = layer < widths.Length - 1 && offset >= 0.01 && thickness - offset >= 0.01; + var grids = hatches != null && viewOrigin is { Length: 3 } + ? DetailAnnotations.CutGrids(document, layers[layer].RawMaterialId) : null; + if (!drawBoundary && grids == null) continue; + + for (int i = 0; i < planes.Count; i++) + { + var (normal, distance) = planes[i]; + if (grids != null) + { + var band = RoofMaterialBand(ring, planes[i], planes.Count == 2 ? planes[1 - i] : null, + start, offset); + if (band.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(band)) > 1e-6) + hatches!.Add(new(band, grids, Project(viewOrigin!, right), Project(viewOrigin!, up))); + } + if (!drawBoundary) continue; + var origin = new[] { normal[0] * (distance - offset), normal[1] * (distance - offset), 0d }; + foreach (var (a, b) in CutChords(profile, origin, normal)) + { + double x1 = a[0], y1 = a[1], x2 = b[0], y2 = b[1]; + if (planes.Count == 2) + { + var adjacent = planes[1 - i]; + double da = a[0] * adjacent.Normal[0] + a[1] * adjacent.Normal[1] - adjacent.Distance + offset; + double db = b[0] * adjacent.Normal[0] + b[1] * adjacent.Normal[1] - adjacent.Distance + offset; + if (da > 0 && db > 0) continue; + if (da > 0 || db > 0) + { + double t = da / (da - db); + double x = a[0] + (b[0] - a[0]) * t, y = a[1] + (b[1] - a[1]) * t; + if (da > 0) (x1, y1) = (x, y); + else (x2, y2) = (x, y); + } + } + if (ClipSegment(x1, y1, x2, y2, crop.X0, crop.Y0, crop.X1, crop.Y1, + out double ax, out double ay, out double bx, out double by)) + output.Add(new((ax, ay), (bx, by), (int)BuiltInCategory.OST_Roofs)); + } + } + } + } + } + + private static List<(double X, double Y)> RoofMaterialBand(List<(double X, double Y)> ring, + (double[] Normal, double Distance) plane, (double[] Normal, double Distance)? adjacent, double outer, double inner) + { + double Depth((double X, double Y) point) => plane.Distance - point.X * plane.Normal[0] - point.Y * plane.Normal[1]; + var band = ClipHalfPlane(ring, point => Depth(point) >= outer, point => Depth(point) - outer); + band = ClipHalfPlane(band, point => Depth(point) <= inner, point => inner - Depth(point)); + if (adjacent is { } other) + { + // The closest exterior plane owns each side of the ridge. + double RidgeDistance((double X, double Y) point) => + other.Distance - point.X * other.Normal[0] - point.Y * other.Normal[1] - Depth(point); + band = ClipHalfPlane(band, point => RidgeDistance(point) >= 0, RidgeDistance); + } + return band; + } + + private static CollectedEdge? ClipCollectedEdge(CollectedEdge edge, + (double X0, double Y0, double X1, double Y1) crop) + { + if (!ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, crop.X0, crop.Y0, crop.X1, crop.Y1, + out double x1, out double y1, out double x2, out double y2) + || (x1, y1) == (x2, y2)) return null; + return edge with { X1 = x1, Y1 = y1, X2 = x2, Y2 = y2 }; + } + + internal static List ResolveRoofWallCutJoins(List edges, + IReadOnlyList> roofs, IReadOnlyList> walls, + double depth, (long Nx, long Ny, long Nz, long Off) plane) + { + const double tolerance = 1e-5; + const int roofCategory = (int)BuiltInCategory.OST_Roofs; + const int wallCategory = (int)BuiltInCategory.OST_Walls; + var wallBoundaries = Boundaries(walls).ToList(); + var seams = new List(); + foreach (var roof in Boundaries(roofs)) + { + double dx = roof.X2 - roof.X1, dy = roof.Y2 - roof.Y1; + bool horizontal = Math.Abs(dx) >= Math.Abs(dy); + foreach (var wall in wallBoundaries) + { + // Counterclockwise rings put their interiors to the left. + if (dx * (wall.X2 - wall.X1) + dy * (wall.Y2 - wall.Y1) >= 0) continue; + if (CollinearOverlap(roof, wall, horizontal, tolerance) is { } overlap) + seams.Add(WithSpan(roof, overlap.Lo, overlap.Hi, horizontal)); + } + } + if (seams.Count == 0) return edges; + + var uniqueSeams = MergeOverlaps(seams) + .DistinctBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToList(); + var result = new List(edges.Count + uniqueSeams.Count); + foreach (var edge in edges) + { + if (edge.IsCut && edge.ViewLineStyleId == 0 && edge.CategoryId is roofCategory or wallCategory) + result.AddRange(UncoveredCollinearSpans(edge, uniqueSeams, tolerance)); + else + result.Add(edge); + } + result.AddRange(uniqueSeams); + return result; + + IEnumerable Boundaries(IReadOnlyList> rings) + { + foreach (var ring in rings) + { + bool counterclockwise = PlanPrinter.SignedArea(ring) > 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + if (!counterclockwise) (a, b) = (b, a); + yield return new(a.X, a.Y, b.X, b.Y, depth, depth, -1, -1, + plane.Nx, plane.Ny, plane.Nz, plane.Off, CategoryId: roofCategory); + } + } + } + } + + internal static IEnumerable TrimProjectedEdgesAtCuts(IReadOnlyList edges, + Func? coversProjection = null) + { + const double tolerance = 0.1; + var cuts = edges.Where(edge => edge.IsCut && (coversProjection?.Invoke(edge) ?? true)).ToList(); + foreach (var edge in edges) + { + if (edge.IsCut || edge.ViewLineStyleId > 0 || cuts.Count == 0) + yield return edge; + else + foreach (var span in UncoveredCollinearSpans(edge, cuts, tolerance)) + yield return span; + } + } + + private static (double Lo, double Hi)? CollinearOverlap( + CollectedEdge edge, CollectedEdge cover, bool horizontal, double tolerance) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (length <= tolerance) return null; + + double Distance(double x, double y) => Math.Abs((x - edge.X1) * dy - (y - edge.Y1) * dx) / length; + if (Distance(cover.X1, cover.Y1) > tolerance || Distance(cover.X2, cover.Y2) > tolerance) return null; + + double a = horizontal ? edge.X1 : edge.Y1, b = horizontal ? edge.X2 : edge.Y2; + double c = horizontal ? cover.X1 : cover.Y1, d = horizontal ? cover.X2 : cover.Y2; + double lo = Math.Max(Math.Min(a, b), Math.Min(c, d)); + double hi = Math.Min(Math.Max(a, b), Math.Max(c, d)); + return hi > lo ? (lo, hi) : null; + } + + private static IEnumerable UncoveredCollinearSpans( + CollectedEdge edge, IReadOnlyList covers, double tolerance) + { + bool horizontal = Math.Abs(edge.X2 - edge.X1) >= Math.Abs(edge.Y2 - edge.Y1); + double a = horizontal ? edge.X1 : edge.Y1, b = horizontal ? edge.X2 : edge.Y2; + double start = Math.Min(a, b), end = Math.Max(a, b); + var covered = covers.Where(cover => cover.MidDepth <= edge.MidDepth + tolerance) + .Select(cover => CollinearOverlap(edge, cover, horizontal, tolerance)) + .OfType<(double Lo, double Hi)>().OrderBy(span => span.Lo); + double cursor = start; + foreach (var span in covered) + { + if (span.Lo > cursor + tolerance) yield return WithSpan(edge, cursor, span.Lo, horizontal); + cursor = Math.Max(cursor, span.Hi); + if (cursor >= end) break; + } + if (cursor == start) yield return edge; + else if (end > cursor + tolerance) yield return WithSpan(edge, cursor, end, horizontal); + } + + private static CollectedEdge WithSpan(CollectedEdge edge, double lo, double hi, bool horizontal) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double denom = horizontal ? dx : dy; + if (Math.Abs(denom) < 1e-12) return edge; + double baseLo = horizontal ? edge.X1 : edge.Y1; + double t0 = (lo - baseLo) / denom, t1 = (hi - baseLo) / denom; + return edge with + { + X1 = edge.X1 + t0 * dx, + Y1 = edge.Y1 + t0 * dy, + X2 = edge.X1 + t1 * dx, + Y2 = edge.Y1 + t1 * dy, + }; + } + + internal static IEnumerable VisibleTerrainEdges(IEnumerable terrainEdges, + IEnumerable> polygons, List<(double From, double To)> pads, + double minimumLengthSquared = 0.01, bool coverBoundary = true, bool coverOppositeEdges = false, + IReadOnlyDictionary, List>>? openings = null, + bool preserveDashOrigin = false) + { + // Ground is background. Keep only its parts outside the opaque model polygons so covered lines + // do not remain as invisible strokes in the PDF. + var masks = polygons.Select(points => (Points: points, X0: points.Min(p => p.X), Y0: points.Min(p => p.Y), + X1: points.Max(p => p.X), Y1: points.Max(p => p.Y))).ToList(); + foreach (var edge in terrainEdges) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double lengthSquared = dx * dx + dy * dy; + if (lengthSquared < minimumLengthSquared) continue; + double crossTolerance = coverOppositeEdges ? 1e-5 * Math.Sqrt(lengthSquared) : 0; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double bottom = Math.Min(edge.Y1, edge.Y2), top = Math.Max(edge.Y1, edge.Y2); + var covered = new List<(double From, double To)>(); + // A building pad replaces the terrain within its footprint, at every height in the section. + foreach (var (from, to) in pads) + { + if (right <= from || left >= to) continue; + if (Math.Abs(dx) < 1e-9) + { + covered.Add((0, 1)); + break; + } + double t0 = (from - edge.X1) / dx, t1 = (to - edge.X1) / dx; + covered.Add((Math.Max(0, Math.Min(t0, t1)), Math.Min(1, Math.Max(t0, t1)))); + } + foreach (var (polygon, x0, y0, x1, y1) in masks) + { + if (x1 < left || x0 > right || y1 < bottom || y0 > top) continue; + var crossings = new List { 0, 1 }; + var holes = openings?.GetValueOrDefault(polygon); + AddCrossings(polygon); + if (holes != null) + foreach (var hole in holes) AddCrossings(hole); + crossings.Sort(); + for (int i = 1; i < crossings.Count; i++) + { + double from = crossings[i - 1], to = crossings[i]; + if (to - from < 1e-9) continue; + double mid = (from + to) / 2; + double x = edge.X1 + dx * mid, y = edge.Y1 + dy * mid; + if (PointInPolygon(x, y, polygon) && (coverBoundary || DistToPolygon(x, y, polygon) > 1e-5) + && holes?.Any(hole => PointInPolygon(x, y, hole)) != true) + covered.Add((from, to)); + } + + void AddCrossings(List<(double X, double Y)> ring) + { + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + double ex = b.X - a.X, ey = b.Y - a.Y; + double ax = a.X - edge.X1, ay = a.Y - edge.Y1; + if (coverOppositeEdges && dx * ex + dy * ey < 0) + { + double bx = b.X - edge.X1, by = b.Y - edge.Y1; + if (Math.Abs(ax * dy - ay * dx) <= crossTolerance && Math.Abs(bx * dy - by * dx) <= crossTolerance) + { + // Opposite boundary directions put material on both sides of their common span. + double from = Math.Max(0, (bx * dx + by * dy) / lengthSquared); + double to = Math.Min(1, (ax * dx + ay * dy) / lengthSquared); + if (to > from) covered.Add((from, to)); + continue; + } + } + double denominator = dx * ey - dy * ex; + if (Math.Abs(denominator) < 1e-9) continue; + double t = (ax * ey - ay * ex) / denominator; + double u = (ax * dy - ay * dx) / denominator; + if (t > 0 && t < 1 && u >= 0 && u <= 1) crossings.Add(t); + } + } + } + if (covered.Count == 0) + { + yield return edge; + continue; + } + double cursor = 0; + foreach (var (from, to) in covered.OrderBy(interval => interval.From)) + { + if (from > cursor + 1e-9) yield return Slice(cursor, from); + cursor = Math.Max(cursor, to); + } + if (cursor < 1 - 1e-9) yield return Slice(cursor, 1); + + CollectedEdge Slice(double from, double to) => edge with + { + X1 = edge.X1 + dx * from, Y1 = edge.Y1 + dy * from, + X2 = edge.X1 + dx * to, Y2 = edge.Y1 + dy * to, + UnclippedViewLine = preserveDashOrigin && edge.ViewLineStyleId > 0 && (from > 1e-9 || to < 1 - 1e-9) + ? edge.UnclippedViewLine ?? edge : edge.UnclippedViewLine, + }; + } + } + + private static IEnumerable> GroundSpans(TerrainHatch terrain, double baseY) + { + foreach (var edge in terrain.Profile) + { + if (Math.Abs(edge.X1 - edge.X2) < 1e-9 || baseY >= Math.Max(edge.Y1, edge.Y2)) continue; + double x1 = edge.X1, y1 = edge.Y1, x2 = edge.X2, y2 = edge.Y2; + if (y1 < baseY) + { + x1 += (x2 - x1) * (baseY - y1) / (y2 - y1); + y1 = baseY; + } + else if (y2 < baseY) + { + x2 += (x1 - x2) * (baseY - y2) / (y1 - y2); + y2 = baseY; + } + yield return [(x1, y1), (x2, y2), (x2, baseY), (x1, baseY)]; + } + } + + private static List>? ClosedSectionWithOpenings(IReadOnlyList faces, + double[] origin, double[] direction, double[] horizontal, double[] vertical) + { + if (faces.Any(face => face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } + || (face.InnerLoops?.Count ?? 0) > (face.InnerVertices?.Count ?? 0))) return null; + + var rings = ClosedSectionRings(faces, origin, direction, horizontal, vertical, + requireClosed: true, includeFaceOpenings: true).ToList(); + // shortcut: nested profiles need a cut mask with holes. + return rings.Count > 0 && !HasNestedSectionRings(rings) ? rings : null; + } + + private static bool HasNestedSectionRings(List> rings) => + rings.Any(ring => rings.Any(other => other != ring && PointInPolygon(ring[0].X, ring[0].Y, other))); + + private static HashSet? OutwardConvexStairFaces(GeometryData geometry) + { + if (geometry.BrepSolids == null) return null; + var outward = new HashSet(); + foreach (var solid in geometry.BrepSolids) + { + if (!solid.IsClosed || solid.FaceIndices.Count < 4 + || solid.FaceIndices.Any(index => (uint)index >= (uint)geometry.Faces.Count)) + continue; + var faces = solid.FaceIndices.Select(index => geometry.Faces[index]).ToArray(); + if (faces.Any(face => !face.PlaneSurface || face.OuterVertices is not { Count: >= 3 })) + continue; + + var vertices = faces.SelectMany(face => face.OuterVertices!).ToArray(); + // The original face normals point outward only when the shell lies behind every supporting plane. + if (faces.All(face => + { + double depth = Project(face.OuterVertices![0], face.Normal); + return vertices.All(point => Project(point, face.Normal) <= depth + 1e-6); + })) + outward.UnionWith(faces); + } + return outward.Count > 0 ? outward : null; + } + + internal static IEnumerable> ClosedSectionRings(IReadOnlyList faces, + double[] origin, double[] direction, double[] horizontal, double[] vertical, bool requireClosed = false, + bool includeFaceOpenings = false) + { + if (!includeFaceOpenings && faces.Any(face => face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 })) + yield break; + var points = new Dictionary<(long, long), (double X, double Y)>(); + var neighbors = new Dictionary<(long, long), HashSet<(long, long)>>(); + foreach (var face in faces) + { + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } corners) continue; + var ring = corners.Select(p => new[] { p[0] * FeetToMillimetres, p[1] * FeetToMillimetres, + p[2] * FeetToMillimetres }).ToList(); + var chords = CutChords(ring, origin, direction); + if (includeFaceOpenings && face.InnerVertices is { Count: > 0 } holes) + { + var openings = holes.SelectMany(hole => CutChords(hole.Select(p => new[] + { p[0] * FeetToMillimetres, p[1] * FeetToMillimetres, p[2] * FeetToMillimetres }).ToList(), + origin, direction)).ToList(); + if (openings.Count > 0) + { + var trimmed = SubtractFaceOpeningChords(chords, openings); + if (trimmed == null) yield break; + chords = trimmed; + } + } + foreach (var (from, to) in chords) + { + var a = (X: Project(from, horizontal, 1), Y: Project(from, vertical, 1)); + var b = (X: Project(to, horizontal, 1), Y: Project(to, vertical, 1)); + var ka = ((long)Math.Round(a.X * 10), (long)Math.Round(a.Y * 10)); + var kb = ((long)Math.Round(b.X * 10), (long)Math.Round(b.Y * 10)); + if (ka == kb) continue; + if (points.TryAdd(ka, a)) neighbors.Add(ka, []); + if (points.TryAdd(kb, b)) neighbors.Add(kb, []); + neighbors[ka].Add(kb); + neighbors[kb].Add(ka); + } + } + if (requireClosed && neighbors.Values.Any(end => end.Count != 2)) yield break; + var visited = new HashSet<(long, long)>(); + foreach (var start in points.Keys) + { + if (!visited.Add(start) || neighbors[start].Count != 2) continue; + var ring = new List<(double X, double Y)> { points[start] }; + var current = neighbors[start].First(); + var previous = start; + while (neighbors[current].Count == 2 && visited.Add(current)) + { + ring.Add(points[current]); + var next = neighbors[current].First(neighbor => neighbor != previous); + previous = current; + current = next; + } + if (current == start && ring.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(ring)) > 1e-6) + yield return ring; + } + } + + private static List<(double[] A, double[] B)>? SubtractFaceOpeningChords( + List<(double[] A, double[] B)> outer, List<(double[] A, double[] B)> openings) + { + if (outer.Count == 0) return null; + // Every crossing of a planar face lies on one line. Sort its endpoints along the dominant axis. + var (start, end) = outer[0]; + int axis = Enumerable.Range(0, 3).MaxBy(i => Math.Abs(end[i] - start[i])); + var holes = openings.Select(chord => Ascending(chord.A, chord.B)).OrderBy(hole => hole.Low[axis]).ToList(); + var result = new List<(double[] A, double[] B)>(); + int matched = 0; + foreach (var (a, b) in outer) + { + var (low, high) = Ascending(a, b); + var cursor = low; + foreach (var (first, last) in holes) + { + if (first[axis] < low[axis] || last[axis] > high[axis]) continue; + if (first[axis] < cursor[axis]) return null; + if (first[axis] > cursor[axis]) result.Add((cursor, first)); + cursor = last; + matched++; + } + if (cursor[axis] < high[axis]) result.Add((cursor, high)); + } + return matched == holes.Count ? result : null; + + (double[] Low, double[] High) Ascending(double[] a, double[] b) => a[axis] <= b[axis] ? (a, b) : (b, a); + } + + internal static IEnumerable OutlineJoinedRings(List> rings, int category, + bool coverOppositeEdges = false, bool retainSource = false, bool snapEndpoints = true) { - const double ToleranceMillimetres = 50.0; - var survivors = new List(edges.Count); - foreach (var edge in edges.OrderBy(e => e.MidDepth)) + var edges = new Dictionary<((double X, double Y) A, (double X, double Y) B), (CollectedEdge Edge, int Sides)>(); + for (int ringIndex = 0; ringIndex < rings.Count; ringIndex++) { - double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; - double len = Math.Sqrt(dx * dx + dy * dy); - if (!(len > 1e-9)) continue; - bool horizontal = Math.Abs(dy) <= Math.Abs(dx); - double lo = horizontal ? Math.Min(edge.X1, edge.X2) : Math.Min(edge.Y1, edge.Y2); - double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); - bool absorbed = false; - foreach (var kept in survivors) + var ring = rings[ringIndex]; + for (int i = 0; i < ring.Count; i++) { - double kdx = kept.X2 - kept.X1, kdy = kept.Y2 - kept.Y1; - double klen = Math.Sqrt(kdx * kdx + kdy * kdy); - if (!(klen > 1e-9)) continue; - bool kHorizontal = Math.Abs(kdy) <= Math.Abs(kdx); - if (kHorizontal != horizontal) continue; - // Parallel within the tolerance: the perpendicular distance of both ends. - double sep = horizontal - ? Math.Max(Math.Abs(edge.Y1 - kept.Y1), Math.Abs(edge.Y2 - kept.Y2)) - : Math.Max(Math.Abs(edge.X1 - kept.X1), Math.Abs(edge.X2 - kept.X2)); - if (sep > ToleranceMillimetres) continue; - if (Math.Abs(edge.MidDepth - kept.MidDepth) > ToleranceMillimetres) continue; - double klo = horizontal ? Math.Min(kept.X1, kept.X2) : Math.Min(kept.Y1, kept.Y2); - double khi = horizontal ? Math.Max(kept.X1, kept.X2) : Math.Max(kept.Y1, kept.Y2); - double overlap = Math.Min(hi, khi) - Math.Max(lo, klo); - double shorter = Math.Min(len, klen); - if (overlap < 0.8 * shorter) continue; - if (Math.Min(len, klen) < 0.8 * Math.Max(len, klen)) continue; - absorbed = true; - break; + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + var start = snapEndpoints ? (Math.Round(a.X * 10), Math.Round(a.Y * 10)) : a; + var end = snapEndpoints ? (Math.Round(b.X * 10), Math.Round(b.Y * 10)) : b; + if (start == end) continue; + // Counterclockwise rings put their interiors on the left of each directed edge. + bool forward = start.CompareTo(end) < 0; + var key = forward ? (start, end) : (end, start); + int side = forward ? 1 : 2; + if (edges.TryGetValue(key, out var existing)) + edges[key] = (existing.Edge, existing.Sides | side); + else + edges.Add(key, (new(a.X, a.Y, b.X, b.Y, 0, 0, -1, -1, 0, 0, 0, 0, false, category) + { SourceRingEdge = retainSource ? (ringIndex, i) : null }, side)); } - if (!absorbed) survivors.Add(edge); } - survivors.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - return survivors; + return VisibleTerrainEdges(edges.Values.Where(e => e.Sides != 3).Select(e => e.Edge), rings, [], + coverBoundary: false, coverOppositeEdges: coverOppositeEdges); } - private static CollectedEdge WithSpan(CollectedEdge edge, double lo, double hi, bool horizontal) + private static double Project(double[] point, double[] basis, double units = FeetToMillimetres) => + (point[0] * basis[0] + point[1] * basis[1] + point[2] * basis[2]) * units; + + private static IEnumerable SiteWireEdges( + List<(List Points, double Facing)> faces, double[] horizontal, double[] vertical, + double[] direction, double planeDepth, bool cutMesh) { - double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; - double denom = horizontal ? dx : dy; - if (Math.Abs(denom) < 1e-12) return edge; - double baseLo = horizontal ? edge.X1 : edge.Y1; - double t0 = (lo - baseLo) / denom, t1 = (hi - baseLo) / denom; - return edge with + var edges = new HashSet<(long Ax, long Ay, long Bx, long By)>(); + foreach (var (points, facing) in faces) { - X1 = edge.X1 + t0 * dx, - Y1 = edge.Y1 + t0 * dy, - X2 = edge.X1 + t1 * dx, - Y2 = edge.Y1 + t1 * dy, - }; + if (!cutMesh && facing >= 0) continue; + for (int i = 0; i < points.Count; i++) + { + var a = points[i]; + var b = points[(i + 1) % points.Count]; + double da = Project(a, direction, 1) - planeDepth, db = Project(b, direction, 1) - planeDepth; + if (da < 0 && db < 0) continue; + double ax = Project(a, horizontal, 1), ay = Project(a, vertical, 1); + double bx = Project(b, horizontal, 1), by = Project(b, vertical, 1); + if (da < 0 || db < 0) + { + double t = da / (da - db); + double x = ax + t * (bx - ax), y = ay + t * (by - ay); + if (da < 0) { ax = x; ay = y; } + else { bx = x; by = y; } + } + var key = ProjectedEdgeKey(ax, ay, bx, by); + if (key.Ax == key.Bx && key.Ay == key.By || !edges.Add(key)) continue; + yield return new CollectedEdge(ax, ay, bx, by, 0, 0, -1, -1, 0, 0, 0, 0, false, + (int)BuiltInCategory.OST_Entourage); + } + } } private static bool PointInPolygon(double x, double y, List<(double X, double Y)> polygon) @@ -798,9 +3407,13 @@ private static bool PointInPolygon(double x, double y, List<(double X, double Y) } /// The distance from a point to the boundary of a polygon, in the polygon's units. - private static double DistToPolygon(double x, double y, List<(double X, double Y)> polygon) + private static double DistToPolygon(double x, double y, List<(double X, double Y)> polygon) => + Math.Sqrt(ClosestPolygonPoint(x, y, polygon).DistanceSquared); + + private static (double X, double Y, double DistanceSquared) ClosestPolygonPoint( + double x, double y, List<(double X, double Y)> polygon) { - double best = double.PositiveInfinity; + var best = (X: x, Y: y, DistanceSquared: double.PositiveInfinity); for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) { var (ax, ay) = polygon[j]; @@ -810,8 +3423,8 @@ private static double DistToPolygon(double x, double y, List<(double X, double Y double t = lengthSquared > 1e-18 ? ((x - ax) * dx + (y - ay) * dy) / lengthSquared : 0; t = Math.Clamp(t, 0, 1); double px = ax + t * dx, py = ay + t * dy; - double dist = Math.Sqrt((x - px) * (x - px) + (y - py) * (y - py)); - if (dist < best) best = dist; + double distSquared = (x - px) * (x - px) + (y - py) * (y - py); + if (distSquared < best.DistanceSquared) best = (px, py, distSquared); } return best; } @@ -865,7 +3478,8 @@ internal static void AddElevationPage(PdfDocument pdf, RvtDocument document, Ele double m = options.MarginMillimetres; page.DrawRectangle(m, m, paper.WidthMillimetres - 2 * m, paper.HeightMillimetres - 2 * m, 0.25); } - DrawContent(page, content, scale, offsetX, offsetY, view.Direction == "section" ? 0.82 : 1, document); + DrawContent(page, content, scale, offsetX, offsetY, view.Direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: document.RawData.UnshadedHiddenLineViews?.Contains(view.ViewId) == true); if (pdf.Font != null) { page.DrawText(view.Name, options.MarginMillimetres + 2, paper.HeightMillimetres - options.MarginMillimetres - 6, 4); @@ -890,7 +3504,7 @@ internal static void AddElevationPage(PdfDocument pdf, RvtDocument document, Ele return result; } - private static List<(double X, double Y)> ClipHalfPlane(List<(double X, double Y)> polygon, + internal static List<(double X, double Y)> ClipHalfPlane(List<(double X, double Y)> polygon, Func<(double X, double Y), bool> inside, Func<(double X, double Y), double> distance) { var result = new List<(double X, double Y)>(polygon.Count + 2); @@ -920,7 +3534,7 @@ internal static void AddLayerLines( RvtDocument document, List output, double[] viewDir, double[] horiz, double[] vert, - long pnx, long pny, long pnz, long poff) + long pnx, long pny, long pnz, long poff, IReadOnlySet? sectionedLayerChords = null) { var stacks = new Dictionary(); foreach (var chord in raw) @@ -953,6 +3567,8 @@ internal static void AddLayerLines( { for (int b = a + 1; b < cand.Count; b++) { + if (sectionedLayerChords?.Contains(cand[a]) == true + || sectionedLayerChords?.Contains(cand[b]) == true) continue; var first = raw[cand[a]]; var second = raw[cand[b]]; if (first.TypeId != second.TypeId) continue; @@ -1034,45 +3650,41 @@ internal static void AddLayerLines( } } - /// The part of a 3D ring whose projection lies inside a rectangle (the crop of a detail), with the - /// crossing points interpolated in 3D so the ring keeps a vertex per projected point: the cut test reads the - /// ring, and a projected-only clip lost that correspondence. - internal static List ClipToWindow3(List ring, double[] horizontal, double[] vertical, - double left, double right, double bottom, double top) + /// Clips a face for painting and occlusion, retaining which edges came from its perimeter. + private static (List Ring, bool[] IncomingEdges) ClipToWindow3(List ring, + double[] horizontal, double[] vertical, double left, double right, double bottom, double top) { - double U(double[] p) => p[0] * horizontal[0] + p[1] * horizontal[1] + p[2] * horizontal[2]; - double V(double[] p) => p[0] * vertical[0] + p[1] * vertical[1] + p[2] * vertical[2]; - var result = ClipHalfPlane3(ring, U, u => u - left); - result = ClipHalfPlane3(result, U, u => right - u); - result = ClipHalfPlane3(result, V, v => v - bottom); - return ClipHalfPlane3(result, V, v => top - v); + var vertices = ring.Select(point => (Point: point, IncomingEdge: true)).ToList(); + vertices = ClipHalfPlane3(vertices, point => Project(point, horizontal, 1) - left); + vertices = ClipHalfPlane3(vertices, point => right - Project(point, horizontal, 1)); + vertices = ClipHalfPlane3(vertices, point => Project(point, vertical, 1) - bottom); + vertices = ClipHalfPlane3(vertices, point => top - Project(point, vertical, 1)); + return (vertices.Select(vertex => vertex.Point).ToList(), vertices.Select(vertex => vertex.IncomingEdge).ToArray()); } - /// Clips a 3D ring by one half-plane of its projected coordinates: is - /// positive inside, so the crossing parameter is da / (da - db) and the new vertex interpolates in 3D. - /// - private static List ClipHalfPlane3(List ring, Func coordinate, - Func distance) + internal static List<(double[] Point, bool IncomingEdge)> ClipHalfPlane3( + List<(double[] Point, bool IncomingEdge)> ring, Func distance) { - var result = new List(ring.Count + 2); + var result = new List<(double[] Point, bool IncomingEdge)>(ring.Count + 2); for (int i = 0; i < ring.Count; i++) { var a = ring[i]; var b = ring[(i + 1) % ring.Count]; - double da = distance(coordinate(a)), db = distance(coordinate(b)); + double da = distance(a.Point), db = distance(b.Point); bool insideA = da >= 0, insideB = db >= 0; if (insideA) result.Add(a); - if (insideA != insideB) - { - double t = da / (da - db); - result.Add([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, - a[2] + (b[2] - a[2]) * t]); - } + if (insideA == insideB) continue; + + double t = da / (da - db); + var from = a.Point; + var to = b.Point; + // Along the crop boundary the entrance follows the previous exit across an artificial edge. + result.Add(([from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t, + from[2] + (to[2] - from[2]) * t], insideA && b.IncomingEdge)); } return result; } - internal static bool ClipSegment(double x0, double y0, double x1, double y1, double rx0, double ry0, double rx1, double ry1, out double cx0, out double cy0, out double cx1, out double cy1) @@ -1156,7 +3768,7 @@ internal static bool ClipSegment(double x0, double y0, double x1, double y1, /// The part of a polygon that stands behind the cutting plane (the side the view direction points /// to), the plane crossing a polygon adding the points where it crosses the plane. - private static List ClipBehind(List polygon, double[] origin, double[] direction) + internal static List ClipBehind(List polygon, double[] origin, double[] direction) { var result = new List(polygon.Count + 2); for (int i = 0; i < polygon.Count; i++) @@ -1190,10 +3802,15 @@ internal static List SectionMarks(RvtDocument document, int? viewportViewId = null, double? viewportScaleDenominator = null) { var marks = new List(); + var hidden = viewportViewId is int planId ? document.RawData.ViewHiddenElements?.GetValueOrDefault(planId) : null; + var planExtents = viewportViewId is int ownerId + && document.GetElement(ownerId) is { ViewAnnotationCropActive: false, ViewCrop: { Right: [1, 0, 0], Up: [0, 1, 0] } } + && document.RawData.DatumExtents?.GetValueOrDefault(ownerId) is { Normal: [0, 0, -1] } savedExtents + ? savedExtents.Sections : null; foreach (var view in document.Elements) { if (view.CategoryId != (int)BuiltInCategory.OST_Views) continue; - if (view.RootClassName is not ("DBViewSection" or "DBViewElevation")) continue; + if (view.RootClassName is not ("DBViewSection" or "DBViewElevation") || hidden?.Contains(view.Id) == true) continue; string name = view.Name ?? ""; if (!name.Contains("section", StringComparison.OrdinalIgnoreCase)) continue; if (view.ViewOrigin is not { Length: 3 } origin || view.ViewDirection is not { Length: 3 } direction @@ -1203,7 +3820,7 @@ internal static List SectionMarks(RvtDocument document, // section view with no decoded extent (no viewer record) leaves no trace, the way the // reference draws none for the Architectural Section (viewer -1, no extent record) while // rvt-prt draws traces only from Section m_frontCut extents. - if (view.SectionViewerId is not int viewerId || viewerId <= 0 + if (view.SectionViewerId is not int viewerId || viewerId <= 0 || hidden?.Contains(viewerId) == true || document.RawData.SectionViews?.TryGetValue(viewerId, out var section) != true) continue; // A callout of another view marks that view, not the plan; a finer-scale-only section @@ -1231,19 +3848,13 @@ internal static List SectionMarks(RvtDocument document, // The file's front-cut polyline is the true trace (a jogged section draws its jogs); without a // decoded extent the mark stays a straight ray through the plane origin, as before. List<(double X, double Y)> points; - bool bounded; + bool bounded, usesPlanExtent = false; if (section.FrontCut is { Count: >= 2 } cut) { points = cut.Select(p => (p[0] * FeetToMillimetres, p[1] * FeetToMillimetres)).ToList(); - // A measured per-view correction, in model millimetres: the reference export places the - // Longitudinal Section's mark 3,090 mm along +X from its decoded front cut while the - // Building Section's sits exactly on its own (control: both land at x = 592.1 pt). The - // shift matches no stored field — m_pntForViewData equals the first front-cut point, - // m_rotOffset.x is half the cut length, and the view origin (3,280 mm) is 190 mm away, - // nine times the measurement error — so it stays a measured constant, keyed by view name - // so it survives the id-shifted fixture. - if (MeasuredSectionTraceOffsets.ByViewName.TryGetValue(name, out var shift)) - points = points.Select(p => (p.X + shift.Dx, p.Y + shift.Dy)).ToList(); + if (planExtents?.GetValueOrDefault(viewerId) is { } extent && extent.SegmentCount == points.Count - 1 + && document.RawData.SectionTraceOrigins?.TryGetValue(viewerId, out var traceOrigin) == true) + usesPlanExtent = ApplyPlanSectionExtent(points, ux, uy, traceOrigin, extent); bounded = true; } else if (section.FrontCut != null) @@ -1271,14 +3882,72 @@ internal static List SectionMarks(RvtDocument document, return Math.Abs(mark.Points[0].X - sx) < 50 && Math.Abs(mark.Points[0].Y - sy) < 50 && Math.Abs((mdx * sdx + mdy * sdy) / (mlen * slen)) > 0.99; })) continue; - marks.Add(new SectionMark(points, bounded, name)); + marks.Add(new SectionMark(points, bounded, name, view.Id, usesPlanExtent)); } return marks; } + private static bool ApplyPlanSectionExtent(List<(double X, double Y)> points, double ux, double uy, + (double X, double Y) origin, Parsing.TfBlockDeserializer.SectionTraceExtent extent) + { + // View extents are distances along the section axis from its stored trace origin. + // Move the outer endpoints along their own legs so the jogs keep their model positions. + double zero = (origin.X * ux + origin.Y * uy) * FeetToMillimetres; + double first = zero + extent.Start * FeetToMillimetres; + double last = zero + extent.End * FeetToMillimetres; + double startLeg = Along(points[1]) - Along(points[0]); + double endLeg = Along(points[^1]) - Along(points[^2]); + if (!(startLeg > 0 && endLeg > 0 && first < Along(points[1]) && last > Along(points[^2]) + && Math.Abs(Cross(points[0]) - Cross(points[1])) < 1e-6 + && Math.Abs(Cross(points[^2]) - Cross(points[^1])) < 1e-6)) return false; + + points[0] = Extend(points[0], first); + points[^1] = Extend(points[^1], last); + return true; + + double Along((double X, double Y) p) => p.X * ux + p.Y * uy; + double Cross((double X, double Y) p) => p.X * uy - p.Y * ux; + (double X, double Y) Extend((double X, double Y) p, double distance) + { + double delta = distance - Along(p); + return (p.X + delta * ux, p.Y + delta * uy); + } + } + internal static void DrawContent(PdfPage page, ElevationContent content, double scale, double originX, double originY, double faceFill = 1, RvtDocument? document = null, - (double X0, double Y0, double X1, double Y1)? clipRect = null) + (double X0, double Y0, double X1, double Y1)? clipRect = null, bool drawNativeDatums = true, + bool unshadedHiddenLine = false) + { + if (content.SectionBands is { } bands) + { + var crop = clipRect ?? (content.MinX, content.MinY, content.MaxX, content.MaxY); + foreach (var band in bands) + { + double left = Math.Max(crop.Item1, band.Left), right = Math.Min(crop.Item3, band.Right); + if (right <= left) continue; + DrawModel(page, band.Content, scale, originX + (band.Content.MinX - content.MinX) / scale, + originY + (band.Content.MinY - content.MinY) / scale, faceFill, document, + (left, crop.Item2, right, crop.Item4), unshadedHiddenLine); + } + } + else + DrawModel(page, content, scale, originX, originY, faceFill, document, clipRect, unshadedHiddenLine); + + DrawFallbackDatums(page, content, scale, originX, originY, document, clipRect); + if (drawNativeDatums) + { + DrawNativeDatums(page, content, scale, originX, originY, document, clipRect); + CircularAnnotations.Draw(page, document, content.AnnotationSymbols ?? [], scale, + x => (x - content.MinX) / scale + originX, y => (y - content.MinY) / scale + originY); + } + } + + private const double DefaultOutlinePen = 0.2; + + private static void DrawModel(PdfPage page, ElevationContent content, double scale, double originX, + double originY, double faceFill, RvtDocument? document, + (double X0, double Y0, double X1, double Y1)? clipRect, bool unshadedHiddenLine) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; @@ -1287,7 +3956,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double // projection pen. Only the edges the cut created ink cut; the projected edges of a section ink thin // like the reference does. bool isSection = faceFill < 1; - double faceLine = 0.2, projLine = 0.1; + double faceLine = DefaultOutlinePen, projLine = 0.1; int penScale = (int)Math.Round(scale); if (document != null) { @@ -1300,12 +3969,125 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double if (!isSection) projLine = faceLine; double clipX0 = clipRect?.X0 ?? content.MinX, clipY0 = clipRect?.Y0 ?? content.MinY; double clipX1 = clipRect?.X1 ?? content.MaxX, clipY1 = clipRect?.Y1 ?? content.MaxY; - // The faded site behind the building: the plants and the ground as light shapes without outlines. - foreach (var (contextPoints, _) in content.Context) - page.DrawPolyline(contextPoints.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, 0.9); + var groundPolygons = new List>(); + if (content.GroundHatch is { } terrain && terrain.BaseY < clipY1) + { + double baseY = Math.Max(terrain.BaseY, clipY0); + foreach (var span in GroundSpans(terrain, baseY)) + { + var polygon = ClipToWindow(span, clipX0, clipX1, baseY, clipY1); + if (polygon.Count >= 3) groundPolygons.Add(polygon.Select(p => (ToX(p.X), ToY(p.Y))).ToList()); + } + } + double groundPen = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_TopographySurface, true, penScale, out var soilPen) + ? soilPen : 0.1; + var groundTiles = content.GroundHatch is { } tiledGround && groundPolygons.Count > 0 + ? FillHatch.DraftingTiles(tiledGround.Grids, ToX(tiledGround.AnchorX), ToY(tiledGround.AnchorY), groundPen) : null; + if (content.SkyGradient is { } gradient) + { + if (clipY1 > 0) + { + double bottom = Math.Max(0, clipY0); + var horizon = Color(gradient.Horizon); + var sky = Color(gradient.Sky); + double t = bottom / clipY1; + page.FillVerticalGradient(ToX(clipX0), ToY(bottom), (clipX1 - clipX0) / scale, (clipY1 - bottom) / scale, + new PdfColor(horizon.R + (sky.R - horizon.R) * t, horizon.G + (sky.G - horizon.G) * t, + horizon.B + (sky.B - horizon.B) * t), sky); + } + if (clipY0 < 0 && gradient.Ground is int groundColor) + { + double top = Math.Min(0, clipY1); + page.DrawPolyline([(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(top)), (ToX(clipX0), ToY(top))], 0, true, Color(groundColor)); + } + + static PdfColor Color(int packed) => new((packed & 255) / 255d, ((packed >> 8) & 255) / 255d, + (packed >> 16) / 255d); + } + // In opaque hidden line, the site surface covers the gradient behind the building. + var terrainShadows = new List>(); + double terrainShadowFill = 1; + foreach (var (contextPoints, _, isTerrain) in content.Context) + { + var points = clipRect.HasValue ? ClipToWindow(contextPoints, clipX0, clipX1, clipY0, clipY1) : contextPoints; + if (points.Count < 3) continue; + var polygon = points.Select(point => (X: ToX(point.X), Y: ToY(point.Y))).ToList(); + double fill = isTerrain && content.SkyGradient != null ? 1 : 0.9; + page.DrawPolyline(polygon, 0, true, fill); + if (content.CastShadows?.GetValueOrDefault(contextPoints) is not { } shadow) continue; + double winding = Math.Sign(PlanPrinter.SignedArea(points)); + if (winding == 0) continue; + var sides = new List<(double X, double Y, double C)>(points.Count); + for (int i = 0; i < points.Count; i++) + { + var a = points[i]; + var b = points[(i + 1) % points.Count]; + double x = (a.Y - b.Y) * winding, y = (b.X - a.X) * winding; + sides.Add((x, y, -x * a.X - y * a.Y)); + } + if (shadow.Openings.Count > 0 || sides.Any(side => points.Any(p => + side.X * p.X + side.Y * p.Y + side.C < -0.01))) + { + DrawShadow(contextPoints, polygon, fill); + continue; + } + foreach (var ring in shadow.Rings) + { + var clipped = ring; + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + clipped = ClipHalfPlane(clipped, p => Distance(p) >= 0, Distance); + } + if (clipped.Count >= 3) terrainShadows.Add(clipped.Select(p => (ToX(p.X), ToY(p.Y))).ToList()); + } + terrainShadowFill = fill * shadow.Light; + } + if (terrainShadows.Count > 0) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(terrainShadows, terrainShadowFill); + page.EndClip(); + } + if (content.SiteSilhouettes is { } silhouettes) + { + var background = silhouettes.Where(ring => content.ForegroundSite?.Sources.Contains(ring) != true).ToList(); + var rings = background.Select(ring => ClipToWindow(ring, clipX0, clipX1, clipY0, clipY1)) + .Where(ring => ring.Count >= 3).Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()); + double fill = content.SkyGradient != null ? 1 : 0.9; + page.FillPolygonUnion(rings, fill); + if (content.PlantTones is { } shades) + foreach (var (gray, visible) in shades) + page.FillPolygonUnion(visible.Select(ring => ClipToWindow(ring, clipX0, clipX1, clipY0, clipY1)) + .Where(ring => ring.Count >= 3).Select(ToPage), gray / 255.0); + if (content.CastShadows != null) + { + var shadedPlants = background.Select(ring => content.CastShadows.GetValueOrDefault(ring)) + .OfType().ToList(); + if (shadedPlants.Count > 0) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(shadedPlants.SelectMany(shadow => shadow.Rings) + .Select(ring => ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()), + fill * shadedPlants[0].Light); + page.EndClip(); + } + } + } + var sectionMasks = content.GroundHatch?.SectionMasks; + if (isSection && groundTiles != null && sectionMasks == null) DrawGroundTiles(groundTiles); // The faces only fill, far to near, so nearer mass covers what stands behind it; the shared edge // set below inks the visible lines, without the triangulation diagonals. A crop rectangle drops // the faces wholly outside it and clips the ones crossing it, so only the crop is drawn. + // shortcut: use the saved opaque base in sections, until local ambient shadows are supported. + double surfaceFill = unshadedHiddenLine || content.OpaqueSection ? 1 : faceFill; + var surfaceTiles = new Dictionary, List?>(); + var surfaceHatches = content.Hatch; foreach (var (points, _, _) in content.Faces) { var pagePoints = points; @@ -1324,30 +4106,407 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double if (pagePoints.Count < 3) continue; } } - page.DrawPolyline(pagePoints.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, faceFill); + var polygon = pagePoints.Select(point => (X: ToX(point.X), Y: ToY(point.Y))).ToList(); + var modelHatch = content.ModelHatches?.GetValueOrDefault(points); + double fill = modelHatch != null ? 1 : surfaceFill; + double shadowBase = surfaceFill; + if (content.FaceFills?.TryGetValue(points, out double? materialFill) == true) + { + if (!materialFill.HasValue) continue; + fill = shadowBase = materialFill.Value; + } + var openings = content.FaceOpenings?.GetValueOrDefault(points); + var rings = openings == null ? null : FaceRings(polygon, openings); + var terrainVisible = content.TerrainClippedFaces?.GetValueOrDefault(points); + if (terrainVisible is { Count: 0 }) continue; + if (terrainVisible != null) page.BeginPolygonClip(terrainVisible.Select(ToPage), evenOdd: false); + if (content.DetailGlass?.TryGetValue(points, out var pane) == true) + page.FillPolygonUnion(rings ?? [polygon], pane.Gray, pane.Opacity); + else if (rings == null) + page.DrawPolyline(polygon, 0, true, fill); + else + page.FillPolygonUnion(rings, fill); + var glazing = content.Glazing; + bool paintPane = glazing?.IsPane(points) == true; + if (!paintPane && modelHatch == null && content.AmbientTones?.GetValueOrDefault(points) is { } shade) + { + page.BeginPolygonClip(rings ?? [polygon]); + double x = ToX(shade.X0), y = ToY(shade.Y0); + double width = ToX(shade.X1) - x, height = ToY(shade.Y1) - y; + page.DrawImage(shade.Image, x, y, width, height); + if (shade.ThroughGlass is { } throughGlass && shade.Glass is { } glassMasks) + { + foreach (var mask in glassMasks) + { + var paneRing = ToPage(mask.Polygon); + page.BeginPolygonClip(mask.Holes == null ? [paneRing] : FaceRings(paneRing, mask.Holes)); + page.DrawImage(throughGlass, x, y, width, height); + page.EndClip(); + } + } + page.EndClip(); + } + if (paintPane) + glazing!.Draw(page, content, points, rings ?? [polygon], ToX, ToY, FaceRings); + if (modelHatch == null && content.PaneTones?.GetValueOrDefault(points) is { } paneTone) + { + page.BeginPolygonClip(rings ?? [polygon]); + double x = ToX(paneTone.X0), y = ToY(paneTone.Y0); + page.DrawImage(paneTone.Image, x, y, ToX(paneTone.X1) - x, ToY(paneTone.Y1) - y); + page.EndClip(); + } + if (content.ExteriorWallTones?.TryGetValue(points, out var tone) == true && tone.Light < 1) + { + double lower = Math.Max(tone.BaseY, pagePoints.Min(point => point.Y)); + double upper = pagePoints.Max(point => point.Y); + double left = pagePoints.Min(point => point.X); + double right = pagePoints.Max(point => point.X); + if (upper > lower && right > left) + { + page.BeginClip(ToX(left), ToY(lower), (right - left) / scale, (upper - lower) / scale); + page.FillPolygonUnion(rings ?? [polygon], 0, 1 - tone.Light); + page.EndClip(); + } + } + DrawShadow(points, polygon, shadowBase); + if (surfaceHatches is { } hatch && hatch.Faces.TryGetValue(points, out var surfacePattern)) + { + var (grid, width) = surfacePattern; + double spacing = grid.Offset * FeetToMillimetres; + double anchorX = ToX(hatch.AnchorX) + grid.OriginX * FeetToMillimetres; + double anchorY = ToY(hatch.AnchorY) + grid.OriginY * FeetToMillimetres; + if (hatch.UseClippedLines) + page.FillWithClippedParallelLines(rings ?? [polygon], spacing, grid.Angle, anchorX, anchorY, width); + else + page.FillWithParallelLines(rings ?? [polygon], spacing, grid.Angle, anchorX, anchorY, width); + } + if (surfaceHatches?.Regions?.TryGetValue(points, out var regions) == true) + { + page.BeginPolygonClip(rings ?? [polygon]); + foreach (var region in regions) + { + var grid = region.Grid; + var regionRings = FaceRings(ToPage(region.Outer), region.Holes); + page.FillWithClippedParallelLines(regionRings, grid.Offset * FeetToMillimetres, + grid.Angle, ToX(surfaceHatches.AnchorX) + grid.OriginX * FeetToMillimetres, + ToY(surfaceHatches.AnchorY) + grid.OriginY * FeetToMillimetres, 0.1); + } + page.EndClip(); + } + if (surfaceHatches?.DashedFaces.TryGetValue(points, out var grids) == true) + { + if (!surfaceTiles.TryGetValue(grids, out var tiles)) + { + tiles = FillHatch.DraftingTiles(grids, ToX(surfaceHatches.AnchorX), ToY(surfaceHatches.AnchorY), 0.1); + surfaceTiles.Add(grids, tiles); + } + foreach (var tile in tiles ?? []) page.FillWithLinePattern([polygon], tile); + } + if (modelHatch != null) + { + var modelRings = FaceRings(polygon, modelHatch.Holes); + foreach (var modelGrid in modelHatch.Grids) + { + if (modelGrid.Segments == null) + page.FillWithParallelLines(modelRings, modelGrid.Spacing / scale, modelGrid.Angle, ToX(modelGrid.X), ToY(modelGrid.Y), 0.1); + else + page.FillWithLinePattern(modelRings, new PdfLinePattern(modelGrid.Spacing / scale, modelGrid.Angle, + ToX(modelGrid.X), ToY(modelGrid.Y), 0.1, modelGrid.Shift / scale, + modelGrid.Segments.Select(segment => segment / scale).ToArray())); + } + } + if (terrainVisible != null) page.EndClip(); + } + if (content.ForegroundSite is { Rings.Count: > 0 } site) + { + double fill = content.SkyGradient != null ? 1 : 0.9; + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + page.FillPolygonUnion(site.Rings.Select(ToPage), fill); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(site.Shade.Select(ToPage), fill * site.Light); + page.EndClip(); + } + + List<(double X, double Y)> ToPage(List<(double X, double Y)> ring) => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + + if (groundTiles != null && sectionMasks != null) + { + List<(double X, double Y)> frame = + [(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(clipY1)), (ToX(clipX0), ToY(clipY1))]; + var caps = new List>(); + page.BeginPolygonClip([frame]); + foreach (var mask in sectionMasks) + { + var clipped = ClipToWindow(mask, clipX0, clipX1, clipY0, clipY1); + if (clipped.Count < 3) continue; + var polygon = clipped.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + page.IntersectPolygonClip([frame, polygon]); + if (isSection) continue; + if (PlanPrinter.SignedArea(polygon) < 0) polygon.Reverse(); + caps.Add(polygon); + } + DrawGroundTiles(groundTiles, opaque: true); + if (!isSection && document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Topography, true, penScale, out double terrainOutline)) + { + var padCuts = content.Edges.Where(edge => edge.IsCut && edge.CategoryId == (int)BuiltInCategory.OST_BuildingPad + && terrainOutline > CutPen(edge)).ToList(); + if (padCuts.Count > 0) + { + // The intersected ground adds its cut pen only on the soil side of the pad's contour. + page.BeginPolygonClip(groundPolygons, evenOdd: false); + foreach (var edge in padCuts) + { + double x1 = ToX(edge.X1), y1 = ToY(edge.Y1), x2 = ToX(edge.X2), y2 = ToY(edge.Y2); + double dx = x2 - x1, dy = y2 - y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (length == 0) continue; + double nx = -dy * terrainOutline / (2 * length), ny = dx * terrainOutline / (2 * length); + page.DrawPolyline([(x1 - nx, y1 - ny), (x2 - nx, y2 - ny), + (x2 + nx, y2 + ny), (x1 + nx, y1 + ny)], 0, closed: true, fillGray: 0); + } + page.EndClip(); + } + } + page.EndClip(); + if (caps.Count > 0) page.FillPolygonUnion(caps, 1); + } + if (content.SectionBillboards is { Count: > 0 } billboards) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + page.FillPolygonUnion(billboards.Select(ToPage), 1); + page.EndClip(); + } + if (content.DetailCutFaces is { } cutFaces) + { + // Closed cuts cover projected surfaces before the cut patterns and linework are drawn. + var caps = cutFaces.Select(face => ClipToWindow(face, clipX0, clipX1, clipY0, clipY1)) + .Where(face => face.Count >= 3).Select(ToPage).ToList(); + foreach (var cap in caps) + if (PlanPrinter.SignedArea(cap) < 0) cap.Reverse(); + if (caps.Count > 0) page.FillPolygonUnion(caps, 1); + } + if (content.SiteOutlines is { Count: > 0 } siteEdges) + foreach (var group in siteEdges.GroupBy(edge => edge.CategoryId)) + { + double width = document != null + && PenWidths.TryGetWidth(document, group.Key, false, penScale, out double savedWidth) + ? savedWidth : 0.1; + var inked = new HashSet<(long Ax, long Ay, long Bx, long By)>(); + foreach (var edge in group) + { + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2) + && inked.Add(ProjectedEdgeKey(x1, y1, x2, y2))) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width); + } + } + List> FaceRings(List<(double X, double Y)> polygon, + IReadOnlyList> openings) + { + bool positive = PlanPrinter.SignedArea(polygon) > 0; + var rings = new List> { polygon }; + foreach (var hole in openings) + { + var clipped = clipRect.HasValue ? ClipToWindow(hole, clipX0, clipX1, clipY0, clipY1) : hole; + if (clipped.Count < 3) continue; + var ring = clipped.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (area == 0) continue; + // Opposite winding keeps the opening clear in the face fill. + if ((area > 0) == positive) ring.Reverse(); + rings.Add(ring); + } + return rings; + } + + void DrawShadow(List<(double X, double Y)> face, List<(double X, double Y)> polygon, double fill) + { + if (content.CastShadows?.GetValueOrDefault(face) is not { } shadow) return; + page.BeginPolygonClip([polygon, .. shadow.Openings.Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList())]); + if (groundPolygons.Count > 0) + ClipShadowAtGround(polygon.Min(p => p.X), polygon.Min(p => p.Y), + polygon.Max(p => p.X), polygon.Max(p => p.Y)); + page.FillPolygonUnion(shadow.Rings.Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()), fill * shadow.Light); + page.EndClip(); + } + + void ClipShadowAtGround(double left, double bottom, double right, double top) + { + // The terrain cut hides the projected shadows in its hatched area. + List<(double X, double Y)> frame = + [(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(clipY1)), (ToX(clipX0), ToY(clipY1))]; + foreach (var mask in groundPolygons) + if (mask.Max(p => p.X) > left && mask.Min(p => p.X) < right + && mask.Max(p => p.Y) > bottom && mask.Min(p => p.Y) < top) + page.IntersectPolygonClip([frame, mask]); + } + + if (groundTiles != null) + { + if (!isSection && sectionMasks == null) DrawGroundTiles(groundTiles, opaque: true); + } + else if (content.GroundHatch is { } ground && groundPolygons.Count > 0) + { + var strokes = FillHatch.Strokes(groundPolygons, ground.Grids, ToX(ground.AnchorX), ToY(ground.AnchorY)) + .Select(line => new CollectedEdge(line.X1, line.Y1, line.X2, line.Y2, 0, 0, -1, -1, 0, 0, 0, 0)); + // Covered portions must be absent from the PDF, including when compared as vectors. + if (isSection) + strokes = VisibleTerrainEdges(strokes, + content.Faces.Select(face => face.Points.Select(p => (ToX(p.X), ToY(p.Y))).ToList()), + [], 0.01 / (scale * scale)); + foreach (var line in strokes) + page.DrawLine(line.X1, line.Y1, line.X2, line.Y2, groundPen); + } + void DrawGroundTiles(List tiles, bool opaque = false) + { + foreach (var polygon in groundPolygons) + if (PlanPrinter.SignedArea(polygon) < 0) polygon.Reverse(); + if (opaque) + { + page.FillPolygonUnion(groundPolygons, 1); + if (content.GroundHatch?.Shadow is { } soilShadow) + { + page.BeginPolygonClip(groundPolygons, evenOdd: false); + page.FillPolygonUnion(soilShadow.Rings.Select(ToPage), soilShadow.Light); + page.EndClip(); + } + } + foreach (var tile in tiles) page.FillWithLinePattern(groundPolygons, tile); + } + var masks = content.DetailBreaks is { Count: > 0 } breaks + ? breaks.Select(b => b.Mask).ToList() : null; + if (masks != null) + foreach (var polygon in masks) + { + var clipped = ClipToWindow(polygon, clipX0, clipX1, clipY0, clipY1); + if (clipped.Count >= 3) + page.DrawPolyline(clipped.Select(p => (ToX(p.X), ToY(p.Y))).ToList(), 0, true, 1); + } + if (content.LayerHatches is { } hatches) + { + foreach (var group in hatches.GroupBy(p => (p.Grids, p.AnchorX, p.AnchorY, p.PenWidth))) + { + var polygons = group.Select(p => ClipToWindow(p.Polygon, clipX0, clipX1, clipY0, clipY1) + .Select(point => (ToX(point.X), ToY(point.Y))).ToList()); + double anchorX = ToX(group.Key.AnchorX), anchorY = ToY(group.Key.AnchorY); + var grids = group.Key.Grids; + double draftingPen = group.Key.PenWidth ?? 0.1; + if ((!isSection || group.Key.PenWidth.HasValue) && masks == null + && FillHatch.DraftingTiles(grids, anchorX, anchorY, draftingPen) is { } tiles) + { + var rings = polygons.Where(p => p.Count >= 3).ToList(); + foreach (var ring in rings) + if (PlanPrinter.SignedArea(ring) < 0) ring.Reverse(); + foreach (var tile in tiles) page.FillWithLinePattern(rings, tile); + foreach (var grid in grids.Where(g => g.Segments.Length == 0)) + page.FillWithParallelLines(rings, Math.Abs(grid.Offset) * FeetToMillimetres, grid.Angle, + anchorX + grid.OriginX * FeetToMillimetres, anchorY + grid.OriginY * FeetToMillimetres, draftingPen); + continue; + } + var strokes = FillHatch.Strokes(polygons, grids, anchorX, anchorY, continuousLines: true) + .Select(s => new CollectedEdge(s.X1, s.Y1, s.X2, s.Y2, 0, 0, -1, -1, 0, 0, 0, 0)); + if (masks != null) + strokes = VisibleTerrainEdges(strokes, masks.Select(p => p.Select(point => + (ToX(point.X), ToY(point.Y))).ToList()), [], 1e-9); + foreach (var stroke in strokes) + page.DrawLine(stroke.X1, stroke.Y1, stroke.X2, stroke.Y2, group.Key.PenWidth ?? 0.18); + } } - foreach (var edge in content.Edges) + HashSet<(long Ax, long Ay, long Bx, long By)>? doorProjections = content.KeepDoorDepths ? [] : null; + var visibleEdges = Unmasked(content.Edges); + if (isSection && clipRect.HasValue) + visibleEdges = TrimProjectedEdgesAtCuts(visibleEdges.ToList(), + edge => edge.ViewLineStyleId == 0 && CutPen(edge) >= projLine); + foreach (var edge in visibleEdges) { double x1 = edge.X1, y1 = edge.Y1, x2 = edge.X2, y2 = edge.Y2; - if (clipRect.HasValue && !ClipSegment(x1, y1, x2, y2, clipX0, clipY0, clipX1, clipY1, + if ((clipRect.HasValue || edge.CategoryId == (int)BuiltInCategory.OST_Topography) + && !ClipSegment(x1, y1, x2, y2, clipX0, clipY0, clipX1, clipY1, out x1, out y1, out x2, out y2)) continue; + // Different physical door edges can leave the same visible span after clipping. + if (doorProjections != null && edge.CategoryId == (int)BuiltInCategory.OST_Doors + && !edge.IsCut && edge.ViewLineStyleId == 0 + && !doorProjections.Add(ProjectedEdgeKey(x1, y1, x2, y2))) continue; // A cut edge inks with its own category's cut pen (falling back to the Walls cut pen when the // category decodes none); anything else inks with the projection pen. - double width = projLine; - if (edge.IsCut) - width = document != null - && PenWidths.TryGetWidth(document, edge.CategoryId, true, penScale, out double cutWidth) - ? cutWidth : faceLine; + double width = edge.IsCut ? CutPen(edge) : projLine; + if (edge.ViewLineStyleId > 0) + { + if (document == null || document.RawData.GraphicsStylePens?.TryGetValue(edge.ViewLineStyleId, out var style) != true + || style.GStyleType != 1) continue; + var color = new PdfColor((style.Color & 255) / 255d, ((style.Color >> 8) & 255) / 255d, + ((style.Color >> 16) & 255) / 255d); + width = document.RawData.PenWidthTable is { } widths + && PenWidths.TryPenWidth(widths, style.PenNumber, penScale, out double patternPen) ? patternPen : projLine; + if (LinePatterns.TryGetPatternDashes(document, style.LinePatternId, out var dashes)) + { + double dx = x2 - x1, dy = y2 - y1; + double length = Math.Sqrt(dx * dx + dy * dy); + double phase = 0; + if (edge.UnclippedViewLine is { } source) + { + dx = source.X2 - source.X1; + dy = source.Y2 - source.Y1; + length = Math.Sqrt(dx * dx + dy * dy); + double offset = ((x1 - source.X1) * dx + (y1 - source.Y1) * dy) / length; + phase = Math.Max(0, offset) / scale * 72 / 25.4; + } + page.SetDashPoints(LinePatterns.FitEndpointDashes(length / scale * 72 / 25.4, dashes), phase); + } + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width, color); + page.ResetDash(); + continue; + } page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width); } + if (content.Insulation != null) + { + double pen = 0.18; + if (document != null && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_InsulationLines, + false, penScale, out double width)) + pen = width; + foreach (var edge in Unmasked(content.Insulation)) + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2)) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), pen); + } + if (content.DetailBreaks is { } detailBreaks) + foreach (var detail in detailBreaks) + for (int i = 1; i < detail.Line.Count; i++) + { + var a = detail.Line[i - 1]; + var b = detail.Line[i]; + if (ClipSegment(a.X, a.Y, b.X, b.Y, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2)) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), 0.35); + } + + double CutPen(CollectedEdge edge) => document != null + && PenWidths.TryGetWidth(document, edge.CategoryId, true, penScale, out double width) ? width : faceLine; + + IEnumerable Unmasked(List edges) => + masks == null ? edges : VisibleTerrainEdges(edges, masks, []); + } + private static void DrawFallbackDatums(PdfPage page, ElevationContent content, double scale, double originX, + double originY, RvtDocument? document, (double X0, double Y0, double X1, double Y1)? clipRect) + { + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + var (clipX0, clipY0, clipX1, clipY1) = clipRect ?? (content.MinX, content.MinY, content.MaxX, content.MaxY); // Grids first, then the levels: light over the faces the way an elevation prints them. The grids // dash coarsely from the grid type's line pattern ([36 9 9 9] pt on the sample, decoded below); // their bubbles print solid like the reference. if (content.Grids.Count > 0) { // Grids are datum elements: they ink with the annotation pen table (fixed weights), not the - // scale-dependent model table — pen 1 annotates 0.1 mm (0.283 pt) at every scale on the reference. + // scale-dependent model table — pen 1 annotates 0.1 mm (0.283 pt) at every scale on the reference. double gridLine = 0.1; if (document != null && PenWidths.TryGetPenNumber(document, (int)BuiltInCategory.OST_Grids, false, out int gridPen) && PenWidths.TryAnnotationWidth(document, gridPen, out double g)) @@ -1361,6 +4520,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double double bottom = ToY(Math.Max(content.MinY, clipY0)); foreach (var (x, name) in content.Grids) { + if (content.NativeGrids?.ContainsKey(x) == true) continue; if (x < clipX0 || x > clipX1) continue; double pageX = ToX(x); // The dash pattern starts at the top of the line, as the reference grids do (a cut 36 pt @@ -1391,6 +4551,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double double lastLabelY = double.NegativeInfinity; foreach (var (y, label, x0, x1) in content.Levels) { + if (content.NativeLevels?.ContainsKey(y) == true) continue; // A level belongs to the crop, not to the collected model bounds: stairs-only content ends // above the Foundation while the crop reaches it, and the reference draws it. if (y < clipY0 - 1 || y > clipY1 + 1) continue; @@ -1447,4 +4608,131 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double page.ResetDash(); } } + + internal static void DrawNativeDatums(PdfPage page, ElevationContent content, double scale, double originX, + double originY, RvtDocument? document, (double X0, double Y0, double X1, double Y1)? crop) + { + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + if (content.NativeGrids is { Count: > 0 } grids) + { + double[] pattern = document != null && LinePatterns.TryGetGridDashes(document, out var gridDashes) + ? gridDashes.Select(p => p * 25.4 / 72).ToArray() + : []; + foreach (var (x, name) in content.Grids) + { + if (!grids.TryGetValue(x, out var g)) continue; + if (crop is { } c && (x < c.X0 || x > c.X1 || g.Top < c.Y0 || g.Bottom > c.Y1)) continue; + double pageX = ToX(x), top = ToY(g.Top), center = top + g.Radius; + DrawDatumDashes(page, pageX, ToY(g.Bottom), pageX, top, pattern); + page.DrawPolyline(DatumCircle(pageX, center, g.Radius, 25), 0.1, true); + page.DrawText(name, pageX, center - 2.17, 18 * 25.4 / 72, PdfTextAlignment.Center); + } + } + + if (content.NativeLevels is not { Count: > 0 } lines) return; + foreach (var (y, label, _, _) in content.Levels) + { + if (!lines.TryGetValue(y, out var line)) continue; + if (crop is { } c && (y < c.Y0 - 1 || y > c.Y1 + 1 || line.HeadX < c.X0 || line.Left > c.X1)) continue; + double left = ToX(line.Left), right = ToX(line.LineEnd), rowY = ToY(y); + DrawDatumDashes(page, left, rowY, right, rowY, [3, 1.5]); + + double headLeft = ToX(line.HeadX), headY = ToY(line.HeadY); + if (line.Elbow is { } e) + { + page.DrawLine(right, rowY, ToX(e.X), ToY(e.Y), 0.1); + page.DrawLine(ToX(e.X), ToY(e.Y), headLeft, headY, 0.1); + } + double cx = headLeft + line.Radius; + var outline = DatumCircle(cx, headY, line.Radius, 20); + page.DrawPolyline(outline, 0.1, true); + page.DrawPolyline([(cx, headY), .. outline.Skip(5).Take(6)], 0, true, 0); + page.DrawPolyline([(cx, headY), .. outline.Skip(15), outline[0]], 0, true, 0); + string elevation = $"{y:0}"; + if (DrawSavedLevelLabels(page, document, line.SymbolId, headLeft, headY, label, elevation)) continue; + page.DrawText(label, headLeft - 4, headY + 1.85, 12 * 25.4 / 72, PdfTextAlignment.Right); + page.DrawText(elevation, headLeft - 4, headY - 5.05, 12 * 25.4 / 72, PdfTextAlignment.Right); + } + } + + private static bool DrawSavedLevelLabels(PdfPage page, RvtDocument? document, int symbolId, + double x, double y, string name, string elevation) + { + if (document?.RawData.TitleBlockLabels?.GetValueOrDefault(symbolId) is not [var first, var second] labels + || first.ParamId == second.ParamId || page.Owner.Font is not { } font + || labels.Any(label => (BuiltInParameter)label.ParamId is not (BuiltInParameter.DATUM_TEXT or BuiltInParameter.LEVEL_ELEV) + || label is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || !(label.Height > 0) + || !double.IsFinite(label.Height) || !double.IsFinite(label.Ox) || !double.IsFinite(label.Oy))) return false; + + foreach (var label in labels) + { + string value = label.Prefix + (label.ParamId == (int)BuiltInParameter.DATUM_TEXT ? name : elevation) + label.Suffix; + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double size = SheetComposer.SymbolLabelTextSize(font, height, cap); + double width = label.Width * FeetToMillimetres; + bool wrap = label.Wrap && width > 0 && page.MeasureText(value, size) > width; + var lines = PlanPrinter.WrapPlanNoteText(page, value, size, width, wrap); + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + bool useArialLayout = document.RawData.RegularArialSymbolLabelStyles?.Contains(label.AttrId) == true + && font.Name.Equals("Arial", StringComparison.OrdinalIgnoreCase); + SheetComposer.DrawTitleBlockText(page, lines, x + label.Ox * FeetToMillimetres, + y + label.Oy * FeetToMillimetres, size, height * lines.Count, label.Flags, + label.Bx, label.By, label.Hx, label.Hy, opaque, useArialLayout); + } + return true; + } + + internal static List<(double X, double Y)> DatumCircle(double x, double y, double radius, int count) + { + var circle = new List<(double X, double Y)>(count); + for (int i = 0; i < count; i++) + { + double a = i * 2 * Math.PI / count; + circle.Add((x + radius * Math.Cos(a), y + radius * Math.Sin(a))); + } + return circle; + } + + internal static void DrawDatumDashes(PdfPage page, double x1, double y1, double x2, double y2, + double[] pattern, double width = 0.1, bool roundCaps = false) + { + double dx = x2 - x1, dy = y2 - y1; + double length = Math.Sqrt(dx * dx + dy * dy), period = pattern.Sum(); + if (!(length > 0)) return; + int cycles = period > 0 ? (int)Math.Floor(length / period) : 0; + if (cycles <= 0) + { + Stroke(0, length); + return; + } + // Revit balances the two end dashes around the full-length interior dashes. + double endDash = (length - cycles * period + pattern[0]) / 2; + Stroke(0, endDash); + double cursor = endDash; + for (int repeat = 0; repeat < cycles; repeat++) + { + for (int i = 1; i < pattern.Length; i++) + { + double next = cursor + pattern[i]; + if (i % 2 == 0) Stroke(cursor, next); + cursor = next; + } + if (repeat + 1 < cycles) + { + Stroke(cursor, cursor + pattern[0]); + cursor += pattern[0]; + } + } + Stroke(length - endDash, length); + + void Stroke(double from, double to) + { + var a = (X: x1 + from * dx / length, Y: y1 + from * dy / length); + var b = (X: x1 + to * dx / length, Y: y1 + to * dy / length); + if (roundCaps) page.DrawRoundDashedPolyline([a, b], width, []); + else page.DrawLine(a.X, a.Y, b.X, b.Y, width); + } + } } diff --git a/src/RvtIO/Print/FillHatch.cs b/src/RvtIO/Print/FillHatch.cs index a29b254e..0c7ee3fa 100644 --- a/src/RvtIO/Print/FillHatch.cs +++ b/src/RvtIO/Print/FillHatch.cs @@ -1,3 +1,4 @@ +using RvtIO.Model; using RvtIO.Parsing; using RvtIO.Pdf; @@ -8,57 +9,166 @@ internal static class FillHatch { private const double FeetToMillimetres = 304.8; + internal sealed record ModelGrid(double X, double Y, double Angle, double Spacing, + double Shift = 0, double[]? Segments = null); + + // shortcut: a single continuous model grid with an authored face placement. + internal static ModelGrid? ProjectModelGrid(RvtDocument document, GeoFace face, + Func inView) + { + if (face.ModelPattern is not { } placement + || document.RawData.FillPatterns?.TryGetValue(placement.PatternId, out var pattern) != true + || pattern.Grids is not [{ Target: 1, Segments.Length: 0, Offset: > 0 } grid]) return null; + return ProjectGrid(placement, grid, inView); + } + + internal static IReadOnlyList? ProjectDashedModelGrids(RvtDocument document, GeoFace face, + Func inView) + { + if (face.ModelPattern is not { } placement + || document.RawData.FillPatterns?.TryGetValue(placement.PatternId, out var pattern) != true + || pattern.Grids.Count == 0 + || !pattern.Grids.All(grid => grid is { Target: 1, Orientation: 0, Segments.Length: > 0 })) return null; + var grids = new List(pattern.Grids.Count); + foreach (var grid in pattern.Grids) + { + if (ProjectGrid(placement, grid, inView) is not { } projected) return null; + grids.Add(projected); + } + return grids; + } + + private static ModelGrid? ProjectGrid(RvtIO.Internal.ModelFacePattern placement, + TfBlockDeserializer.PatternGrid grid, Func inView) + => ProjectGrid(grid, inView(placement.Origin), inView(placement.U), inView(placement.V)); + + internal static ModelGrid? ProjectGrid(TfBlockDeserializer.PatternGrid grid, + (double X, double Y) origin, (double X, double Y) u, (double X, double Y) v) + { + var (ax, ay) = origin; + var (ux, uy) = u; + var (vx, vy) = v; + double cos = Math.Cos(grid.Angle), sin = Math.Sin(grid.Angle); + double dx = cos * ux + sin * vx, dy = cos * uy + sin * vy; + double length = Math.Sqrt(dx * dx + dy * dy); + double nx = -sin * ux + cos * vx, ny = -sin * uy + cos * vy; + double signedSpacing = (dx * ny - dy * nx) / length * grid.Offset; + double spacing = Math.Abs(signedSpacing); + double x = ax + grid.OriginX * ux + grid.OriginY * vx; + double y = ay + grid.OriginX * uy + grid.OriginY * vy; + if (!double.IsFinite(spacing) || spacing <= 1e-6 || !double.IsFinite(x) || !double.IsFinite(y)) return null; + double angle = Math.Atan2(dy, dx); + if (grid.Segments.Length == 0) return new ModelGrid(x, y, angle, spacing); + + double shift = grid.Shift * length + grid.Offset * (dx * nx + dy * ny) / length; + if (signedSpacing < 0) shift = -shift; + var segments = grid.Segments.Select(segment => segment * length).ToArray(); + double period = segments.Sum(); + return double.IsFinite(shift) && double.IsFinite(period) + && period > 0 && segments.All(segment => segment >= 0) + ? new ModelGrid(x, y, angle, spacing, shift, segments) : null; + } + /// Draws the dashes of clipped to . The polygon, /// the anchor and the pen width are in page millimetres; the pattern's own lengths are feet, read as drafting /// pattern paper lengths (they do not scale with the view). internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> polygon, IReadOnlyList grids, double anchorX, double anchorY, double width) { - if (polygon.Count < 3) return; + foreach (var line in Strokes([polygon], grids, anchorX, anchorY)) + page.DrawLine(line.X1, line.Y1, line.X2, line.Y2, width); + } + + internal static List? DraftingTiles(IReadOnlyList grids, + double anchorX, double anchorY, double width) + { + var tiles = new List(); foreach (var grid in grids) { if (grid.Segments.Length == 0) continue; + double spacing = Math.Abs(grid.Offset) * FeetToMillimetres; + double shift = (grid.Offset < 0 ? -grid.Shift : grid.Shift) * FeetToMillimetres; + double x = anchorX + grid.OriginX * FeetToMillimetres, y = anchorY + grid.OriginY * FeetToMillimetres; + var segments = grid.Segments.Select(segment => segment * FeetToMillimetres).ToArray(); + double period = segments.Sum(); + if (!double.IsFinite(spacing) || spacing <= width || !double.IsFinite(shift) + || !double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(grid.Angle) + || !double.IsFinite(period) || period <= 0 || segments.Any(segment => segment < 0)) return null; + tiles.Add(new(spacing, grid.Angle, x, y, width, shift, segments)); + } + return tiles; + } + + internal static IEnumerable<(double X1, double Y1, double X2, double Y2)> Strokes( + IEnumerable> polygons, + IReadOnlyList grids, double anchorX, double anchorY, + bool continuousLines = false) + { + foreach (var grid in grids) + { + bool continuous = grid.Segments.Length == 0; + if (continuous && !continuousLines) continue; double dx = Math.Cos(grid.Angle), dy = Math.Sin(grid.Angle); double nx = -dy, ny = dx; double offset = grid.Offset * FeetToMillimetres; double shift = grid.Shift * FeetToMillimetres; double period = 0; foreach (double segment in grid.Segments) period += segment * FeetToMillimetres; - if (Math.Abs(offset) < 1e-9 || period <= 0) continue; + if (Math.Abs(offset) < 1e-9 || !continuous && period <= 0) continue; var segments = new double[grid.Segments.Length]; for (int i = 0; i < segments.Length; i++) segments[i] = grid.Segments[i] * FeetToMillimetres; double ox = anchorX + grid.OriginX * FeetToMillimetres; double oy = anchorY + grid.OriginY * FeetToMillimetres; - double minK = double.MaxValue, maxK = double.MinValue; - foreach (var point in polygon) + var rows = new SortedDictionary>(); + foreach (var polygon in polygons) { - double k = ((point.X - ox) * nx + (point.Y - oy) * ny) / offset; - if (k < minK) minK = k; - if (k > maxK) maxK = k; + if (polygon.Count < 3) continue; + double minK = double.MaxValue, maxK = double.MinValue; + foreach (var point in polygon) + { + double k = ((point.X - ox) * nx + (point.Y - oy) * ny) / offset; + if (k < minK) minK = k; + if (k > maxK) maxK = k; + } + + for (int k = (int)Math.Floor(minK); k <= (int)Math.Ceiling(maxK); k++) + { + double bx = ox + k * (shift * dx + offset * nx); + double by = oy + k * (shift * dy + offset * ny); + var crossings = new List(8); + for (int i = 0; i < polygon.Count; i++) + { + var a = polygon[i]; + var b = polygon[(i + 1) % polygon.Count]; + double ex = b.X - a.X, ey = b.Y - a.Y; + double den = dx * ey - dy * ex; + if (Math.Abs(den) < 1e-12) continue; + double t = ((a.X - bx) * ey - (a.Y - by) * ex) / den; + double u = ((bx - a.X) * dy - (by - a.Y) * dx) / -den; + if (u >= -1e-9 && u <= 1 + 1e-9) crossings.Add(t); + } + crossings.Sort(); + for (int i = 0; i + 1 < crossings.Count; i += 2) + { + if (crossings[i + 1] - crossings[i] < 1e-9) continue; + if (!rows.TryGetValue(k, out var intervals)) rows[k] = intervals = []; + intervals.Add((crossings[i], crossings[i + 1])); + } + } } - for (int k = (int)Math.Floor(minK); k <= (int)Math.Ceiling(maxK); k++) + foreach (var (k, intervals) in rows) { double bx = ox + k * (shift * dx + offset * nx); double by = oy + k * (shift * dy + offset * ny); - var crossings = new List(8); - for (int i = 0; i < polygon.Count; i++) + foreach (var (ta, tb) in UnionIntervals(intervals)) { - var a = polygon[i]; - var b = polygon[(i + 1) % polygon.Count]; - double ex = b.X - a.X, ey = b.Y - a.Y; - double den = dx * ey - dy * ex; - if (Math.Abs(den) < 1e-12) continue; - double t = ((a.X - bx) * ey - (a.Y - by) * ex) / den; - double u = ((bx - a.X) * dy - (by - a.Y) * dx) / -den; - if (u >= -1e-9 && u <= 1 + 1e-9) crossings.Add(t); - } - crossings.Sort(); - for (int i = 0; i + 1 < crossings.Count; i += 2) - { - double ta = crossings[i], tb = crossings[i + 1]; - if (tb - ta < 1e-9) continue; + if (continuous) + { + yield return (bx + ta * dx, by + ta * dy, bx + tb * dx, by + tb * dy); + continue; + } for (double start = Math.Floor(ta / period) * period; start < tb; start += period) { double cursor = start; @@ -70,7 +180,7 @@ internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> poly { double from = Math.Max(cursor, ta), to = Math.Min(cursor + segment, tb); if (to > from + 1e-9) - page.DrawLine(bx + from * dx, by + from * dy, bx + to * dx, by + to * dy, width); + yield return (bx + from * dx, by + from * dy, bx + to * dx, by + to * dy); } cursor += segment; } @@ -79,4 +189,22 @@ internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> poly } } } + + // Terrain triangles may overlap or share a boundary. Ink each grid's covered intervals once. + private static IEnumerable<(double From, double To)> UnionIntervals(List<(double From, double To)> intervals) + { + intervals.Sort((a, b) => a.From.CompareTo(b.From)); + var (from, to) = intervals[0]; + for (int i = 1; i < intervals.Count; i++) + { + var (nextFrom, nextTo) = intervals[i]; + if (nextFrom > to + 1e-9) + { + yield return (from, to); + from = nextFrom; + } + to = Math.Max(to, nextTo); + } + yield return (from, to); + } } diff --git a/src/RvtIO/Print/LinePatterns.cs b/src/RvtIO/Print/LinePatterns.cs index 1544af94..6f75143c 100644 --- a/src/RvtIO/Print/LinePatterns.cs +++ b/src/RvtIO/Print/LinePatterns.cs @@ -29,19 +29,32 @@ internal static bool TryGetGridDashes(RvtDocument document, out double[] dashes) break; } } - if (centerCategory == null) return false; + return centerCategory is int categoryId && TryGetDashes(document, categoryId, out dashes); + } + + internal static bool TryGetDashes(RvtDocument document, int categoryId, out double[] dashes) + { + dashes = []; + var info = document.RawData; + if (info.GraphicsStylePens == null || info.LinePatterns == null) return false; int patternId = 0; bool found = false; foreach (var style in info.GraphicsStylePens.Values) { - if (style.CategoryId == centerCategory && style.OwnerId == -1 && style.GStyleType == 1) + if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == 1) { patternId = style.LinePatternId; found = true; break; } } - if (!found || patternId <= 0 || !info.LinePatterns.TryGetValue(patternId, out var pattern)) + return found && TryGetPatternDashes(document, patternId, out dashes); + } + + internal static bool TryGetPatternDashes(RvtDocument document, int patternId, out double[] dashes) + { + dashes = []; + if (patternId <= 0 || document.RawData.LinePatterns?.TryGetValue(patternId, out var pattern) != true) return false; var points = new List(); var ink = new List(); @@ -59,4 +72,23 @@ internal static bool TryGetGridDashes(RvtDocument document, out double[] dashes) dashes = [.. points.Select(v => Math.Round(v, 3))]; return true; } + + internal static double[] FitEndpointDashes(double lengthPoints, double[] dashes) + { + if (dashes.Length < 2 || dashes.Length % 2 != 0 || !double.IsFinite(lengthPoints) + || dashes.Any(value => !(value > 0 && double.IsFinite(value)))) return dashes; + double period = dashes.Sum(); + double repeats = Math.Floor(lengthPoints / period); + if (repeats < 1) return []; + if (repeats * dashes.Length + 2 > 4096) return dashes; + + // Keep the interior sequence and split the remaining length equally between the terminal dashes. + double terminal = (lengthPoints - repeats * period + dashes[0]) / 2; + var fitted = new double[(int)repeats * dashes.Length + 2]; + for (int i = 0; i < fitted.Length - 2; i += dashes.Length) + Array.Copy(dashes, 0, fitted, i, dashes.Length); + fitted[0] = fitted[^2] = terminal; + fitted[^1] = dashes[1]; + return fitted; + } } diff --git a/src/RvtIO/Print/PenWidths.cs b/src/RvtIO/Print/PenWidths.cs index 5b53e923..bf00380d 100644 --- a/src/RvtIO/Print/PenWidths.cs +++ b/src/RvtIO/Print/PenWidths.cs @@ -13,8 +13,11 @@ internal static class PenWidths /// The pen number a category's cut (isCut) or projection lines use, from the document's /// Object Styles. False when the category has no style for that kind. internal static bool TryGetPenNumber(RvtDocument document, int categoryId, bool isCut, out int pen) + => TryGetStyle(document, categoryId, isCut, out pen, out _); + + internal static bool TryGetStyle(RvtDocument document, int categoryId, bool isCut, out int pen, out int color) { - pen = 0; + pen = color = 0; var styles = document.RawData.GraphicsStylePens; if (styles == null) return false; int kind = isCut ? 2 : 1; @@ -23,6 +26,7 @@ internal static bool TryGetPenNumber(RvtDocument document, int categoryId, bool if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == kind) { pen = style.PenNumber; + color = style.Color; return true; } } @@ -35,22 +39,9 @@ internal static bool TryGetWidth(RvtDocument document, int categoryId, bool isCu { widthMillimetres = 0; var info = document.RawData; - if (info.GraphicsStylePens == null || info.PenWidthTable == null) return false; - if (scaleDenominator <= 0) return false; - int kind = isCut ? 2 : 1; - int pen = 0; - bool found = false; - foreach (var style in info.GraphicsStylePens.Values) - { - if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == kind) - { - pen = style.PenNumber; - found = true; - break; - } - } - if (!found) return false; - return TryPenWidth(info.PenWidthTable.Value, pen, scaleDenominator, out widthMillimetres); + return info.PenWidthTable is { } table && scaleDenominator > 0 + && TryGetPenNumber(document, categoryId, isCut, out int pen) + && TryPenWidth(table, pen, scaleDenominator, out widthMillimetres); } /// Width in millimetres a model pen prints at for a view scale denominator. False when the pen is out diff --git a/src/RvtIO/Print/PlanElevationMarks.cs b/src/RvtIO/Print/PlanElevationMarks.cs new file mode 100644 index 00000000..2dbc93ee --- /dev/null +++ b/src/RvtIO/Print/PlanElevationMarks.cs @@ -0,0 +1,94 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class PlanElevationMarks +{ + private const double FeetToMillimetres = 304.8; + + internal static void Draw(PdfPage page, RvtDocument document, Element plan, ViewCropFrame crop, + double scale, double sheetX, double sheetY) + { + if (document.RawData.PlanElevationMarks is not { Count: > 0 } marks + || crop.Right is not [1, 0, 0] || crop.Up is not [0, 1, 0] + || document.RawData.PlanViewRanges?.GetValueOrDefault(plan.Id) is not + ({ Length: > 0 } offsets, { Length: > 0 } levels) + || document.GetElement(levels[0])?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double level) + return; + + double cut = level + offsets[0]; + if (!double.IsFinite(cut)) return; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(plan.Id); + double pen = PenWidths.TryGetPenNumber(document, (int)BuiltInCategory.OST_ElevationMarks, false, out int weight) + && PenWidths.TryAnnotationWidth(document, weight, out double width) ? width : 0.1; + foreach (var mark in marks) + { + double u = mark.X - crop.OriginX, v = mark.Y - crop.OriginY; + if (u < crop.X0 || u > crop.X1 || v < crop.Y0 || v > crop.Y1 || hidden?.Contains(mark.Id) == true + || document.GetElement(mark.BodyId) is not + { FamilyName: "M_Elevation Mark Body_Circle-12mm", BoundingBox: { Length: 6 } box }) + continue; + + double r = (box[3] - box[0]) * FeetToMillimetres / 2; + if (!(r is > 0 and <= 100) || Math.Abs(box[3] - box[0] - box[4] + box[1]) > 1e-6) continue; + double x = sheetX + u * FeetToMillimetres / scale; + double y = sheetY + v * FeetToMillimetres / scale; + double tipLength = r / Math.Cos(mark.ArrowHalfAngle); + if (plan.ViewAnnotationCropActive == true) + { + var (left, right, top, bottom) = plan.ViewAnnotationCrop ?? (0, 0, 0, 0); + double margin = tipLength * scale / FeetToMillimetres; + if (u - margin < crop.X0 - left * scale || u + margin > crop.X1 + right * scale + || v - margin < crop.Y0 - bottom * scale || v + margin > crop.Y1 + top * scale) + continue; + } + + if (hidden?.Contains(mark.ArrowId) == true || hidden?.Contains(mark.ViewId) == true + || 1 / scale < mark.CoarserScale || document.GetElement(mark.ViewId) is not + { ViewDirection: [var dx, var dy, 0], ViewCrop: { } elevationCrop } + || elevationCrop.Up is not [0, 0, 1] + || cut < elevationCrop.OriginZ + elevationCrop.Y0 || cut > elevationCrop.OriginZ + elevationCrop.Y1 + || document.GetElement(mark.ArrowSymbolId)?.FamilyName != "M_Elevation Mark Pointer_Circle") + continue; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0) || !double.IsFinite(length)) continue; + dx /= length; + dy /= length; + + var viewport = document.Elements.FirstOrDefault(element => element.ViewportViewId == mark.ViewId); + string detail = viewport?.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? "-"; + string number = viewport?.OwnerViewId is int sheetId + ? document.GetElement(sheetId)?.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? "-" : "-"; + page.DrawPolyline(ElevationPrinter.DatumCircle(x, y, r, 25), pen, true); + DrawLabel(page, document, mark.BodyId, BuiltInParameter.VIEWER_SHEET_NUMBER, number, x, y, 0, 1); + + double direction = Math.Atan2(dy, dx); + var points = new List<(double X, double Y)> { (x + dx * tipLength, y + dy * tipLength) }; + for (int i = 0; i <= 12; i++) + { + double a = direction + mark.ArrowHalfAngle * (2.0 * i / 12 - 1); + points.Add((x + r * Math.Cos(a), y + r * Math.Sin(a))); + } + page.DrawPolyline(points, pen, true, mark.Filled ? 0 : null); + DrawLabel(page, document, mark.ArrowSymbolId, BuiltInParameter.VIEWER_DETAIL_NUMBER, detail, x, y, dx, dy); + } + } + + private static void DrawLabel(PdfPage page, RvtDocument document, int symbolId, BuiltInParameter parameter, + string value, double x, double y, double dx, double dy) + { + var label = document.RawData.TitleBlockLabels?.GetValueOrDefault(symbolId) + ?.FirstOrDefault(candidate => candidate.ParamId == (int)parameter); + if (label is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || page.Owner.Font is not { } font) return; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double height = label.Height * FeetToMillimetres; + double size = SheetComposer.SymbolLabelTextSize(font, height, cap); + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + SheetComposer.DrawTitleBlockText(page, [label.Prefix + value + label.Suffix], + x + (label.Ox * dy + label.Oy * dx) * FeetToMillimetres, + y + (-label.Ox * dx + label.Oy * dy) * FeetToMillimetres, + size, height, label.Flags, 1, 0, 0, 1, opaque); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Columns.cs b/src/RvtIO/Print/PlanPrinter.Columns.cs new file mode 100644 index 00000000..890df8ee --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Columns.cs @@ -0,0 +1,91 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record ColumnProfile(List<(double X, double Y)> Ring, + (double X, double Y, double Radius)? Circle, int CategoryId, int MaterialId); + + private static ColumnProfile? CutColumnProfile(RvtDocument document, Element column, double cut) + { + if (column.Geometry is not { Faces.Count: > 0 } geometry + || geometry.Faces.Any(face => face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(p => p.Length != 3 || !p.All(double.IsFinite)) + || face.InnerLoops is { Count: > 0 } || face.InnerVertices is { Count: > 0 })) + return null; + + var rings = ElevationPrinter.ClosedSectionRings(geometry.Faces, [0, 0, cut * FeetToMillimetres], + [0, 0, 1], [1, 0, 0], [0, 1, 0], requireClosed: true).Take(2).ToArray(); + if (rings is not [var ring]) return null; + + int materialId = column.LookupParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM)?.Value is int material + ? material : 0; + return new(ring, MatchColumnCylinder(document, geometry, cut, ring), column.CategoryId.GetValueOrDefault(), materialId); + } + + private static (double X, double Y, double Radius)? MatchColumnCylinder( + RvtDocument document, GeometryData geometry, double worldCut, List<(double X, double Y)> ring) + { + if (geometry.Instances is not [{ Transform: { Length: 12 } transform } instance] + || !ElementBuilder.IsRigidPlacement(transform) || Math.Abs(Math.Abs(transform[8]) - 1) > 1e-9 + || document.GetElement(instance.SymbolId)?.Geometry is not { } symbol) + return null; + + double localCut = (worldCut - transform[11]) / transform[8]; + foreach (var face in symbol.Faces) + { + if (face.AnalyticCylinderRadius is not (> 0 and < double.PositiveInfinity) + || face.AnalyticCylinderAxis is not { Length: 3 } axis + || Math.Abs(axis[0]) > 1e-9 || Math.Abs(axis[1]) > 1e-9 || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 + || face.AnalyticCylinderOrigin is not { Length: 3 } origin || !origin.All(double.IsFinite) + || face.OuterVertices is not { Count: >= 3 } vertices || vertices.Any(p => p.Length != 3 || !double.IsFinite(p[2])) + || localCut < vertices.Min(p => p[2]) || localCut > vertices.Max(p => p[2])) + continue; + + var centre = ElementBuilder.TransformGeometryPoint(origin, transform); + double x = centre[0] * FeetToMillimetres, y = centre[1] * FeetToMillimetres; + double radius = face.AnalyticCylinderRadius * FeetToMillimetres; + // Require the placed cut to agree with the analytic surface within the ring's join resolution. + if (ring.All(p => Math.Abs(Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y)) - radius) <= 0.1)) + return (x, y, radius); + } + return null; + } + + private static void DrawColumns(PdfPage page, RvtDocument? document, PlanContent content, double scale, double width, + Func toX, Func toY, (double X0, double Y0, double X1, double Y1)? clip) + { + var white = new PdfColor(1, 1, 1); + for (int i = 0; i < content.Columns.Count; i++) + { + if (content.ColumnProfiles?.GetValueOrDefault(i) is not { } profile) + { + var column = content.Columns[i]; + page.DrawRectangle(toX(column.X), toY(column.Y), column.Width / scale, column.Height / scale, width, 1); + continue; + } + + double cutWidth = document != null && PenWidths.TryGetWidth(document, profile.CategoryId, true, + (int)Math.Round(scale), out double savedWidth) ? savedWidth : width; + if (profile.Circle is { } circle) + { + if (clip is { } frame) + page.BeginClip(toX(frame.X0), toY(frame.Y0), toX(frame.X1) - toX(frame.X0), toY(frame.Y1) - toY(frame.Y0)); + page.DrawFilledCircle(toX(circle.X), toY(circle.Y), circle.Radius / scale, cutWidth, white, new PdfColor(0, 0, 0)); + if (clip != null) page.EndClip(); + } + else DrawClippedOutline(page, profile.Ring, toX, toY, cutWidth, white, clip); + + if (document == null || DetailAnnotations.CutGrids(document, profile.MaterialId) is not { } grids) + continue; + var hatch = clip is { } bounds + ? ElevationPrinter.ClipToWindow(profile.Ring, bounds.X0, bounds.X1, bounds.Y0, bounds.Y1) : profile.Ring; + if (hatch.Count >= 3) + FillHatch.Draw(page, hatch.Select(p => (toX(p.X), toY(p.Y))).ToList(), grids, toX(0), toY(0), 0.1); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Datums.cs b/src/RvtIO/Print/PlanPrinter.Datums.cs new file mode 100644 index 00000000..2f177959 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Datums.cs @@ -0,0 +1,97 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record PlanGrid(int TypeId, string Name, double Radius, + (double X, double Y) Start, (double X, double Y) End, + bool StartBubble, bool EndBubble, TfBlockDeserializer.DatumLeader? StartLeader, + TfBlockDeserializer.DatumLeader? EndLeader); + + internal static List? CollectPlanGrids(RvtDocument document, Element view, ViewCropFrame crop, double scale) + { + if (!crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || document.RawData.DatumExtents?.GetValueOrDefault(view.Id) is not { Normal: [0, 0, -1] } extents) + return null; + var box = SheetComposer.CropContentRect(crop); + var grids = new List(); + foreach (var element in document.Elements) + { + if (element.CategoryId != (int)BuiltInCategory.OST_Grids + || element.Location is not { CurveType: "Line", StartPoint.Length: >= 2, EndPoint.Length: >= 2 } line) + continue; + double x0 = line.StartPoint[0] * FeetToMillimetres, y0 = line.StartPoint[1] * FeetToMillimetres; + double x1 = line.EndPoint[0] * FeetToMillimetres, y1 = line.EndPoint[1] * FeetToMillimetres; + if (!ElevationPrinter.ClipSegment(x0, y0, x1, y1, box.X0, box.Y0, box.X1, box.Y1, + out _, out _, out _, out _)) continue; + var extent = extents.Datums.GetValueOrDefault(element.Id); + byte flags = extent?.Overrides ?? 0; + // shortcut: use the fallback plan drawing until per-view 2D endpoints are supported. + if ((flags & 0xF0) != 0 || (flags & 3) == 3 || ((flags >> 2) & 3) == 3 + || document.RawData.DatumHeads?.GetValueOrDefault(element.TypeId) is not + { EndSegmentLength: > 0 and < 1, BubbleAtEnd1: bool endBubble, BubbleAtEnd2: bool startBubble } head + || ElevationPrinter.CircleHeadRadius(document, head.SymbolId, "M_Grid Head - Circle") is not double radius) + return null; + + // Revit applies a fixed paper-space margin in a cropped plan with annotation cropping off. + const double modelCropDatumMarginFeetOnPaper = 43d / 512; + double margin = (view.ViewAnnotationCropActive == false ? modelCropDatumMarginFeetOnPaper + : head.EndSegmentLength.Value) * FeetToMillimetres * scale; + if (!ElevationPrinter.ClipSegment(x0, y0, x1, y1, box.X0 - margin, box.Y0 - margin, + box.X1 + margin, box.Y1 + margin, out x0, out y0, out x1, out y1)) continue; + grids.Add(new PlanGrid(element.TypeId, element.Name ?? "", radius, (x0, y0), (x1, y1), + BubbleVisible((flags >> 2) & 3, startBubble), BubbleVisible(flags & 3, endBubble), + extent?.BubbleLeader, extent?.FreeEndLeader)); + } + return grids; + + static bool BubbleVisible(int flag, bool visible) => flag == 0 ? visible : flag == 1; + } + + internal static void DrawPlanGrids(PdfPage page, RvtDocument document, List grids, + PlanContent content, double scale, double originX, double originY) + { + const double ptToMm = 25.4 / 72; + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + foreach (var grid in grids) + { + double dx = grid.End.X - grid.Start.X, dy = grid.End.Y - grid.Start.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0)) continue; + dx /= length; + dy /= length; + var start = DrawEnd(grid.Start, -1, grid.StartBubble, grid.StartLeader); + var end = DrawEnd(grid.End, 1, grid.EndBubble, grid.EndLeader); + var pattern = document.RawData.GridCenterCategories?.GetValueOrDefault(grid.TypeId) is int category + && LinePatterns.TryGetDashes(document, category, out var dashes) + ? dashes.Select(pt => pt * ptToMm).ToArray() : []; + ElevationPrinter.DrawDatumDashes(page, start.X, start.Y, end.X, end.Y, pattern); + + (double X, double Y) DrawEnd((double X, double Y) point, int side, bool show, + TfBlockDeserializer.DatumLeader? leader) + { + var endOfLine = (X: ToX(point.X), Y: ToY(point.Y)); + if (!show) return endOfLine; + var anchor = endOfLine; + if (leader != null) + { + endOfLine = (ToX(leader.End[0] * FeetToMillimetres), ToY(leader.End[1] * FeetToMillimetres)); + anchor = (ToX(leader.Anchor[0] * FeetToMillimetres), ToY(leader.Anchor[1] * FeetToMillimetres)); + double x = ToX(leader.Elbow[0] * FeetToMillimetres), y = ToY(leader.Elbow[1] * FeetToMillimetres); + page.DrawLine(endOfLine.X, endOfLine.Y, x, y, 0.1); + page.DrawLine(x, y, anchor.X, anchor.Y, 0.1); + } + double cx = anchor.X + side * dx * grid.Radius, cy = anchor.Y + side * dy * grid.Radius; + page.DrawPolyline(ElevationPrinter.DatumCircle(cx, cy, grid.Radius, 25), 0.1, true); + if (page.Owner.Font != null || grid.Name.All(c => c is >= ' ' and <= '~')) + page.DrawText(grid.Name, cx, cy - 2.17, 18 * ptToMm, PdfTextAlignment.Center); + return endOfLine; + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Dimensions.cs b/src/RvtIO/Print/PlanPrinter.Dimensions.cs new file mode 100644 index 00000000..3df32d17 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Dimensions.cs @@ -0,0 +1,93 @@ +using RvtIO.Compact; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record PrintedDimension(RevitFileInfo.PlanDimension Dimension, + RevitFileInfo.PlanDimensionStyle Style, string[] Labels, double LineWidth, double TickWidth); + + internal static List CollectPlanDimensions(RvtDocument document, int viewId, ViewCropFrame crop) + { + var data = document.RawData; + if (!crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || data.PlanDimensions?.GetValueOrDefault(viewId) is not { Count: > 0 } dimensions + || data.PlanDimensionStyles == null || data.SerializedFormatSettings is not { } formatting) + return []; + var result = new List(dimensions.Count); + foreach (var dimension in dimensions) + { + var d = dimension.Direction; + if (Math.Abs(d[2]) > 1e-8 || Math.Abs(d[0] * d[0] + d[1] * d[1] - 1) > 1e-8 + || !data.PlanDimensionStyles.TryGetValue(dimension.StyleId, out var style)) + continue; + var labels = dimension.Values.Select(value => + CompactValueFormatter.Format(value, IfcNumericUnitPlan.LengthSpecName, formatting)).ToArray(); + if (labels.Any(string.IsNullOrEmpty)) continue; + result.Add(new(dimension, style, labels.Select(label => label!).ToArray(), + PlanAnnotationWidth(document, style.LineCategory, 0.1), PlanAnnotationWidth(document, style.TickCategory, 0.5))); + } + return result; + } + + internal static double PlanAnnotationWidth(RvtDocument document, int category, double fallback) + { + if (document.RawData.GraphicsStylePens?.Values.FirstOrDefault(pen => + pen.CategoryId == category && pen.GStyleType == 1) is { PenNumber: > 0 } pen + && PenWidths.TryAnnotationWidth(document, pen.PenNumber, out double width)) + return width; + return fallback; + } + + internal static void DrawPlanDimensions(PdfPage page, List dimensions, PlanContent content, + double scale, double originX, double originY) + { + double modelToPaper = FeetToMillimetres / scale; + double X(double feet) => feet * modelToPaper - content.MinX / scale + originX; + double Y(double feet) => feet * modelToPaper - content.MinY / scale + originY; + foreach (var printed in dimensions) + { + var (dimension, style, labels, lineWidth, tickWidth) = printed; + double dx = dimension.Direction[0], dy = dimension.Direction[1]; + double ox = dimension.Origin[0], oy = dimension.Origin[1]; + var along = dimension.References.Select(point => ((point[0] - ox) * dx + (point[1] - oy) * dy) + * modelToPaper).ToArray(); + double first = along[0], last = along[^1]; + double extension = style.LineExtensionFeet * FeetToMillimetres; + Line(Math.Min(first, last) - extension, 0, Math.Max(first, last) + extension, 0, lineWidth); + double tick = style.TickSizeFeet * FeetToMillimetres / 2; + for (int i = 0; i < along.Length; i++) + { + var reference = dimension.References[i]; + double distance = (-(reference[0] - ox) * dy + (reference[1] - oy) * dx) * modelToPaper; + double side = Math.Sign(distance); + double gap = style.WitnessGapFeet * FeetToMillimetres; + Line(along[i], distance - side * gap, along[i], side * style.WitnessExtensionFeet * FeetToMillimetres, lineWidth); + Line(along[i] - tick, -tick, along[i] + tick, tick, tickWidth); + } + + if (page.Owner.Font is not { } font) continue; + double textHeight = style.TextHeightFeet * FeetToMillimetres + / (font.CapHeight > 0 ? (double)font.CapHeight / font.UnitsPerEm : 0.7); + double textGap = style.TextGapFeet * FeetToMillimetres - textHeight * font.Descent / font.UnitsPerEm; + double rotation = Math.Atan2(dy, dx) * 180 / Math.PI; + if (rotation < -89.999) { rotation += 180; textGap = -textGap; } + else if (rotation > 90.001) { rotation -= 180; textGap = -textGap; } + for (int i = 0; i < labels.Length; i++) + { + double middle = (along[i] + along[i + 1]) / 2; + page.DrawTextRotated(labels[i], X(ox) + middle * dx - textGap * dy, + Y(oy) + middle * dy + textGap * dx, textHeight, rotation, PdfTextAlignment.Center); + } + + void Line(double u0, double v0, double u1, double v1, double width) + { + page.DrawLine(X(ox) + u0 * dx - v0 * dy, Y(oy) + u0 * dy + v0 * dx, + X(ox) + u1 * dx - v1 * dy, Y(oy) + u1 * dy + v1 * dx, width); + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs b/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs new file mode 100644 index 00000000..fb353fcf --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs @@ -0,0 +1,78 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static double? PlanCutHeight(RvtDocument document, int viewId) + { + if (document.RawData.PlanViewRanges?.GetValueOrDefault(viewId) is not + ({ Length: > 0 } offsets, { Length: > 0 } levels) + || document.GetElement(levels[0])?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double level) + return null; + double cut = level + offsets[0]; + return double.IsFinite(cut) ? cut : null; + } + + private static DoorPlanSymbol? SelectDoorPlanSymbol( + IReadOnlyList symbols, double[] matrix, double worldCut, double[]? bounds) + { + if (matrix.Length != 12 || !matrix.All(double.IsFinite) || !double.IsFinite(worldCut)) return null; + const double tolerance = 1e-9; + if (Math.Abs(matrix[6]) > tolerance || Math.Abs(matrix[7]) > tolerance + || Math.Abs(matrix[8] - 1) > tolerance + || Math.Abs(matrix[0] * matrix[0] + matrix[3] * matrix[3] - 1) > tolerance + || Math.Abs(matrix[1] * matrix[1] + matrix[4] * matrix[4] - 1) > tolerance + || Math.Abs(matrix[0] * matrix[1] + matrix[3] * matrix[4]) > tolerance) + return null; + + double localCut = worldCut - matrix[11]; + DoorPlanSymbol? found = null; + foreach (var symbol in symbols) + { + bool matches = symbol.CutRange is { } range + ? localCut >= range.Lo && localCut <= range.Hi + : bounds is { Length: 6 } && worldCut >= bounds[2] && worldCut <= bounds[5]; + if (!matches) continue; + if (found != null) return null; + found = symbol; + } + return found; + } + + private static void DrawDoorPlanSymbol(PdfPage page, DoorPlanSymbol symbol, double[] matrix, double scale, + Func toX, Func toY, (double X0, double Y0, double X1, double Y1)? clip) + { + (double X, double Y) Direction(double[] vector) => + (matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2], + matrix[3] * vector[0] + matrix[4] * vector[1] + matrix[5] * vector[2]); + foreach (var curve in symbol.Curves) + { + var c = Direction(curve.C); + var x = Direction(curve.X); + double cx = (c.X + matrix[9]) * FeetToMillimetres; + double cy = (c.Y + matrix[10]) * FeetToMillimetres; + if (curve.R > 0) + { + var y = Direction(curve.Y); + double orientation = Math.Sign(x.X * y.Y - x.Y * y.X); + double angle = Math.Atan2(x.Y, x.X); + page.DrawArc(toX(cx), toY(cy), curve.R * FeetToMillimetres / scale, + (angle + orientation * curve.T0) * 180 / Math.PI, + (angle + orientation * curve.T1) * 180 / Math.PI, 0.18); + continue; + } + + double x0 = cx + curve.T0 * x.X * FeetToMillimetres; + double y0 = cy + curve.T0 * x.Y * FeetToMillimetres; + double x1 = cx + curve.T1 * x.X * FeetToMillimetres; + double y1 = cy + curve.T1 * x.Y * FeetToMillimetres; + if (clip is { } bounds && !ElevationPrinter.ClipSegment(x0, y0, x1, y1, + bounds.X0, bounds.Y0, bounds.X1, bounds.Y1, out x0, out y0, out x1, out y1)) + continue; + page.DrawLine(toX(x0), toY(y0), toX(x1), toY(y1), 0.18); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs b/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs new file mode 100644 index 00000000..fc3e32ed --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs @@ -0,0 +1,244 @@ +using RvtIO.Geometry.Meshing; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private sealed record FixtureFacet(List World, List<(double X, double Y)> Ring, + double Left, double Bottom, double Right, double Top, double MaxZ); + + private static List<(double X1, double Y1, double X2, double Y2)>? FixtureProfiles(GeometryData geometry) + { + if (geometry is not { BrepSolids.Count: > 1, UnresolvedSymbol: false, PlacedSymbolBox: false, + PlacedSymbolClipped: false, UntriangulatedFaces: 0 } + || geometry.BrepSolids.Any(solid => !solid.IsClosed || solid.FaceIndices.Count == 0)) + return null; + + var groups = new List>(); + var faces = geometry.Faces; + var assigned = new HashSet(); + foreach (var solid in geometry.BrepSolids) + { + var facets = new List(); + var members = new HashSet(); + bool decoded = true; + foreach (int index in solid.FaceIndices) + { + if ((uint)index >= faces.Count || !members.Add(index)) return null; + // The reader can deduplicate an identical face referenced by different closed solids. + assigned.Add(index); + if (decoded) decoded = AddFacets(faces[index], facets); + } + if (!decoded) + { + facets.Clear(); + if (!MeshFixtureSolid(geometry, solid, facets)) return null; + } + if (facets.Count == 0) return null; + groups.Add(facets); + } + if (assigned.Count != faces.Count) return null; + + var segments = new List(); + for (int i = 0; i < groups.Count; i++) + { + var group = groups[i]; + var otherFacets = groups.Where((_, index) => index != i).SelectMany(part => part).ToList(); + var rings = group.Select(facet => facet.Ring).ToList(); + var sources = group.SelectMany(facet => Enumerable.Range(0, facet.Ring.Count).Select(vertex => + { + int next = (vertex + 1) % facet.Ring.Count; + var a = facet.Ring[vertex]; + var b = facet.Ring[next]; + var (start, end) = a.CompareTo(b) <= 0 + ? (facet.World[vertex], facet.World[next]) : (facet.World[next], facet.World[vertex]); + return (Key: ElevationPrinter.ProjectedEdgeKey(a.X, a.Y, b.X, b.Y), Start: start, End: end); + })).ToLookup(source => source.Key); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, 0, coverOppositeEdges: true, retainSource: true)) + { + var (ring, vertex) = edge.SourceRingEdge!.Value; + var a = rings[ring][vertex]; + var b = rings[ring][(vertex + 1) % rings[ring].Count]; + var key = ElevationPrinter.ProjectedEdgeKey(a.X, a.Y, b.X, b.Y); + // Several edges at different heights can share a projected silhouette. + // Any visible span of the original edges contributes to the outline. + foreach (var source in sources[key].DistinctBy(source => (source.Start[2], source.End[2]))) + AddVisible(edge, source.Start, source.End, otherFacets); + } + + double height = geometry.BrepSolids[i].FaceIndices.Max(index => + faces[index].OuterVertices!.Max(point => point[2])); + foreach (int index in geometry.BrepSolids[i].FaceIndices) + { + // An upward cap with a hole defines the visible rims of the vessel. + if (faces[index] is not { PlaneSurface: true, Normal: [_, _, > 0.999999], + OuterVertices: { } outer, InnerVertices: { Count: > 0 } holes } + || outer.Any(p => Math.Abs(p[2] - height) > 1e-8) + || holes.Any(hole => hole.Any(p => Math.Abs(p[2] - height) > 1e-8))) + continue; + (outer, holes) = ResampleFixtureArcs(faces[index], outer, holes); + foreach (var loop in holes.Prepend(outer)) + for (int j = 0; j < loop.Count; j++) + { + var a = loop[j]; + var b = loop[(j + 1) % loop.Count]; + var start = InPlan(a); + var end = InPlan(b); + AddVisible(new(start.X, start.Y, end.X, end.Y, 0, 0, -1, -1, 0, 0, 0, 0), + a, b, otherFacets); + } + } + } + + if (segments.Count == 0) return null; + return ElevationPrinter.MergeOverlaps(segments).Select(edge => + (edge.X1, edge.Y1, edge.X2, edge.Y2)).ToList(); + + void AddVisible(ElevationPrinter.CollectedEdge edge, double[] a, double[] b, + List otherFacets) + { + double dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2]; + double lengthSquared = dx * dx + dy * dy; + if (lengthSquared < 1e-12) return; + + // Along this edge the plane has the same height as the original straight segment. + // A projected face can obscure it only where the face lies above that plane. + double[] origin = [a[0], a[1], a[2] + 1e-8]; + double[] normal = [-dx * dz / lengthSquared, -dy * dz / lengthSquared, 1]; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double bottom = Math.Min(edge.Y1, edge.Y2), top = Math.Max(edge.Y1, edge.Y2); + var covers = otherFacets.Where(facet => facet.MaxZ >= Math.Min(a[2], b[2]) + && facet.Left <= right && facet.Right >= left && facet.Bottom <= top && facet.Top >= bottom) + .Select(facet => ElevationPrinter.ClipBehind(facet.World, origin, normal).Select(InPlan).ToList()) + .Where(ring => ring.Count >= 3 && Math.Abs(SignedArea(ring)) > 1e-8); + foreach (var span in ElevationPrinter.VisibleTerrainEdges([edge], covers, [], coverBoundary: false)) + segments.Add((span.X1, span.Y1).CompareTo((span.X2, span.Y2)) <= 0 ? span + : span with { X1 = span.X2, Y1 = span.Y2, X2 = span.X1, Y2 = span.Y1 }); + } + } + + private static (List Outer, List> Holes) ResampleFixtureArcs( + GeoFace face, List outer, List> holes) + { + if (face is not { PlaneSurface: true, Normal: [_, _, var z], MeshArcs: { Count: > 0 } arcs } + || !(Math.Abs(z) > 0.999999)) return (outer, holes); + + // A split face carries the arc list of the source face. Match only runs on this region. + var regionArcs = new List(); + foreach (var ring in holes.Prepend(outer)) + { + var occupied = new HashSet(); + foreach (var run in IfcExporter.FindArcRunsCurrent(ring, arcs)) + { + for (int i = 0; i < run.Steps; i++) + if (!occupied.Add((run.First + i) % ring.Count)) return (outer, holes); + regionArcs.Add(run.Arc); + } + } + return IfcExporter.TryResampleArcsCurrent(outer, holes, regionArcs, + out var curvedOuter, out var curvedHoles, out _) ? (curvedOuter, curvedHoles) : (outer, holes); + } + + private static bool AddFacets(GeoFace face, List facets) + { + if (face.OuterVertices is not { Count: >= 3 } outer + || face.InnerLoops?.Count > (face.InnerVertices?.Count ?? 0)) return false; + var holes = face.InnerVertices ?? []; + var contours = holes.Prepend(outer).ToList(); + if (contours.Any(loop => loop.Count < 3 || loop.Any(p => p.Length != 3 || !p.All(double.IsFinite)))) + return false; + (outer, holes) = ResampleFixtureArcs(face, outer, holes); + contours = holes.Prepend(outer).ToList(); + var projected = contours.Select(loop => loop.Select(InPlan).ToList()).ToList(); + if (holes.Count == 0 && (face.PlaneSurface || outer.Count == 3)) + { + AddFixtureFacet(outer, projected[0], facets); + return true; + } + + var world = contours.SelectMany(loop => loop).ToArray(); + var plan = projected.SelectMany(loop => loop).ToArray(); + if (face.Normal is not { Length: 3 } normal || !normal.All(double.IsFinite) + || normal.All(value => value == 0)) return false; + // A curved patch can fold over itself in plan. Triangulate its native ring in the + // dominant plane of the patch normal, then project the individual triangles. + int axis = Array.IndexOf(normal, normal.MaxBy(value => Math.Abs(value))); + var local = world.Select(p => (X: p[(axis + 1) % 3], Y: p[(axis + 2) % 3])).ToArray(); + int offset = 0; + var indices = contours.Select(loop => + { + var range = Enumerable.Range(offset, loop.Count).ToArray(); + offset += loop.Count; + return range; + }).ToArray(); + var outerFlags = new bool[indices.Length]; + outerFlags[0] = true; + double outerArea = Math.Abs(SignedArea(indices[0].Select(index => local[index]).ToList())); + if (outerArea < 1e-12) return true; + double expected = outerArea - indices.Skip(1).Sum(loop => + Math.Abs(SignedArea(loop.Select(index => local[index]).ToList()))); + double area = 0; + foreach (var (a, b, c) in GeTess.TriangulateProfile(local, indices, outerFlags)) + { + area += Math.Abs(SignedArea([local[a], local[b], local[c]])); + AddFixtureFacet([world[a], world[b], world[c]], [plan[a], plan[b], plan[c]], facets); + } + return expected > 0 && Math.Abs(area - expected) <= 1e-7 * outerArea; + } + + private static bool MeshFixtureSolid(GeometryData geometry, GeoBrepSolid solid, List facets) + { + var source = solid.FaceIndices.Select(index => geometry.Faces[index]).ToArray(); + int id = source[0].GeometryNode; + if (id <= 0 || source.Any(face => face.GeometryNode != id) + || geometry.MeshNodes?.Where(node => node.Node == id && !node.Ghost).Take(2).ToArray() + is not [var meshNode] + || meshNode.Placement is not { Length: 12 } placement + || !ElementBuilder.IsRigidPlacement(placement)) return false; + + var markers = meshNode.Faces.Select(face => (uint)face.Marker).ToHashSet(); + if (source.Any(face => !markers.Contains(face.SourceFace != 0 ? face.SourceFace : face.MeshMarker))) + return false; + + // Some curved trims fold across a projection of the dense polygons. In that case use + // the same authored surface and edge sampler used to mesh the node for export. + const double lod = 0.2; + bool freeform = meshNode.Faces.Any(FreeformSolid.IsFreeform); + var sampler = freeform ? FreeformSolid.Create(meshNode.Faces, lod, meshNode.Diagonal) : null; + if (freeform && sampler == null) return false; + foreach (var face in meshNode.Faces) + { + bool ok = FreeformSolid.IsFreeform(face) ? sampler!.TryMesh(face, out var mesh) + : FaceMesher.TryMesh(GRepParserV2.WithSamples(face, lod, meshNode.Diagonal, sampler), + lod, meshNode.Diagonal, out mesh); + if (!ok) return false; + var world = mesh.Vertices.Select(point => ElementBuilder.TransformGeometryPoint(point, placement)).ToArray(); + if (world.Any(point => !point.All(double.IsFinite))) return false; + var plan = world.Select(InPlan).ToArray(); + foreach (var triangle in mesh.Triangles) + AddFixtureFacet([world[triangle[0]], world[triangle[1]], world[triangle[2]]], + [plan[triangle[0]], plan[triangle[1]], plan[triangle[2]]], facets); + } + return facets.Count > 0; + } + + private static void AddFixtureFacet(List vertices, List<(double X, double Y)> ring, + List facets) + { + double signed = SignedArea(ring); + if (Math.Abs(signed) < 1e-8) return; + if (signed < 0) + { + vertices = [.. vertices.AsEnumerable().Reverse()]; + ring.Reverse(); + } + facets.Add(new(vertices, ring, ring.Min(p => p.X), ring.Min(p => p.Y), + ring.Max(p => p.X), ring.Max(p => p.Y), vertices.Max(p => p[2]))); + } + + private static (double X, double Y) InPlan(double[] point) => + (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres); +} diff --git a/src/RvtIO/Print/PlanPrinter.Furniture.cs b/src/RvtIO/Print/PlanPrinter.Furniture.cs new file mode 100644 index 00000000..9a14eac8 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Furniture.cs @@ -0,0 +1,169 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private sealed record FurnitureFace(List<(double X, double Y)> Outer, List> Holes, + double MinX, double MaxX, double MinY, double MaxY); + + internal static (double Bottom, double Cut, double Top)? GetPlanRange(RvtDocument document, int levelId, int? viewId) + { + if (viewId is not int id || document.RawData.PlanViewRanges?.TryGetValue(id, out var range) != true + || range.Offsets is not { Length: >= 3 } || range.LevelIds is not { Length: >= 3 }) return null; + double bottom = Plane(2, double.NegativeInfinity), cut = Plane(0, double.NaN), top = Plane(1, double.PositiveInfinity); + return bottom <= cut && cut <= top && double.IsFinite(cut) ? (bottom, cut, top) : null; + + double Plane(int index, double unlimited) + { + int level = range.LevelIds[index]; + if (level == -4) return unlimited; + if (level == -1) level = levelId; + return document.GetElement(level)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double height + ? height + range.Offsets[index] : double.NaN; + } + } + + private static bool FurnitureInView(Element element, int levelId, (double Bottom, double Cut, double Top)? range) + { + if (range is { } planes && element.BoundingBox is { Length: 6 } box + && double.IsFinite(box[2]) && box[2] <= box[5] && double.IsFinite(box[5])) + { + double upper = element.CategoryId == (int)BuiltInCategory.OST_Casework ? planes.Top : planes.Cut; + return box[5] >= planes.Bottom && box[2] <= upper; + } + return LevelOf(element) == levelId; + } + + private static bool FixtureProjectionCoversBody(PlanFixtureProjection projection, GeometryData geometry) + => projection.Masks is [{ Count: >= 3 } mask] && HorizontalMaskCoversBody(mask, geometry); + + private static bool HorizontalMaskCoversBody(List mask, GeometryData geometry) + { + var ring = mask.Select(InPlan).ToList(); + double area = SignedArea(ring); + if (Math.Abs(area) < 1e-8) return false; + if (area < 0) ring.Reverse(); + + // A convex mask contains the full projection of a face when it contains its vertices. + for (int i = 0; i < ring.Count; i++) + if (Side(ring[i], ring[(i + 1) % ring.Count], ring[(i + 2) % ring.Count]) < -1e-7) + return false; + return geometry.Faces.Where(face => !face.ExcludedFromTopPlan) + .All(face => face.OuterVertices is { Count: >= 3 } vertices && vertices.All(point => + { + if (point[2] > mask[0][2] + 1e-7) return false; + var xy = InPlan(point); + for (int i = 0; i < ring.Count; i++) + if (Side(ring[i], ring[(i + 1) % ring.Count], xy) < -1e-7) return false; + return true; + })); + + static double Side((double X, double Y) a, (double X, double Y) b, (double X, double Y) point) => + (b.X - a.X) * (point.Y - a.Y) - (b.Y - a.Y) * (point.X - a.X); + } + + internal static void DrawFixtureLines(PdfPage page, RvtDocument? document, + List<(double X1, double Y1, double X2, double Y2, int StyleId)> lines, + double scale, double fallbackWidth, Func toX, Func toY, + (double X0, double Y0, double X1, double Y1)? clip) + { + foreach (var group in lines.GroupBy(line => line.StyleId)) + { + var color = new PdfColor(0, 0, 0); + double pen = fallbackWidth; + double[]? dashes = null; + if (document?.RawData.GraphicsStylePens?.TryGetValue(group.Key, out var style) == true && style.GStyleType == 1) + { + color = new PdfColor((style.Color & 255) / 255d, ((style.Color >> 8) & 255) / 255d, + ((style.Color >> 16) & 255) / 255d); + if (document.RawData.PenWidthTable is { } widths + && PenWidths.TryPenWidth(widths, style.PenNumber, (int)Math.Round(scale), out double savedWidth)) + pen = savedWidth; + if (LinePatterns.TryGetPatternDashes(document, style.LinePatternId, out var savedDashes)) + dashes = savedDashes; + } + foreach (var (x1, y1, x2, y2, _) in group) + { + double a = x1, b = y1, c = x2, d = y2; + if (clip is { } bounds && !ElevationPrinter.ClipSegment(a, b, c, d, + bounds.X0, bounds.Y0, bounds.X1, bounds.Y1, out a, out b, out c, out d)) + continue; + if (dashes != null) + page.SetDashPoints(LinePatterns.FitEndpointDashes(Math.Sqrt((c - a) * (c - a) + (d - b) * (d - b)) / scale * 72 / 25.4, dashes)); + page.DrawLine(toX(a), toY(b), toX(c), toY(d), pen, color); + if (dashes != null) page.ResetDash(); + } + } + } + + private static List FurnitureFaces(IEnumerable faces) + { + var result = new List(); + foreach (var face in faces) + { + if (face.OuterVertices is not { Count: >= 3 } vertices || Project(vertices, true) is not { } outer) continue; + var holes = new List>(); + foreach (var inner in face.InnerVertices ?? []) + if (Project(inner, false) is { } hole) holes.Add(hole); + result.Add(new(outer, holes, outer.Min(p => p.X), outer.Max(p => p.X), + outer.Min(p => p.Y), outer.Max(p => p.Y))); + } + return result; + + static List<(double X, double Y)>? Project(List vertices, bool isOuter) + { + if (vertices.Count < 3 || vertices.Any(v => v.Length < 2 || !(Math.Abs(v[0]) < 1e6 && Math.Abs(v[1]) < 1e6))) + return null; + var points = vertices.Select(v => (X: v[0] * FeetToMillimetres, Y: v[1] * FeetToMillimetres)).ToList(); + double area = SignedArea(points); + if (Math.Abs(area) < 1e-8) return null; + if ((area > 0) != isOuter) points.Reverse(); + return points; + } + } + + // shortcut: the silhouette stroke uses a 5 mm grid; the opaque fill uses the projected face rings. + private static List<(double X1, double Y1, double X2, double Y2)> SilhouetteLines( + List faces, double cell) + { + if (faces.Count == 0) return []; + double x0 = faces.Min(face => face.MinX), x1 = faces.Max(face => face.MaxX); + double y0 = faces.Min(face => face.MinY), y1 = faces.Max(face => face.MaxY); + int nx = (int)Math.Ceiling((x1 - x0) / cell) + 1; + int ny = (int)Math.Ceiling((y1 - y0) / cell) + 1; + if (nx < 1 || ny < 1 || (long)nx * ny > 400_000) return []; + var inside = new bool[nx, ny]; + foreach (var face in faces) + { + int startX = Math.Max(0, (int)Math.Floor((face.MinX - x0) / cell)); + int startY = Math.Max(0, (int)Math.Floor((face.MinY - y0) / cell)); + int endX = Math.Min(nx - 1, (int)Math.Floor((face.MaxX - x0) / cell)); + int endY = Math.Min(ny - 1, (int)Math.Floor((face.MaxY - y0) / cell)); + for (int i = startX; i <= endX; i++) + for (int j = startY; j <= endY; j++) + { + if (inside[i, j]) continue; + double cx = x0 + (i + 0.5) * cell, cy = y0 + (j + 0.5) * cell; + inside[i, j] = PointInPolygon(cx, cy, face.Outer) + && !face.Holes.Any(hole => PointInPolygon(cx, cy, hole)); + } + } + var lines = new List<(double X1, double Y1, double X2, double Y2)>(); + for (int i = 0; i < nx; i++) + for (int j = 0; j < ny; j++) + { + if (!inside[i, j]) continue; + double left = x0 + i * cell, right = left + cell; + double bottom = y0 + j * cell, top = bottom + cell; + if (i == 0 || !inside[i - 1, j]) lines.Add((left, bottom, left, top)); + if (i == nx - 1 || !inside[i + 1, j]) lines.Add((right, bottom, right, top)); + if (j == 0 || !inside[i, j - 1]) lines.Add((left, bottom, right, bottom)); + if (j == ny - 1 || !inside[i, j + 1]) lines.Add((left, top, right, top)); + } + return lines; + } +} diff --git a/src/RvtIO/Print/PlanPrinter.GenericModels.cs b/src/RvtIO/Print/PlanPrinter.GenericModels.cs new file mode 100644 index 00000000..9ae789ae --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.GenericModels.cs @@ -0,0 +1,75 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static void CollectSectionedGenericModel(GeometryData geometry, double bottom, double cut, + List> masks, + ref List<(double X1, double Y1, double X2, double Y2, bool Cut)>? lines) + { + if (geometry is not { BrepSolids.Count: > 0, UnresolvedSymbol: false, PlacedSymbolBox: false, + PlacedSymbolClipped: false, UntriangulatedFaces: 0 }) return; + var faces = geometry.Faces; + var members = new HashSet(); + var projection = new List>(); + var sections = new List>(); + double[] lower = [0, 0, bottom], upper = [0, 0, cut]; + double[] up = [0, 0, 1], down = [0, 0, -1]; + foreach (var solid in geometry.BrepSolids) + { + if (!solid.IsClosed || solid.FaceIndices.Count == 0 + || solid.FaceIndices.Any(index => (uint)index >= (uint)faces.Count)) return; + + var crossing = new List(); + foreach (int index in solid.FaceIndices) + { + var face = faces[index]; + if (face.ExcludedFromTopPlan || face.CurvedSurface + || face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 } + || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(point => point.Length != 3 || !point.All(double.IsFinite))) return; + double min = vertices.Min(point => point[2]), max = vertices.Max(point => point[2]); + if (min < cut && max > cut) crossing.Add(face); + if (!members.Add(index) || max < bottom || min > cut) continue; + var clipped = min < bottom ? ElevationPrinter.ClipBehind(vertices, lower, up) : vertices; + if (max > cut) clipped = ElevationPrinter.ClipBehind(clipped, upper, down); + if (clipped.Count < 3) continue; + + var ring = clipped.Select(InPlan).ToList(); + double area = SignedArea(ring); + if (Math.Abs(area) < 1e-8) continue; + if (area < 0) ring.Reverse(); + projection.Add(ring); + } + + if (crossing.Count == 0) continue; + var rings = ElevationPrinter.ClosedSectionRings(crossing, [0, 0, cut * FeetToMillimetres], up, + [1, 0, 0], [0, 1, 0], requireClosed: true).ToList(); + // shortcut: nested cut rings need a mask with holes. + if (rings.Count == 0 || rings.Any(ring => rings.Any(other => other != ring + && PointInPolygon(ring[0].X, ring[0].Y, other)))) return; + foreach (var ring in rings) + { + if (SignedArea(ring) < 0) ring.Reverse(); + sections.Add(ring); + } + } + if (members.Count != faces.Count || sections.Count == 0) return; + + projection.AddRange(sections); + // A thin projected facet can have distinct boundaries within the same snapped coordinate. + var outline = ElevationPrinter.OutlineJoinedRings(projection, (int)BuiltInCategory.OST_GenericModel, + coverOppositeEdges: true, snapEndpoints: false).ToList(); + if (outline.Count == 0) return; + masks.AddRange(projection); + lines ??= []; + // Reverse cut rings so their coincident spans cover the projection edges as well as their interiors. + var cutMasks = sections.Select(ring => ring.AsEnumerable().Reverse().ToList()); + lines.AddRange(ElevationPrinter.VisibleTerrainEdges(outline, cutMasks, [], coverOppositeEdges: true) + .Select(edge => (edge.X1, edge.Y1, edge.X2, edge.Y2, false))); + lines.AddRange(ElevationPrinter.OutlineJoinedRings(sections, (int)BuiltInCategory.OST_GenericModel, + coverOppositeEdges: true).Select(edge => (edge.X1, edge.Y1, edge.X2, edge.Y2, true))); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Notes.cs b/src/RvtIO/Print/PlanPrinter.Notes.cs new file mode 100644 index 00000000..8db07033 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Notes.cs @@ -0,0 +1,108 @@ +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal static void DrawPlanNotes(PdfPage page, RvtDocument document, int viewId, ViewCropFrame crop, + PlanContent content, double scale, double originX, double originY) + { + if (page.Owner.Font == null || !crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) + || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || document.RawData.PlanNotes?.GetValueOrDefault(viewId) is not { Count: > 0 } notes) return; + + double X(double feet) => (feet * FeetToMillimetres - content.MinX) / scale + originX; + double Y(double feet) => (feet * FeetToMillimetres - content.MinY) / scale + originY; + + foreach (var note in notes) + DrawTextNote(page, document, note, X, Y); + } + + internal static bool DrawTextNote(PdfPage page, RvtDocument document, RevitFileInfo.PlanNote note, + Func toX, Func toY) + { + if (page.Owner.Font is not { } font) return false; + (double X, double Y) Point(double[] feet) => (toX(feet[0]), toY(feet[1])); + double width = note.WidthFeet * FeetToMillimetres, height = note.HeightFeet * FeetToMillimetres; + double padding = note.PaddingFeet * FeetToMillimetres; + double x = toX(note.X), y = toY(note.Y); + double pen = PlanAnnotationWidth(document, note.CategoryId, 0.1); + foreach (var leader in note.Leaders) + DrawPlanNoteLeader(page, Point(leader.End), Point(leader.Elbow), Point(leader.Anchor), + note.ArcLeaders, note.ArrowSizeFeet * FeetToMillimetres, note.ArrowAngle, pen); + if (note.Opaque) + page.DrawRectangle(x, y - height, width, height, 0, 1); + if (note.HasBorder) + page.DrawRectangle(x - padding, y - height - padding, width + 2 * padding, height + 2 * padding, pen); + + double size = note.FontPoints * 25.4 / 72; + var lines = WrapPlanNoteText(page, note.Text, size, width, note.Wrap); + double baseline = y - size * font.Ascent / font.UnitsPerEm; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], x, baseline - i * height / lines.Count, size); + return true; + } + + internal static IReadOnlyList WrapPlanNoteText(PdfPage page, string text, double size, double width, bool wrap) + { + var paragraphs = text.Split('\n'); + if (!wrap) return paragraphs; + + var lines = new List(); + foreach (string paragraph in paragraphs) + { + if (page.MeasureText(paragraph, size) <= width) + { + lines.Add(paragraph); + continue; + } + string line = ""; + var words = paragraph.Split(' ', StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < words.Length; i++) + { + // The space after a word counts toward the saved wrapping width. + string token = i == words.Length - 1 ? words[i] : words[i] + " "; + if (line.Length > 0 && page.MeasureText(line + token, size) > width) + { + lines.Add(line.TrimEnd()); + line = token; + } + else line += token; + } + lines.Add(line.TrimEnd()); + } + return lines; + } + + private static void DrawPlanNoteLeader(PdfPage page, (double X, double Y) end, (double X, double Y) elbow, + (double X, double Y) anchor, bool arc, double arrowSize, double arrowAngle, double pen) + { + double ux = elbow.X - end.X, uy = elbow.Y - end.Y; + double vx = anchor.X - end.X, vy = anchor.Y - end.Y; + double det = 2 * (ux * vy - uy * vx); + double direction = Math.Atan2(uy, ux); + if (arc && Math.Abs(det) > 1e-8) + { + double u = ux * ux + uy * uy, v = vx * vx + vy * vy; + double cx = (u * vy - v * uy) / det, cy = (ux * v - vx * u) / det; + double radius = Math.Sqrt(cx * cx + cy * cy); + double start = Math.Atan2(-cy, -cx), through = Math.Atan2(uy - cy, ux - cx); + double finish = Math.Atan2(vy - cy, vx - cx); + double sweep = (finish - start + 2 * Math.PI) % (2 * Math.PI); + if ((through - start + 2 * Math.PI) % (2 * Math.PI) > sweep) sweep -= 2 * Math.PI; + page.DrawArc(end.X + cx, end.Y + cy, radius, start * 180 / Math.PI, (start + sweep) * 180 / Math.PI, pen); + direction = start + Math.CopySign(Math.PI / 2, sweep); + } + else + { + page.DrawLine(end.X, end.Y, elbow.X, elbow.Y, pen); + page.DrawLine(elbow.X, elbow.Y, anchor.X, anchor.Y, pen); + } + + if (arrowSize <= 0) return; + double a = direction - arrowAngle / 2, b = direction + arrowAngle / 2; + page.DrawLine(end.X, end.Y, end.X + arrowSize * Math.Cos(a), end.Y + arrowSize * Math.Sin(a), pen); + page.DrawLine(end.X, end.Y, end.X + arrowSize * Math.Cos(b), end.Y + arrowSize * Math.Sin(b), pen); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.OpeningTags.cs b/src/RvtIO/Print/PlanPrinter.OpeningTags.cs new file mode 100644 index 00000000..9d3e8bdb --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.OpeningTags.cs @@ -0,0 +1,60 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool DrawPlanOpeningTags(PdfPage page, RvtDocument? document, int? viewId, + Func toX, Func toY) + { + if (document == null || viewId is not int view || page.Owner.Font == null + || document.RawData.PlanOpeningTags?.GetValueOrDefault(view) is not { Count: > 0 } tags + || document.RawData.PlanOpeningTagStyles is not { Count: > 0 } styles) return false; + + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(view); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(view); + bool ownTags = false; + foreach (var tag in tags) + { + var element = document.GetElement(tag.ElementId); + if (element == null) continue; + // The tag of a hidden host stays unprinted and still stands for the view's own tags: the generated marks + // are for a view that has none, not for the openings that remain untagged. + if (hidden?.Contains(element.Id) == true + || element.CategoryId is int category && hiddenCategories?.Contains(category) == true) + { + ownTags = true; + continue; + } + if (!styles.TryGetValue(tag.SymbolId, out var style)) continue; + var label = style.Label; + var owner = label.ParamId == (int)BuiltInParameter.ALL_MODEL_TYPE_MARK + ? document.GetElement(element.TypeId) : element; + if (owner?.LookupParameter((BuiltInParameter)label.ParamId)?.Value is not string { Length: > 0 } value) + continue; + double x = toX(tag.X * FeetToMillimetres), y = toY(tag.Y * FeetToMillimetres); + double pen = PlanAnnotationWidth(document, + element.CategoryId == (int)BuiltInCategory.OST_Windows + ? (int)BuiltInCategory.OST_WindowTags : (int)BuiltInCategory.OST_DoorTags, 0.1); + DrawTagSymbol(page, style, value, x, y, pen); + ownTags = true; + } + return ownTags; + } + + internal static void DrawTagSymbol(PdfPage page, Model.RevitFileInfo.PlanOpeningTagStyle style, string value, + double x, double y, double pen) + { + if (page.Owner.Font is not { } font) return; + var label = style.Label; + var (labelX, _, baseline, size, alignment) = AnnotationLabelLayout(font, label, style.FontPoints, x, y); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var arc in style.Arcs) + page.DrawArc(x + arc.X * FeetToMillimetres, y + arc.Y * FeetToMillimetres, + arc.Radius * FeetToMillimetres, arc.Start, arc.End, pen); + page.DrawText(label.Prefix + value + label.Suffix, labelX, baseline, size, alignment); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.RoomTags.cs b/src/RvtIO/Print/PlanPrinter.RoomTags.cs new file mode 100644 index 00000000..88afab03 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.RoomTags.cs @@ -0,0 +1,86 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Compact; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool DrawPlanRoomTags(PdfPage page, RvtDocument? document, int? viewId, + Func toX, Func toY) + { + if (document == null || viewId is not int view || page.Owner.Font is not { } font + || document.RawData.PlanRoomTags?.GetValueOrDefault(view) is not { Count: > 0 } tags + || document.RawData.PlanRoomTagStyles is not { Count: > 0 } styles) return false; + + double pen = PlanAnnotationWidth(document, (int)BuiltInCategory.OST_RoomTags, 0.1); + bool drawn = false; + foreach (var tag in tags) + { + if (document.GetElement(tag.RoomId) is not { CategoryId: (int)BuiltInCategory.OST_Rooms } room + || !styles.TryGetValue(tag.SymbolId, out var style)) continue; + double x = toX(tag.X * FeetToMillimetres), y = toY(tag.Y * FeetToMillimetres); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var (label, sizePoints) in style.Labels) + { + string? value = RoomTagValue(document, room, label.ParamId); + if (string.IsNullOrEmpty(value)) continue; + var (labelX, labelBottom, baseline, size, alignment) = AnnotationLabelLayout(font, label, sizePoints, x, y); + if (!(size is > 0 and < 100)) continue; + // shortcut: vertical single-label attachment only, extend after verifying the other saved attachment modes. + if (style.Labels.Count == 1 && alignment == PdfTextAlignment.Center + && tag.LeaderAnchor is { } anchor && tag.LeaderEnd is { } end + && Math.Abs(end.X - anchor.X) < 1e-8 + && Math.Abs(toX(anchor.X * FeetToMillimetres) - labelX) < 1e-6 + && Math.Abs(toY(anchor.Y * FeetToMillimetres) - labelBottom) < 1e-6) + { + double endY = toY(end.Y * FeetToMillimetres); + double attachment = endY > labelBottom ? baseline + size * font.Ascent / font.UnitsPerEm : labelBottom; + page.DrawLine(toX(end.X * FeetToMillimetres), endY, x, attachment, pen); + } + page.DrawText(label.Prefix + value + label.Suffix, labelX, baseline, size, alignment); + drawn = true; + } + } + return drawn; + } + + internal static (double X, double Bottom, double Baseline, double Size, PdfTextAlignment Alignment) + AnnotationLabelLayout(PdfTrueTypeFont font, TfBlockDeserializer.TitleBlockLabel label, double sizePoints, double x, double y) + { + const double pointsToMm = 25.4 / 72; + double size = sizePoints > 0 ? sizePoints * pointsToMm + : label.Height * FeetToMillimetres * font.UnitsPerEm / (font.Ascent - font.Descent); + var alignment = (label.Flags & 0x80) != 0 ? PdfTextAlignment.Center + : (label.Flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; + double labelBottom = y + label.Oy * FeetToMillimetres; + if ((label.Flags & 0x400) != 0) labelBottom -= label.Height * FeetToMillimetres / 2; + return (x + label.Ox * FeetToMillimetres, labelBottom, + labelBottom - size * font.Descent / font.UnitsPerEm, size, alignment); + } + + private static string LocalizeRoomArea(string value) => + CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru" + && value.EndsWith("m²", StringComparison.Ordinal) ? value[..^2] + "м²" : value; + + private static string? RoomTagValue(RvtDocument document, Element room, int parameter) + { + var value = room.LookupParameter((BuiltInParameter)parameter)?.Value; + if (parameter == (int)BuiltInParameter.ROOM_NAME) return value as string ?? room.Name; + if (parameter == (int)BuiltInParameter.ROOM_NUMBER) return value as string; + if (parameter == (int)BuiltInParameter.ROOM_AREA && document.RawData.SerializedFormatSettings is { } settings) + { + var area = value as double? ?? room.SerializedRoomPlanAreaSquareFeet + ?? SolidQuantities.RoomPlanArea(room.SerializedSpaceBoundaryCurrent); + if (area is > 0 and < double.PositiveInfinity + && CompactValueFormatter.Format(area.Value, "autodesk.spec.aec:area", settings) is { } formatted) + return LocalizeRoomArea(formatted); + } + return null; + } +} diff --git a/src/RvtIO/Print/PlanPrinter.SectionMarks.cs b/src/RvtIO/Print/PlanPrinter.SectionMarks.cs new file mode 100644 index 00000000..61c0c76a --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.SectionMarks.cs @@ -0,0 +1,108 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool TryDrawFilledSectionMark(PdfPage page, RvtDocument document, int planId, int sectionId, + IReadOnlyList<(double X, double Y)> line, (double X0, double Y0, double X1, double Y1)? frame, double pen) + { + // Filled head and tail with parallel terminal legs in an axis-aligned plan. + if (page.Owner.Font is not { } font + || document.GetElement(planId)?.ViewCrop is not { Right: [1, 0, 0], Up: [0, 1, 0] } + || document.GetElement(sectionId) is not { ViewDirection: [var dx, var dy, 0] } section + || document.RawData.ViewHiddenElements?.GetValueOrDefault(planId)?.Contains(sectionId) == true + || document.GetElement(section.TypeId)?.LookupParameter(BuiltInParameter.SECTION_TAG)?.Value is not int tag + || document.RawData.SectionMarkerSymbols?.GetValueOrDefault(tag) is not (var head, var tail) + || document.GetElement(head) is not { FamilyName: "M_Section Head - Filled", BoundingBox: { Length: 6 } headBox } + || document.GetElement(tail) is not { FamilyName: "M_Section Tail - Filled", BoundingBox: { Length: 6 } tailBox } + || document.RawData.TitleBlockLabels?.GetValueOrDefault(head) is not { } labels) + return false; + + var detail = labels.FirstOrDefault(label => label.ParamId == (int)BuiltInParameter.VIEWER_DETAIL_NUMBER); + var sheet = labels.FirstOrDefault(label => label.ParamId == (int)BuiltInParameter.VIEWER_SHEET_NUMBER); + if (detail is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || sheet is not { Bx: 1, By: 0, Hx: 0, Hy: 1 }) + return false; + var start = line[0]; + var end = line[^1]; + double ax = line[1].X - start.X, ay = line[1].Y - start.Y; + double length = double.Hypot(ax, ay); + if (!(length > 0 && double.IsFinite(length))) return false; + double ux = ax / length, uy = ay / length; + double perpendicular = ux * dy - uy * dx; + if (!(Math.Abs(perpendicular) > 1 - 1e-8)) return false; + double vx = -uy * Math.Sign(perpendicular), vy = ux * Math.Sign(perpendicular); + + double radius = -headBox[1] * FeetToMillimetres; + double tip = headBox[4] * FeetToMillimetres; + double center = (headBox[0] + headBox[3]) * FeetToMillimetres / 2; + double tailWidth = (tailBox[3] - tailBox[0]) * FeetToMillimetres; + double tailHeight = (tailBox[4] - tailBox[1]) * FeetToMillimetres; + if (!(radius is > 0 and <= 100 && tailWidth is > 0 and <= 100 && tailHeight is > 0 and <= 100 + && Math.Abs(center + radius) < 1e-6 && Math.Abs(tip - radius * Math.Sqrt(2)) < 1e-6)) + return false; + + (double X, double Y) At((double X, double Y) p, double x, double y) => + (p.X + x * ux + y * vx, p.Y + x * uy + y * vy); + bool Contains((double X, double Y) p) => frame is not { } f + || (p.X >= f.X0 && p.X <= f.X1 && p.Y >= f.Y0 && p.Y <= f.Y1); + if (!Contains(start) || !Contains(end)) return false; + + var viewport = document.Elements.FirstOrDefault(element => element.ViewportViewId == sectionId && element.OwnerViewId is > 0); + string number = viewport?.OwnerViewId is int sheetId + ? document.GetElement(sheetId)?.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? "---" : "---"; + string detailNumber = viewport?.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? "-"; + var mid = At(start, center, 0); + var left = At(mid, -tip, 0); + var right = At(end, tailWidth, 0); + bool vertical = line.Count > 2 && Math.Abs(ux) < 1e-8; + if (line.Count == 2) + page.DrawLine(left.X, left.Y, right.X, right.Y, pen); + else + { + page.DrawPolyline(line, pen, false); + var top = At(mid, tip, 0); + page.DrawLine(top.X, top.Y, start.X, start.Y, pen); + if (vertical) page.DrawLine(mid.X - radius, mid.Y, mid.X + radius, mid.Y, pen); + else page.DrawLine(left.X, left.Y, start.X, start.Y, pen); + } + page.DrawPolyline([end, right, At(end, tailWidth, tailHeight), At(end, 0, tailHeight)], pen, true, 0); + + // The family is the portion of a right isosceles triangle outside its circular opening. + for (int eighth = 0; eighth < 4; eighth++) + { + var corner = eighth switch + { + 0 => At(mid, tip, 0), + 3 => At(mid, -tip, 0), + _ => At(mid, 0, tip), + }; + var wing = new List<(double X, double Y)>(5) { corner }; + for (int i = 0; i <= 3; i++) + { + double theta = (3 * eighth + i) * Math.PI / 12; + wing.Add(At(mid, radius * Math.Cos(theta), radius * Math.Sin(theta))); + } + page.DrawPolyline(wing, pen, true, 0); + } + page.DrawPolyline(ElevationPrinter.DatumCircle(mid.X, mid.Y, radius, 25), pen, true); + DrawLabel(detail, detailNumber); + DrawLabel(sheet, number); + return true; + + void DrawLabel(RvtIO.Parsing.TfBlockDeserializer.TitleBlockLabel label, string value) + { + double ox = label.Ox * FeetToMillimetres, oy = label.Oy * FeetToMillimetres; + var position = vertical ? (X: mid.X + ox - center, Y: mid.Y + oy) : At(start, ox, oy); + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + bool arial = document.RawData.RegularArialSymbolLabelStyles?.Contains(label.AttrId) == true; + bool flip = ux < -1e-8 || (Math.Abs(ux) <= 1e-8 && uy < 0); + double bx = vertical ? 1 : flip ? -ux : ux, by = vertical ? 0 : flip ? -uy : uy; + SheetComposer.DrawTitleBlockText(page, [label.Prefix + value + label.Suffix], position.X, position.Y, + SheetComposer.SymbolLabelTextSize(font, height, cap), height, label.Flags, bx, by, -by, bx, opaque, arial); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Stairs.cs b/src/RvtIO/Print/PlanPrinter.Stairs.cs new file mode 100644 index 00000000..2bc9f92a --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Stairs.cs @@ -0,0 +1,391 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal static void DrawStairPaths(PdfPage page, RvtDocument document, int viewId, int levelId, + PlanContent content, double scale, double originX, double originY) + { + if (document.RawData.PlanStairPaths?.GetValueOrDefault(viewId) is not { Count: > 0 } paths + || GetPlanRange(document, levelId, viewId) is not { } range + || !PenWidths.TryGetStyle(document, (int)BuiltInCategory.OST_StairsPaths, false, out int pen, out int rgb)) + return; + double width = PenWidths.TryAnnotationWidth(document, pen, out double saved) ? saved : 0.1; + var color = new PdfColor((rgb & 255) / 255d, ((rgb >> 8) & 255) / 255d, ((rgb >> 16) & 255) / 255d); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + Point Paper(Point p) => ((p.X * FeetToMillimetres - content.MinX) / scale + originX, + (p.Y * FeetToMillimetres - content.MinY) / scale + originY); + static Point Mid(TfBlockDeserializer.StairPlanLine line) => + ((line.X1 + line.X2) / 2, (line.Y1 + line.Y2) / 2); + static bool Same(Point a, Point b) => Math.Abs(a.X - b.X) < 1e-7 && Math.Abs(a.Y - b.Y) < 1e-7; + foreach (var path in paths) + { + if (hidden?.Contains(path.Id) == true || hidden?.Contains(path.HostId) == true + || document.GetElement(path.HostId) is not { SerializedStairCore: [{ ClassId: 3708 } component] } stair + || stair.LookupParameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM)?.Value is not int top || top != levelId + || stair.LookupParameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM)?.Value is not int bottom || bottom == levelId + || document.GetElement(component.Id)?.SerializedStairRunInput is not { Numbers: { } levels, Plan: { } plan } run + || levels.TopElevation > range.Cut || levels.BeginWithRiser != 1 || levels.EndWithRiser != 0 || plan.Treads.Length < 3) + continue; + + if (run.Style == TfBlockDeserializer.StairRunStyle.Sketched) + { + // For a descending flight that crosses the lower clip, locate the first riser at the + // view's cut offset measured from the base level and the last physical riser at the top. + if (levels.BottomElevation < range.Bottom && levels.TopElevation >= range.Bottom + && document.RawData.PlanViewRanges?.TryGetValue(viewId, out var savedRange) == true + && (savedRange.LevelIds[0] == levelId || savedRange.LevelIds[0] == -1) + && document.GetElement(bottom)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double baseHeight + && SketchedStairPath(plan, baseHeight + savedRange.Offsets[0]) is { Count: >= 2 } points) + { + var paper = points.Select(Paper).ToList(); + double dxToTail = paper[1].X - paper[0].X, dyToTail = paper[1].Y - paper[0].Y; + double headLength = Math.Sqrt(dxToTail * dxToTail + dyToTail * dyToTail); + if (!(headLength > 0 && double.IsFinite(headLength))) continue; + for (int i = 1; i < paper.Count; i++) + page.DrawLine(paper[i - 1].X, paper[i - 1].Y, paper[i].X, paper[i].Y, width, color); + DrawArrowhead(paper[0], dxToTail / headLength, dyToTail / headLength, path); + } + continue; + } + + if (run.Style != TfBlockDeserializer.StairRunStyle.Straight || plan.Center is not [var axis] + || levels.BottomElevation < range.Bottom || !Same(Mid(plan.Treads[0]), (axis.X1, axis.Y1)) + || !Same(Mid(plan.Treads[^1]), (axis.X2, axis.Y2))) + continue; + + Point tip = Paper(Mid(plan.Treads[0])), focus = Paper((axis.X2, axis.Y2)); + double dx = focus.X - tip.X, dy = focus.Y - tip.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0 && double.IsFinite(length))) continue; + + Point previous = tip; + // The upper envelope ends one pitch beyond the last physical nosing when End With Riser is off. + for (int i = 1; i < plan.Treads.Length - 1; i++) + { + Point landing = Paper(Mid(plan.Treads[i])); + page.DrawLine(previous.X, previous.Y, landing.X, landing.Y, width, color); + previous = landing; + } + double ux = dx / length, uy = dy / length; + DrawArrowhead(tip, ux, uy, path); + if (path.DownText is { } text && page.Owner.Font is { CapHeight: > 0 } font + && Math.Abs(ux) < 1e-7 && uy > 0) + { + Point label = Paper((axis.X2 + path.TextX, axis.Y2 + path.TextY)); + double size = SheetComposer.SymbolLabelTextSize(font, 0, path.CapHeight); + page.DrawText(text, label.X, label.Y - path.CapHeight * FeetToMillimetres / 2, size, PdfTextAlignment.Right); + } + } + + void DrawArrowhead(Point tip, double ux, double uy, RevitFileInfo.PlanStairPath path) + { + double arrow = path.ArrowSize * FeetToMillimetres; + double halfSpan = arrow * Math.Tan(path.ArrowAngle / 2); + double x = tip.X + ux * arrow, y = tip.Y + uy * arrow; + page.DrawLine(tip.X, tip.Y, x - uy * halfSpan, y + ux * halfSpan, width, color); + page.DrawLine(tip.X, tip.Y, x + uy * halfSpan, y - ux * halfSpan, width, color); + } + } + + private static List? SketchedStairPath(TfBlockDeserializer.StairPlanInput plan, double cut) + { + const double tolerance = 1e-7; + var treads = plan.Treads; + if (plan.Center.Length < 2 || !(treads[0].Elevation < cut && cut <= treads[^2].Elevation)) return null; + var first = Array.Find(treads, tread => tread.Elevation >= cut); + if (Crossing(first) is not { } tip || Crossing(treads[^2]) is not { } tail + || tip.Segment > tail.Segment || tip.Segment == tail.Segment && tip.Fraction >= tail.Fraction) + return null; + + List path = [tip.Position]; + for (int i = tip.Segment; i < tail.Segment; i++) + { + var line = plan.Center[i]; + var next = plan.Center[i + 1]; + Point end = (line.X2, line.Y2); + if (!SamePoint(end, (next.X1, next.Y1))) return null; + if (!SamePoint(path[^1], end)) path.Add(end); + } + if (!SamePoint(path[^1], tail.Position)) path.Add(tail.Position); + return path; + + (int Segment, double Fraction, Point Position)? Crossing(TfBlockDeserializer.StairPlanLine tread) + { + (int Segment, double Fraction, Point Position)? hit = null; + double rx = tread.X2 - tread.X1, ry = tread.Y2 - tread.Y1; + for (int i = 0; i < plan.Center.Length; i++) + { + var line = plan.Center[i]; + double sx = line.X2 - line.X1, sy = line.Y2 - line.Y1; + double det = sx * ry - sy * rx; + if (Math.Abs(det) < tolerance) continue; + double x = tread.X1 - line.X1, y = tread.Y1 - line.Y1; + double alongPath = (x * ry - y * rx) / det, alongTread = (x * sy - y * sx) / det; + if (alongPath < -tolerance || alongPath > 1 + tolerance + || alongTread < -tolerance || alongTread > 1 + tolerance) continue; + double fraction = Math.Clamp(alongPath, 0, 1); + Point position = (line.X1 + fraction * sx, line.Y1 + fraction * sy); + if (hit is { } other && !SamePoint(other.Position, position)) return null; + hit = (i, fraction, position); + } + return hit; + } + + static bool SamePoint(Point a, Point b) => Math.Abs(a.X - b.X) < tolerance && Math.Abs(a.Y - b.Y) < tolerance; + } + + private static bool CollectSavedStair(RvtDocument document, Element stair, int viewId, int levelId, + (double Bottom, double Cut, double Top) range, + IEnumerable topRails, HashSet savedTopRails, + List> fills, ref List<(double X1, double Y1, double X2, double Y2, int StyleId)>? lines) + { + // shortcut: one run with linear side paths, extend when other run layouts decode. + if (stair.SerializedStairCore is not [{ ClassId: 3708 } component] + || document.GetElement(component.Id)?.SerializedStairRunInput is not { Plan: { } plan } run) + return false; + var start = plan.Treads[0]; + var end = plan.Treads[^1]; + if (!JoinsTread(start, (plan.Left[0].X1, plan.Left[0].Y1), (plan.Right[0].X1, plan.Right[0].Y1)) + || !JoinsTread(end, (plan.Left[^1].X2, plan.Left[^1].Y2), (plan.Right[^1].X2, plan.Right[^1].Y2))) + return false; + bool straightBelowCut = run is { Style: TfBlockDeserializer.StairRunStyle.Straight, Numbers: { } straightLevels } + && plan.Left.Length == 1 && plan.Right.Length == 1 && straightLevels.BottomElevation >= range.Bottom; + // The upper plan's own stair path identifies a descending projection through the opening, + // including lower treads outside the plan's ordinary bottom clip. + bool sketchedDescending = run.Style == TfBlockDeserializer.StairRunStyle.Sketched + && stair.LookupParameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM)?.Value is int top && top == levelId + && stair.LookupParameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM)?.Value is int bottom && bottom != levelId + && document.RawData.PlanStairPaths?.GetValueOrDefault(viewId)?.Any(path => path.HostId == stair.Id) == true; + if ((straightBelowCut || sketchedDescending) && run.Numbers is { } levels + && levels.TopElevation >= range.Bottom && levels.TopElevation <= range.Cut && end.Elevation <= range.Cut) + { + var leftBoundary = ReadSidePath(plan.Left); + var rightBoundary = ReadSidePath(plan.Right); + int edgeStyle = Style(BuiltInCategory.OST_StairsOutlines); + int treadStyle = Style(BuiltInCategory.OST_StairsNosingLines); + if (leftBoundary == null || rightBoundary == null || edgeStyle == 0 || treadStyle == 0) return false; + var projected = lines ??= []; + var railTops = new List>(); + const int railCategory = (int)BuiltInCategory.OST_RailingTopRail; + int projectionRailStyle = sketchedDescending ? Style(BuiltInCategory.OST_RailingTopRail) : 0; + if (projectionRailStyle != 0) + foreach (var rail in topRails) + { + if (rail.BoundingBox is not { Length: 6 } bounds || !(bounds[5] <= range.Cut)) continue; + var tops = rail.Geometry!.Faces.Where(face => face.Normal is [_, _, > 1e-7]).ToList(); + if (tops.Count == 0 || tops.Any(face => face.OuterVertices is not { Count: >= 3 } + || face.OuterVertices.Any(point => point.Length != 3 || point.Any(value => !double.IsFinite(value))) + || face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 })) continue; + var rings = tops.Select(face => ProjectRailRing(face.OuterVertices!)).ToList(); + fills.AddRange(rings); + railTops.AddRange(tops.Select(face => face.OuterVertices!)); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, railCategory)) + projected.Add((edge.X1, edge.Y1, edge.X2, edge.Y2, projectionRailStyle)); + savedTopRails.Add(rail.Id); + } + foreach (var edge in plan.Treads) + { + if (railTops.Count == 0) + { + AddStairLine(projected, (edge.X1, edge.Y1), (edge.X2, edge.Y2), treadStyle); + continue; + } + // The attached rail can hide part of a nosing even when the run projects below the plan range. + var masks = railTops.Select(ring => ElevationPrinter.ClipBehind(ring, [0, 0, edge.Elevation], [0, 0, 1])) + .Where(ring => ring.Count >= 3).Select(ProjectRailRing); + var line = new ElevationPrinter.CollectedEdge(edge.X1 * FeetToMillimetres, edge.Y1 * FeetToMillimetres, + edge.X2 * FeetToMillimetres, edge.Y2 * FeetToMillimetres, 0, 0, -1, -1, 0, 0, 0, 0); + foreach (var span in ElevationPrinter.VisibleTerrainEdges([line], masks, [], coverBoundary: false)) + projected.Add((span.X1, span.Y1, span.X2, span.Y2, treadStyle)); + } + foreach (var edge in plan.Left.Concat(plan.Right)) + AddStairLine(projected, (edge.X1, edge.Y1), (edge.X2, edge.Y2), edgeStyle); + AddMask(leftBoundary.Concat(rightBoundary.AsEnumerable().Reverse())); + return true; + } + + double cut = range.Cut; + if (!(start.Elevation < cut && cut < end.Elevation) + || document.GetElement(stair.TypeId) is not { } stairType + || stairType.LookupParameter(BuiltInParameter.STAIRSTYPE_SHOW_CUTLINE)?.Value is 0 + || stairType.LookupParameter(BuiltInParameter.STAIRSTYPE_CUTMARK_TYPE)?.Value is not int typeId + || document.GetElement(typeId) is not { } markType + || markType.LookupParameter(BuiltInParameter.CUT_LINE_TYPE)?.Value is not 0 + || markType.LookupParameter(BuiltInParameter.CUT_LINE_ANGLE)?.Value is not double angle + || markType.LookupParameter(BuiltInParameter.CUT_LINE_EXTENSION)?.Value is not 0d + || markType.LookupParameter(BuiltInParameter.CUT_MARK_SYMBOL)?.Value is not int symbol || symbol is not (0 or 1) + || document.GetElement(viewId)?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is not int scale || scale <= 0) + return false; + + int tread = 0; + for (int i = 1; i < plan.Treads.Length; i++) + { + if (plan.Treads[i].Elevation <= plan.Treads[i - 1].Elevation) return false; + if (plan.Treads[i].Elevation <= cut) tread = i; + } + var atCut = plan.Treads[tread]; + Point center = ((atCut.X1 + atCut.X2) / 2, (atCut.Y1 + atCut.Y2) / 2); + double direction = Math.Atan2(atCut.Y2 - atCut.Y1, atCut.X2 - atCut.X1) + angle; + Point along = (Math.Cos(direction), Math.Sin(direction)); + double Side(Point point) => along.X * (point.Y - center.Y) - along.Y * (point.X - center.X); + double lower = Side(((start.X1 + start.X2) / 2, (start.Y1 + start.Y2) / 2)); + if (!double.IsFinite(lower) || Math.Abs(lower) < 1e-7) return false; + double sign = Math.Sign(lower); + double Distance(Point point) => Side(point) * sign; + Point Intersect(Point a, Point b, double da, double db) + { + double fraction = da / (da - db); + return (a.X + (b.X - a.X) * fraction, a.Y + (b.Y - a.Y) * fraction); + } + + if (!TrySplitSide(plan.Left, out var left, out var leftAbove) + || !TrySplitSide(plan.Right, out var right, out var rightAbove)) return false; + Point a = left[^1], b = right[^1]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 1e-7) || !double.IsFinite(length)) return false; + + List mark = [a, b]; + if (symbol == 1) + { + if (markType.LookupParameter(BuiltInParameter.CUT_MARK_SYMBOL_SIZE)?.Value is not double size + || !(size > 0) || !double.IsFinite(size)) return false; + double span = size * scale; + if (span >= length) return false; + double ux = dx / length, uy = dy / length; + Point mid = ((a.X + b.X) / 2, (a.Y + b.Y) / 2); + double halfDepth = span * 5 / 8; + mark = [a, (mid.X - ux * span / 2, mid.Y - uy * span / 2), + (mid.X - uy * halfDepth, mid.Y + ux * halfDepth), + (mid.X + uy * halfDepth, mid.Y - ux * halfDepth), + (mid.X + ux * span / 2, mid.Y + uy * span / 2), b]; + } + + int outline = Style(BuiltInCategory.OST_StairsOutlines), outlineAbove = Style(BuiltInCategory.OST_StairsOutlinesAboveCut); + int nosing = Style(BuiltInCategory.OST_StairsNosingLines), nosingAbove = Style(BuiltInCategory.OST_StairsNosingLinesAboveCut); + int cutMark = Style(BuiltInCategory.OST_StairsCutMarks); + if (outline == 0 || outlineAbove == 0 || nosing == 0 || nosingAbove == 0 || cutMark == 0) return false; + + var strokes = lines ??= []; + DrawPath(left, outline); + DrawPath(right, outline); + DrawPath(leftAbove, outlineAbove); + DrawPath(rightAbove, outlineAbove); + DrawPath(mark, cutMark); + foreach (var edge in plan.Treads) + DrawSplit((edge.X1, edge.Y1), (edge.X2, edge.Y2), nosing, nosingAbove); + AddMask(left.Concat(mark.Skip(1)).Concat(right.AsEnumerable().Reverse().Skip(1))); + + int railStyle = Style(BuiltInCategory.OST_RailingTopRail), railAbove = Style(BuiltInCategory.OST_RailingTopRailAboveCut); + if (railStyle != 0 && railAbove != 0) + { + foreach (var rail in topRails) + { + var faces = FurnitureFaces(rail.Geometry!.Faces.Where(face => face.Normal is [_, _, > 1e-7])); + if (faces.Count == 0 || faces.Any(face => face.Holes.Count > 0)) continue; + var rings = faces.Select(face => face.Outer).ToList(); + foreach (var ring in rings) + { + var mask = ElevationPrinter.ClipHalfPlane(ring, point => RailDistance(point) >= 0, RailDistance); + if (mask.Count >= 3) fills.Add(mask); + } + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, (int)BuiltInCategory.OST_RailingTopRail)) + DrawSplit(ToFeet((edge.X1, edge.Y1)), ToFeet((edge.X2, edge.Y2)), railStyle, railAbove); + savedTopRails.Add(rail.Id); + } + } + return true; + + static Point ToFeet(Point point) => (point.X / FeetToMillimetres, point.Y / FeetToMillimetres); + static List ProjectRailRing(List vertices) + { + var ring = vertices.Select(point => (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres)).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + return ring; + } + double RailDistance(Point point) => Distance(ToFeet(point)); + + void DrawSplit(Point p, Point q, int belowStyle, int aboveStyle) + { + double dp = Distance(p), dq = Distance(q); + if (dp * dq < 0) + { + Point split = Intersect(p, q, dp, dq); + AddStairLine(strokes, p, split, dp > 0 ? belowStyle : aboveStyle); + AddStairLine(strokes, split, q, dq > 0 ? belowStyle : aboveStyle); + } + else AddStairLine(strokes, p, q, dp + dq >= 0 ? belowStyle : aboveStyle); + } + + int Style(BuiltInCategory category) => document.RawData.GraphicsStylePens? + .FirstOrDefault(entry => entry.Value.CategoryId == (int)category && entry.Value.OwnerId == -1 + && entry.Value.GStyleType == 1).Key ?? 0; + + void DrawPath(List path, int style) + { + for (int i = 1; i < path.Count; i++) AddStairLine(strokes, path[i - 1], path[i], style); + } + + void AddMask(IEnumerable boundary) + { + var mask = boundary.Select(p => (p.X * FeetToMillimetres, p.Y * FeetToMillimetres)).ToList(); + if (SignedArea(mask) < 0) mask.Reverse(); + fills.Add(mask); + } + + static List? ReadSidePath(TfBlockDeserializer.StairPlanLine[] side) + { + List points = [(side[0].X1, side[0].Y1)]; + foreach (var edge in side) + { + if (Math.Abs(points[^1].X - edge.X1) > 1e-7 || Math.Abs(points[^1].Y - edge.Y1) > 1e-7) + return null; + points.Add((edge.X2, edge.Y2)); + } + return points; + } + + bool TrySplitSide(TfBlockDeserializer.StairPlanLine[] side, out List below, out List above) + { + below = []; + above = []; + Point previous = (side[0].X1, side[0].Y1); + if (Distance(previous) <= 0) return false; + below.Add(previous); + foreach (var edge in side) + { + if (Math.Abs(previous.X - edge.X1) > 1e-7 || Math.Abs(previous.Y - edge.Y1) > 1e-7) return false; + Point next = (edge.X2, edge.Y2); + double dp = Distance(previous), dq = Distance(next); + if (above.Count > 0 && dq >= 0) return false; + if (dp > 0 && dq < 0) + { + Point intersection = Intersect(previous, next, dp, dq); + below.Add(intersection); + above.Add(intersection); + } + if (dq == 0) return false; + (dq > 0 ? below : above).Add(next); + previous = next; + } + return above.Count > 1; + } + } + + private static void AddStairLine(List<(double X1, double Y1, double X2, double Y2, int StyleId)> lines, + Point from, Point to, int style) => lines.Add((from.X * FeetToMillimetres, from.Y * FeetToMillimetres, + to.X * FeetToMillimetres, to.Y * FeetToMillimetres, style)); + + private static bool JoinsTread(TfBlockDeserializer.StairPlanLine tread, Point a, Point b) + { + static bool Same(Point p, Point q) => Math.Abs(p.X - q.X) <= 1e-7 && Math.Abs(p.Y - q.Y) <= 1e-7; + Point start = (tread.X1, tread.Y1), end = (tread.X2, tread.Y2); + return Same(a, start) && Same(b, end) || Same(a, end) && Same(b, start); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.WallCuts.cs b/src/RvtIO/Print/PlanPrinter.WallCuts.cs new file mode 100644 index 00000000..7d4ae14b --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.WallCuts.cs @@ -0,0 +1,150 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)> CollectCurtainProfiles( + RvtDocument document, int viewId, double cutHeight, double? bottom) + { + var result = new List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)>(); + var hiddenElements = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + double[] origin = [0, 0, cutHeight * FeetToMillimetres]; + double[] horizontal = [1, 0, 0], vertical = [0, 1, 0], direction = [0, 0, 1]; + foreach (var part in document.Elements) + { + if (part.CategoryId is not ((int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_CurtainWallMullions) + || part.IsDiscovered || part.NativeIsSymbol == true || part.SerializedUnplacedOwnerId is > 0 + || part.SerializedHostId is not > 0 + || part.BoundingBox is not { Length: 6 } bounds || !(bounds[2] < cutHeight) + || (bounds[5] <= cutHeight + && (part.CategoryId != (int)BuiltInCategory.OST_CurtainWallMullions || !(bounds[5] > bottom))) + || hiddenCategories?.Contains(part.CategoryId.Value) == true + || hiddenElements?.Contains(part.Id) == true || hiddenElements?.Contains(part.SerializedHostId.Value) == true + || part.Geometry is not { BrepSolids: [{ IsClosed: true } solid] } geometry + || solid.FaceIndices.Count != geometry.Faces.Count + || geometry.Faces.Any(face => face.CurvedSurface || face.InnerLoops is { Count: > 0 } + || face.InnerVertices is { Count: > 0 } || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(p => p.Length != 3 || !p.All(double.IsFinite)))) + continue; + + if (cutHeight < bounds[5]) + { + foreach (var ring in ElevationPrinter.ClosedSectionRings(geometry.Faces, origin, direction, + horizontal, vertical, requireClosed: true)) + result.Add((part.CategoryId.Value, true, ring)); + } + else + { + // A mullion below the cut projects its saved horizontal top face. + var tops = geometry.Faces.Where(face => face.PlaneSurface && !face.ExcludedFromTopPlan + && face.Normal is [_, _, > 0] && face.OuterVertices!.All(p => Math.Abs(p[2] - bounds[5]) < 1e-7)) + .Take(2).ToArray(); + if (tops is [var top]) + result.Add((part.CategoryId.Value, false, top.OuterVertices!.Select(InPlan).ToList())); + } + } + return result; + } + + private static Dictionary> CollectProjectedWallTops( + RvtDocument document, IEnumerable wallIds, Dictionary> gaps, + double bottom, double cutHeight) + { + var result = new Dictionary>(); + foreach (int id in wallIds) + { + if (gaps.TryGetValue(id, out var openings) && openings.Count > 0) continue; + if (document.GetElement(id) is not { BoundingBox: { Length: 6 } bounds, Geometry: { Faces.Count: > 0 } geometry } + || !(bounds[2] < bounds[5] && bounds[5] >= bottom && bounds[5] < cutHeight) + || geometry.Faces.Any(face => face.CurvedSurface || !UsableWallRing(face.OuterVertices))) continue; + + var tops = geometry.Faces.Where(face => face.PlaneSurface && !face.ExcludedFromTopPlan + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && face.Normal is [_, _, > 0] && face.OuterVertices!.All(p => Math.Abs(p[2] - bounds[5]) < 1e-7)) + .Take(2).ToArray(); + if (tops is [{ OuterVertices: { } top }] && HorizontalMaskCoversBody(top, geometry)) + result.Add(id, top.Select(InPlan).ToList()); + } + return result; + } + + private static Dictionary> Rings)> CollectWallCuts( + RvtDocument document, int viewId, PlanContent content) + { + var result = new Dictionary> Rings)>(); + if (PlanCutHeight(document, viewId) is not double cutHeight) return result; + double cut = cutHeight * FeetToMillimetres; + if (!double.IsFinite(cut)) return result; + double[] origin = [0, 0, cut]; + double[] horizontal = [1, 0, 0], vertical = [0, 1, 0], direction = [0, 0, 1]; + foreach (var wall in content.Walls) + { + if (document.GetElement(wall.Id) is not + { TypeId: > 0, Geometry: { Faces.Count: > 0 } geometry } element + || geometry.Faces.Any(face => face.CurvedSurface || !UsableWallRing(face.OuterVertices) + || (face.InnerLoops?.Count ?? 0) > (face.InnerVertices?.Count ?? 0) + || (face.InnerVertices is { Count: > 0 } holes && (!face.PlaneSurface || holes.Any(hole => !UsableWallRing(hole)))))) + continue; + + var rings = ElevationPrinter.ClosedSectionRings(geometry.Faces, origin, direction, horizontal, vertical, + requireClosed: true, includeFaceOpenings: true).ToList(); + if (rings.Count == 0 || !PreserveWallOpenings(wall, rings, content.Gaps.GetValueOrDefault(wall.Id))) continue; + foreach (var ring in rings) + if (SignedArea(ring) < 0) ring.Reverse(); + result[wall.Id] = (element.TypeId, rings); + } + return result; + } + + private static bool UsableWallRing(List? ring) => + ring is { Count: >= 3 } && ring.All(point => point.Length == 3 && point.All(double.IsFinite)); + + private static bool PreserveWallOpenings((int Id, double X1, double Y1, double X2, double Y2, double Width) wall, + List> rings, List<(double From, double To)>? gaps) + { + if (rings.Count == 1 && gaps is not { Count: > 0 }) return true; + double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0) || !double.IsFinite(length)) return false; + double Along((double X, double Y) point) => ((point.X - wall.X1) * dx + (point.Y - wall.Y1) * dy) / length; + // The plan draws its saved hosted openings even when the model cut passes below a sash. + const double endpointResolution = 0.1; // Same model millimetre resolution as ClosedSectionRings. + double coveredThrough = double.NegativeInfinity; + foreach (var (from, to) in rings.Select(ring => (From: ring.Min(Along), To: ring.Max(Along))).OrderBy(span => span.From)) + { + if (coveredThrough - from > endpointResolution + || gaps?.Any(gap => Math.Min(gap.To, to) - Math.Max(gap.From, from) > endpointResolution) == true) + return false; + coveredThrough = Math.Max(coveredThrough, to); + } + return true; + } + + private static void DrawWallCuts(PdfPage page, Dictionary> Rings)> cuts, + Func toX, Func toY, double width, + (double X0, double Y0, double X1, double Y1)? clip) + { + foreach (var ring in cuts.Values.SelectMany(cut => cut.Rings)) + { + var fill = clip is { } frame + ? ElevationPrinter.ClipToWindow(ring, frame.X0, frame.X1, frame.Y0, frame.Y1) : ring; + if (fill.Count >= 3) + page.DrawPolyline(fill.Select(p => (toX(p.X), toY(p.Y))).ToList(), 0, true, 1); + } + foreach (var sameType in cuts.Values.GroupBy(cut => cut.TypeId)) + { + var rings = sameType.SelectMany(cut => cut.Rings).ToList(); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, (int)BuiltInCategory.OST_Walls, + coverOppositeEdges: true)) + { + double x0 = edge.X1, y0 = edge.Y1, x1 = edge.X2, y1 = edge.Y2; + if (clip is { } frame && !ElevationPrinter.ClipSegment(x0, y0, x1, y1, frame.X0, frame.Y0, + frame.X1, frame.Y1, out x0, out y0, out x1, out y1)) continue; + page.DrawLine(toX(x0), toY(y0), toX(x1), toY(y1), width); + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index b40185f8..b4cd2c1a 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -1,4 +1,5 @@ using RvtIO.BuiltIns; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; using RvtIO.Pdf; @@ -43,7 +44,7 @@ public sealed record PlanView(int ViewId, string Name, int LevelId, int Scale); /// geometry, not Revit's generated linework, so floors, stairs, annotations, room fills, dimensions, tags and the title /// block are not on the page yet (see the notes in docs/printing.md). /// -public static class PlanPrinter +public static partial class PlanPrinter { private const double FeetToMillimetres = 304.8; @@ -65,7 +66,18 @@ internal sealed record PlanContent( List<(List<(double X, double Y)> Polygon, IReadOnlyList Grids)>? RoomPatterns = null, List<(double X1, double Y1, double X2, double Y2)>? StairLines = null, List<(double X1, double Y1, double X2, double Y2)>? RailLines = null, - List<(double X1, double Y1, double X2, double Y2)>? FurnitureLines = null); + List<(double X1, double Y1, double X2, double Y2)>? FurnitureLines = null, + IReadOnlyDictionary? RoomColors = null, + List>? FurnitureFillRings = null) + { + internal List<(DoorPlanSymbol Symbol, double[] Transform)>? DoorSymbols { get; init; } + internal List<(double X1, double Y1, double X2, double Y2, int StyleId)>? FixtureLines { get; init; } + internal List<(double X1, double Y1, double X2, double Y2, bool Cut)>? GenericModelLines { get; init; } + internal List<(double X, double Y, double Radius)>? DetailCircles { get; init; } + internal Dictionary? ColumnProfiles { get; init; } + internal Dictionary>? ProjectedWallTops { get; init; } + internal List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)>? CurtainProfiles { get; init; } + } /// The same plan seen in a rotated view: every point is projected on the view's own axes, so a site /// plan whose crop basis is turned draws its building turned with it. Wall-relative data (gaps, door and @@ -142,7 +154,41 @@ void Grow(double x, double y) return content with { MinX = content.MinX, MinY = content.MinY, MaxX = content.MaxX, MaxY = content.MaxY }; return new PlanContent(walls, columns, grids, content.Gaps, content.WindowGaps, content.DoorGaps, floorLoops, openingLoops, rooms, furniture, tags, minX, minY, maxX, maxY, - roomPatterns, stairLines, railLines, furnitureLines); + roomPatterns, stairLines, railLines, furnitureLines, content.RoomColors, + content.FurnitureFillRings?.Select(MapPolygon).ToList()) + { + ProjectedWallTops = content.ProjectedWallTops?.ToDictionary(entry => entry.Key, entry => MapPolygon(entry.Value)), + CurtainProfiles = content.CurtainProfiles?.Select(profile => + (profile.CategoryId, profile.IsCut, MapPolygon(profile.Ring))).ToList(), + ColumnProfiles = content.ColumnProfiles?.ToDictionary(entry => entry.Key, entry => + { + var profile = entry.Value; + (double X, double Y, double Radius)? circle = null; + if (profile.Circle is { } source) + { + var centre = Map(source.X, source.Y); + circle = (centre.X, centre.Y, source.Radius); + } + return profile with { Ring = MapPolygon(profile.Ring), Circle = circle }; + }), + DetailCircles = content.DetailCircles?.Select(circle => + { + var center = Map(circle.X, circle.Y); + return (center.X, center.Y, circle.Radius); + }).ToList(), + GenericModelLines = content.GenericModelLines?.Select(line => + { + var a = Map(line.X1, line.Y1); + var b = Map(line.X2, line.Y2); + return (a.X, a.Y, b.X, b.Y, line.Cut); + }).ToList(), + FixtureLines = content.FixtureLines?.Select(line => + { + var a = Map(line.X1, line.Y1); + var b = Map(line.X2, line.Y2); + return (a.X, a.Y, b.X, b.Y, line.StyleId); + }).ToList(), + }; } /// The levels a plan can be printed for: those that own at least one wall or column with a location line, @@ -299,6 +345,9 @@ public static PdfDocument RenderViews(RvtDocument document, IReadOnlyList v { var walls = new List<(int Id, double X1, double Y1, double X2, double Y2, double Width)>(); var columns = new List<(double X, double Y, double Width, double Height)>(); + Dictionary? columnProfiles = null; + double? cutHeight = viewId is int cutView ? PlanCutHeight(document, cutView) : null; + var planRange = GetPlanRange(document, levelId, viewId); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; void Grow(double x, double y) { @@ -327,6 +376,8 @@ void Grow(double x, double y) if (box is not { Length: 6 } || box[3] <= box[0] || box[4] <= box[1]) continue; double x = box[0] * FeetToMillimetres, y = box[1] * FeetToMillimetres; double width = (box[3] - box[0]) * FeetToMillimetres, height = (box[4] - box[1]) * FeetToMillimetres; + if (cutHeight is double cut && CutColumnProfile(document, element, cut) is { } profile) + (columnProfiles ??= []).Add(columns.Count, profile); columns.Add((x, y, width, height)); Grow(x, y); Grow(x + width, y + height); } @@ -341,10 +392,27 @@ void Grow(double x, double y) var gaps = new Dictionary>(); var windowGaps = new List<(int HostId, double From, double To)>(); var doorGaps = new List<(int HostId, double From, double To)>(); + List<(DoorPlanSymbol Symbol, double[] Transform)>? doorSymbols = null; + var hiddenElements = viewId is int openingView ? document.RawData.ViewHiddenElements?.GetValueOrDefault(openingView) : null; + var hiddenCategories = viewId is int categoryView ? document.RawData.ViewHiddenCategories?.GetValueOrDefault(categoryView) : null; + bool IsHidden(Element element) => hiddenElements?.Contains(element.Id) == true + || element.CategoryId is int category && hiddenCategories?.Contains(category) == true; var tags = new List<(double MidX, double MidY, double Nx, double Ny, string Text, bool IsWindow)>(); foreach (var insert in document.Elements) { if (insert.CategoryId is not ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows)) continue; + // A hidden door or window leaves its opening in the wall: the opening is the wall's, and only what the + // insert itself draws (its leaf, glass, symbol and tag) is dropped. + bool hiddenInsert = IsHidden(insert); + bool savedDoor = false; + if (!hiddenInsert && cutHeight is double height + && insert.SerializedHostId is int planHost && wallById.ContainsKey(planHost) + && insert.OwnDoorPlanSymbols is { } display + && SelectDoorPlanSymbol(display.Symbols, display.Transform, height, insert.BoundingBox) is { } symbol) + { + (doorSymbols ??= []).Add((symbol, display.Transform)); + savedDoor = true; + } if (insert.OwnSingleFamilyCutout is not { } cutout || cutout.Transform is not { Length: 12 } matrix) continue; if (!wallById.TryGetValue(cutout.HostId, out var wall)) continue; double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; @@ -371,8 +439,9 @@ void Grow(double x, double y) if (to - from < 1) continue; if (!gaps.TryGetValue(wall.Id, out var list)) gaps[wall.Id] = list = new List<(double From, double To)>(); list.Add((from, to)); + if (hiddenInsert) continue; if (insert.CategoryId == (int)BuiltInCategory.OST_Windows) windowGaps.Add((wall.Id, from, to)); - else doorGaps.Add((wall.Id, from, to)); + else if (!savedDoor) doorGaps.Add((wall.Id, from, to)); // The tag of a door is its mark, the tag of a window its type mark: both are placed beside the opening on // the side it opens into. bool isWindow = insert.CategoryId == (int)BuiltInCategory.OST_Windows; @@ -409,7 +478,7 @@ void Grow(double x, double y) if (element.CategoryId != (int)BuiltInCategory.OST_Rooms) continue; if (element.LookupParameter(BuiltInParameter.ROOM_LEVEL_ID)?.Value is not int roomLevel || roomLevel != levelId) continue; - if (element.SerializedSpaceBoundary is not { Faces.Count: > 0 } boundary) continue; + if (element.SerializedSpaceBoundaryCurrent is not { Faces.Count: > 0 } boundary) continue; List<(double X, double Y)>? polygon = null; double bestArea = 0; foreach (var face in boundary.Faces) @@ -424,7 +493,8 @@ void Grow(double x, double y) polygon = candidate; } if (polygon == null) continue; - double areaFeet = element.LookupParameter(BuiltInParameter.ROOM_AREA)?.Value is double value ? value : 0; + double areaFeet = element.LookupParameter(BuiltInParameter.ROOM_AREA)?.Value is double value + ? value : bestArea / (FeetToMillimetres * FeetToMillimetres); string number = element.LookupParameter(BuiltInParameter.ROOM_NUMBER)?.Value as string ?? ""; rooms.Add((polygon, element.Name ?? "", number, areaFeet)); } @@ -448,7 +518,8 @@ void Grow(double x, double y) var layers = type?.SerializedHostTypeLayers; if (layers is not { Length: > 0 } || layers[0].RawMaterialId <= 0) continue; if (!materialPatterns.TryGetValue(layers[0].RawMaterialId, out var material) - || material.SurfacePatternId <= 0 || !fillPatterns.ContainsKey(material.SurfacePatternId)) continue; + || !fillPatterns.TryGetValue(material.SurfacePatternId, out var surfacePattern) + || surfacePattern.Grids.Count == 0) continue; List<(double X, double Y)>? top = null; double topZ = double.MinValue; foreach (var face in geometry.Faces) @@ -486,17 +557,25 @@ void Grow(double x, double y) var openingLoops = new List>(); foreach (var insert in document.Elements) { - if (insert.CategoryId is not ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows)) continue; + if (insert.CategoryId is not ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows) + || IsHidden(insert)) continue; if (insert.OwnSingleFamilyCutout is not { } cutout || cutout.Transform is not { Length: 12 } matrix) continue; + // A roof opening projects a separate plan outline. Wall loops are used for the jambs. + bool roofOpening = document.GetElement(cutout.HostId)?.CategoryId == (int)BuiltInCategory.OST_Roofs; var points = new List<(double X, double Y)>(cutout.Loop.Vertices.Count); + double low = double.PositiveInfinity, high = double.NegativeInfinity; foreach (var vertex in cutout.Loop.Vertices) { double wx = (matrix[0] * vertex[0] + matrix[1] * vertex[1] + matrix[2] * vertex[2] + matrix[9]) * FeetToMillimetres; double wy = (matrix[3] * vertex[0] + matrix[4] * vertex[1] + matrix[5] * vertex[2] + matrix[10]) * FeetToMillimetres; + double z = matrix[6] * vertex[0] + matrix[7] * vertex[1] + matrix[8] * vertex[2] + matrix[11]; + low = Math.Min(low, z); + high = Math.Max(high, z); points.Add((wx, wy)); } + if (roofOpening && planRange is { } range && (high < range.Bottom || low > range.Top)) continue; if (points.Count >= 3) openingLoops.Add(points); } @@ -519,17 +598,113 @@ void Grow(double x, double y) var furniture = new List>(); var furnitureKeys = new HashSet(StringComparer.Ordinal); var furnitureLines = new List<(double X1, double Y1, double X2, double Y2)>(); + var furnitureFill = new List>(); + List<(double X1, double Y1, double X2, double Y2, int StyleId)>? fixtureLines = null; + List<(double X1, double Y1, double X2, double Y2, bool Cut)>? genericModelLines = null; + List<(double X, double Y, double Radius)>? detailCircles = null; + bool opaqueFurniture = viewId is int fixtureView && document.RawData.OpaquePlanViews?.Contains(fixtureView) == true; + int? planDetail = viewId is int detailView + ? document.GetElement(detailView)?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int? + : null; + var savedStairs = new HashSet(); + var savedTopRails = new HashSet(); + var stairTopRails = opaqueFurniture && planRange != null + ? (from rail in document.Elements + where rail is { CategoryId: (int)BuiltInCategory.OST_RailingTopRail, RootClassName: "TopRail", + SerializedOwningElementId: > 0, Geometry.Faces.Count: > 0 } + && !IsHidden(rail) + let owner = rail.SerializedOwningElementId.GetValueOrDefault() + where !(document.GetElement(owner) is { } ownerRailing ? IsHidden(ownerRailing) : hiddenElements?.Contains(owner) == true) + let host = document.GetElement(owner)?.SerializedRailingStairHostId ?? 0 + where host > 0 + select (Host: host, Rail: rail)).ToLookup(item => item.Host, item => item.Rail) + : null; foreach (var element in document.Elements) { - if (element.CategoryId is not ((int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework + if (IsHidden(element)) continue; + if (viewId is int circleView && element.OwnerViewId == circleView + && element.RootClassName == "CurveElem" && element.CategoryId == (int)BuiltInCategory.OST_Lines + && element.DetailCircle is { } circle) + (detailCircles ??= []).Add((circle.X * FeetToMillimetres, circle.Y * FeetToMillimetres, + circle.Radius * FeetToMillimetres)); + if (opaqueFurniture && element is { CategoryId: (int)BuiltInCategory.OST_GenericModel, + RootClassName: "FamilyInstance", BoundingBox: { Length: 6 } bounds, Geometry: { } modelGeometry } + && planRange is { } modelRange && double.IsFinite(bounds[2]) && double.IsFinite(bounds[5]) + && bounds[2] < modelRange.Cut && bounds[5] >= modelRange.Cut) + { + CollectSectionedGenericModel(modelGeometry, modelRange.Bottom, modelRange.Cut, + furnitureFill, ref genericModelLines); + continue; + } + + // Generic families entirely below the cut draw their projection in the visible portion of the plan. + bool projectedFamily = element.CategoryId is (int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_SpecialityEquipment - or (int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRailing)) + or (int)BuiltInCategory.OST_FurnitureSystems + || element is { CategoryId: (int)BuiltInCategory.OST_GenericModel, RootClassName: "FamilyInstance", + BoundingBox: { Length: 6 } box } && planRange is { } range + && double.IsFinite(box[5]) && box[5] < range.Cut; + if (!projectedFamily && element.CategoryId is not ((int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRailing)) + continue; + if (element.PlacedPlanFixtureGraphics is { } fixture && element.Geometry is not { Faces.Count: > 0 }) + { + if (!FurnitureInView(element, levelId, planRange)) + continue; + foreach (var line in fixture.Lines) + (fixtureLines ??= []).Add((line.Start[0] * FeetToMillimetres, line.Start[1] * FeetToMillimetres, + line.End[0] * FeetToMillimetres, line.End[1] * FeetToMillimetres, line.StyleId)); + if (opaqueFurniture) + foreach (var mask in fixture.Masks) + { + var ring = mask.Select(point => (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres)).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + furnitureFill.Add(ring); + } continue; - if (LevelOf(element) != levelId || element.Geometry is not { Faces.Count: > 0 } geometry) continue; - if (element.CategoryId is (int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework - or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_SpecialityEquipment) + } + if (element.CategoryId == (int)BuiltInCategory.OST_Stairs + && opaqueFurniture && viewId is int planView && planRange is { } stairRange + && OnLevel(element, levelId) + && CollectSavedStair(document, element, planView, levelId, stairRange, stairTopRails?[element.Id] ?? [], + savedTopRails, furnitureFill, ref fixtureLines)) + { + savedStairs.Add(element.Id); + continue; + } + if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; + if (projectedFamily) { - var outline = SilhouetteLines(element, 5.0); + if (element.RootClassName == "FamilySymbol" + || !FurnitureInView(element, levelId, planRange)) + continue; + if (opaqueFurniture && planRange != null && planDetail == 2 + && element.PlacedPlanFixtureGraphics?.MediumProjection is { Masks.Count: > 0 } projection + && geometry.Faces.Any(face => face.ExcludedFromTopPlan) + && (element.CategoryId == (int)BuiltInCategory.OST_PlumbingFixtures + ? geometry.Faces.All(face => face.ExcludedFromTopPlan || face.GeometryNode < 0) + : FixtureProjectionCoversBody(projection, geometry))) + { + foreach (var line in projection.Lines) + (fixtureLines ??= []).Add((line.Start[0] * FeetToMillimetres, line.Start[1] * FeetToMillimetres, + line.End[0] * FeetToMillimetres, line.End[1] * FeetToMillimetres, line.StyleId)); + foreach (var mask in projection.Masks) + { + var ring = mask.Select(InPlan).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + furnitureFill.Add(ring); + } + continue; + } + var faces = opaqueFurniture && element.CategoryId == (int)BuiltInCategory.OST_Furniture + ? FurnitureFaces(geometry.Faces.Where(face => !face.ExcludedFromTopPlan)) : null; + // A direction filter can replace the entire model with a symbol. Until that + // symbol is decoded, retain the model silhouette when no faces can project. + if (faces is not { Count: > 0 }) faces = FurnitureFaces(geometry.Faces); + bool containedFixture = opaqueFurniture && planRange is { } fixtureRange + && element.BoundingBox is { Length: 6 } fixtureBounds + && fixtureBounds[2] >= fixtureRange.Bottom && fixtureBounds[5] <= fixtureRange.Cut + && element.CategoryId is ((int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_GenericModel); + var outline = (containedFixture ? FixtureProfiles(geometry) : null) ?? SilhouetteLines(faces, 5.0); if (outline.Count == 0) continue; double sMinX = outline.Min(s => Math.Min(s.X1, s.X2)); double sMaxX = outline.Max(s => Math.Max(s.X1, s.X2)); @@ -538,8 +713,31 @@ void Grow(double x, double y) string silhouetteKey = $"{sMinX:0}:{sMinY:0}:{sMaxX:0}:{sMaxY:0}"; if (!furnitureKeys.Add(silhouetteKey)) continue; furnitureLines.AddRange(outline); + // A fitting's top face often carries its basin as an inner loop (the bathtub rim): the silhouette + // keeps only the outer boundary, so the loops ink on their own. + foreach (var face in faces) + { + foreach (var hole in face.Holes) + { + for (int i = 0; i < hole.Count; i++) + { + var a = hole[i]; + var b = hole[(i + 1) % hole.Count]; + furnitureLines.Add((a.X, a.Y, b.X, b.Y)); + } + } + } + if (opaqueFurniture) + { + foreach (var face in faces) + { + furnitureFill.Add(face.Outer); + furnitureFill.AddRange(face.Holes); + } + } continue; } + if (LevelOf(element) != levelId) continue; foreach (var face in geometry.Faces) { if (Math.Abs(face.Normal[2]) < 0.9) continue; @@ -568,12 +766,24 @@ void Grow(double x, double y) const double annotation = 1000; minX -= annotation; minY -= annotation; maxX += annotation; maxY += annotation; var stairLines = new List<(double X1, double Y1, double X2, double Y2)>(); - CollectStairLines(document, levelId, stairLines); + CollectStairLines(document, levelId, savedStairs, IsHidden, stairLines); var railLines = new List<(double X1, double Y1, double X2, double Y2)>(); - CollectRailingLines(document, levelId, viewId, railLines); + CollectRailingLines(document, levelId, viewId, savedTopRails, IsHidden, railLines); + var colors = viewId is int planId ? document.RawData.ViewRoomColors?.GetValueOrDefault(planId) : null; return new PlanContent(walls, columns, grids, gaps, windowGaps, doorGaps, floorLoops, openingLoops, rooms, - furniture, tags, minX, minY, maxX, maxY, roomPatterns, stairLines, railLines, furnitureLines); + furniture, tags, minX, minY, maxX, maxY, roomPatterns, stairLines, railLines, furnitureLines, colors, furnitureFill) + { + DoorSymbols = doorSymbols, FixtureLines = fixtureLines, ColumnProfiles = columnProfiles, + GenericModelLines = genericModelLines, + DetailCircles = detailCircles, + ProjectedWallTops = viewId is int wallView && planRange is { } wallRange + && document.RawData.UnshadedHiddenLineViews?.Contains(wallView) == true + ? CollectProjectedWallTops(document, walls.Select(wall => wall.Id), gaps, wallRange.Bottom, wallRange.Cut) + : null, + CurtainProfiles = viewId is int curtainView && cutHeight is double curtainCut + ? CollectCurtainProfiles(document, curtainView, curtainCut, planRange?.Bottom) : null, + }; } /// True when the element belongs to the plan of the level. A stair runs from its base level to its top @@ -587,13 +797,14 @@ private static bool OnLevel(Element element, int levelId) /// The plan linework of a stair: the outlines of its horizontal faces (tread and landing tops) seen from /// above, which is what a plan draws as the tread courses between the stair's sides. - private static void CollectStairLines(RvtDocument document, int levelId, - List<(double X1, double Y1, double X2, double Y2)> lines) + private static void CollectStairLines(RvtDocument document, int levelId, HashSet savedStairs, + Func isHidden, List<(double X1, double Y1, double X2, double Y2)> lines) { var keys = new HashSet(StringComparer.Ordinal); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Stairs || !OnLevel(element, levelId)) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Stairs || savedStairs.Contains(element.Id) + || isHidden(element) || !OnLevel(element, levelId)) continue; if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; foreach (var face in geometry.Faces) { @@ -620,8 +831,8 @@ private static void CollectStairLines(RvtDocument document, int levelId, /// the deck edge. The view range's top and bottom clips decide which rails are visible (a roof deck's rails /// stand below the plan's level but above its bottom clip), so an element outside the band is skipped; a /// view without a decoded range keeps only the rails of the plan's own level. - private static void CollectRailingLines(RvtDocument document, int levelId, int? viewId, - List<(double X1, double Y1, double X2, double Y2)> lines) + private static void CollectRailingLines(RvtDocument document, int levelId, int? viewId, HashSet savedTopRails, + Func isHidden, List<(double X1, double Y1, double X2, double Y2)> lines) { double levelElevation = document.GetElement(levelId)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double elevation ? elevation : 0; @@ -639,7 +850,11 @@ private static void CollectRailingLines(RvtDocument document, int levelId, int? var keys = new HashSet(StringComparer.Ordinal); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail || savedTopRails.Contains(element.Id) + || isHidden(element) + || element.SerializedOwningElementId is int owner + && (savedTopRails.Contains(owner) || document.GetElement(owner) is { } ownerRailing && isHidden(ownerRailing))) + continue; if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; if (banded) { @@ -718,7 +933,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale IReadOnlyList? sectionMarks = null, RvtDocument? document = null, (double X0, double Y0, double X1, double Y1)? frame = null, - (double X0, double Y0, double X1, double Y1)? clipRect = null) + (double X0, double Y0, double X1, double Y1)? clipRect = null, bool drawGrids = true, + bool drawFallbackDimensions = true, int? planViewId = null) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; @@ -728,14 +944,13 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale // section trace with the Sections projection pen (pen 1 annotates 0.1 mm on the reference, where // the old hardcoded 0.22 mm inked every trace heavy). int scaleDenominator = (int)Math.Round(scale); - double wallLine = 0.2, gridLine = 0.18, furnitureLine = 0.12, columnLine = 0.2, sectionLine = 0.1; + double wallLine = 0.2, gridLine = 0.18, furnitureLine = 0.12, columnLine = 0.2; if (document != null) { if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, true, scaleDenominator, out double w)) wallLine = w; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Columns, true, scaleDenominator, out double c)) columnLine = c; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Grids, false, scaleDenominator, out double g)) gridLine = g; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Furniture, false, scaleDenominator, out double f)) furnitureLine = f; - if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Sections, false, scaleDenominator, out double s)) sectionLine = s; } foreach (var floor in content.FloorLoops) @@ -743,7 +958,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale foreach (var room in content.Rooms) page.DrawPolyline(room.Polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, - RoomFill(room.Name)); + RoomFill(room.Name, content.RoomColors)); // A room's floor material may name a surface pattern (the sunken living room's carpet names "Sand"): // the reference prints that hatch inside the room's colour fill, and both the material and the pattern @@ -758,7 +973,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double[]? gridDashes = document != null && LinePatterns.TryGetGridDashes(document, out var decodedGrid) ? decodedGrid : [36.0, 9.0, 9.0, 9.0]; - foreach (var grid in content.Grids) + foreach (var grid in drawGrids ? content.Grids : []) { // Grids run past the crop to their bubbles (the reference draws them to the bubble row, like // rvt-prt growing the crop by the type end length): cutting them at the crop edge loses the @@ -771,11 +986,33 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale Bubble(page, ToX(grid.X2), ToY(grid.Y2), grid.Name, gridLine); } + if (content.FurnitureFillRings is { Count: > 0 } furnitureFill) + { + if (clipRect is { } clip) + page.BeginClip(ToX(clip.X0), ToY(clip.Y0), ToX(clip.X1) - ToX(clip.X0), ToY(clip.Y1) - ToY(clip.Y0)); + page.FillPolygonUnion(furnitureFill.Select(ring => ring.Select(point => (ToX(point.X), ToY(point.Y))).ToArray()), 1); + if (clipRect != null) page.EndClip(); + } + var wallById = new Dictionary(); foreach (var wall in content.Walls) wallById[wall.Id] = wall; - + double wallShade = planViewId is int viewId && document?.RawData.UnshadedHiddenLineViews?.Contains(viewId) == true + ? 1 : 0.72; + var wallFill = new PdfColor(wallShade, wallShade, wallShade); + var wallCuts = wallShade == 1 && document != null && planViewId is int cutView + ? CollectWallCuts(document, cutView, content) : []; + + double wallProjectionLine = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, false, scaleDenominator, out double projectionWidth) + ? projectionWidth : wallLine; foreach (var wall in content.Walls) { + if (wallCuts.ContainsKey(wall.Id)) continue; + if (content.ProjectedWallTops?.TryGetValue(wall.Id, out var top) == true) + { + DrawClippedOutline(page, top, ToX, ToY, wallProjectionLine, wallFill, clipRect); + continue; + } double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; double length = Math.Sqrt(dx * dx + dy * dy); if (length < 1e-9) continue; @@ -785,13 +1022,24 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale { double ax = wall.X1 + ux * from, ay = wall.Y1 + uy * from; double bx = wall.X1 + ux * to, by = wall.Y1 + uy * to; - // The wall is poche: the stretch between its two sides is filled, the way a printed plan fills a cut - // wall, and the four edges are inked over it. + // The wall fill masks the plan geometry underneath before its cut edges are inked. DrawClippedOutline(page, [ (ax + nx, ay + ny), (bx + nx, by + ny), (bx - nx, by - ny), (ax - nx, ay - ny), - ], ToX, ToY, wallLine, new PdfColor(0.72, 0.72, 0.72), clipRect); + ], ToX, ToY, wallLine, wallFill, clipRect); + } + } + DrawWallCuts(page, wallCuts, ToX, ToY, wallLine, clipRect); + if (document != null && content.CurtainProfiles is { Count: > 0 } curtainProfiles) + { + foreach (var style in curtainProfiles.GroupBy(profile => (profile.IsCut, profile.CategoryId)) + .OrderBy(group => group.Key.IsCut)) + { + double width = PenWidths.TryGetWidth(document, style.Key.CategoryId, style.Key.IsCut, + scaleDenominator, out double savedWidth) ? savedWidth : wallLine; + foreach (var profile in style) + DrawClippedOutline(page, profile.Ring, ToX, ToY, width, new PdfColor(1, 1, 1), clipRect); } } @@ -807,8 +1055,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale ToX(wall.X1 + ux * to), ToY(wall.Y1 + uy * to), 0.15, 0.35); } - // The room names and areas, at the centre of the footprint, in plan millimetres. - if (page.Owner.Font != null) + // A level-only print has no owning view and keeps the footprint-based room labels. + if (page.Owner.Font != null && !DrawPlanRoomTags(page, document, planViewId, ToX, ToY)) { foreach (var room in content.Rooms) { @@ -825,7 +1073,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale 0.18, true, 1); page.DrawText(room.Number, pageX - boxWidth / 2 + 2, pageY - 1.1, 2.4); if (room.AreaSquareFeet > 0) - page.DrawText($"{room.AreaSquareFeet * 0.092903:0} m²", pageX + boxWidth / 2 - 2, pageY - 1, + page.DrawText(LocalizeRoomArea($"{room.AreaSquareFeet * 0.092903:0} m²"), pageX + boxWidth / 2 - 2, pageY - 1, 2, PdfTextAlignment.Right); } } @@ -859,6 +1107,36 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale else page.DrawLine(ToX(line.X1), ToY(line.Y1), ToX(line.X2), ToY(line.Y2), furnitureLine); } + if (content.GenericModelLines is { Count: > 0 } genericModelLines) + { + foreach (var group in genericModelLines.GroupBy(line => line.Cut).OrderBy(group => group.Key)) + { + double width = document != null && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_GenericModel, + group.Key, scaleDenominator, out double savedWidth) ? savedWidth : furnitureLine; + foreach (var line in group) + { + var (x0, y0, x1, y1, _) = line; + if (clipRect is { } clip && !ElevationPrinter.ClipSegment(x0, y0, x1, y1, + clip.X0, clip.Y0, clip.X1, clip.Y1, out x0, out y0, out x1, out y1)) continue; + page.DrawLine(ToX(x0), ToY(y0), ToX(x1), ToY(y1), width); + } + } + } + if (content.FixtureLines is { Count: > 0 } fixtureLines) + DrawFixtureLines(page, document, fixtureLines, scale, furnitureLine, ToX, ToY, clipRect); + + if (content.DetailCircles is { Count: > 0 } circles) + { + if (clipRect is { } clip) + page.BeginClip(ToX(clip.X0), ToY(clip.Y0), + ToX(clip.X1) - ToX(clip.X0), ToY(clip.Y1) - ToY(clip.Y0)); + double width = document != null && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Lines, + false, scaleDenominator, out double savedWidth) ? savedWidth : 0.1; + foreach (var circle in circles) + page.DrawArc(ToX(circle.X), ToY(circle.Y), circle.Radius / scale, 0, 360, width); + if (clipRect != null) page.EndClip(); + } + foreach (var line in content.RailLines ?? []) { if (clipRect is { } railClip) @@ -876,8 +1154,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale // wall and on the side of the building the door opens into. double centerX = (content.MinX + content.MaxX) / 2, centerY = (content.MinY + content.MaxY) / 2; - // The marks of the doors and windows, in a small circle beside the opening. - if (page.Owner.Font != null) + // A generated level has no owning view for its opening marks. + if (page.Owner.Font != null && !DrawPlanOpeningTags(page, document, planViewId, ToX, ToY)) { foreach (var tag in content.Tags) { @@ -902,6 +1180,10 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale } } + if (content.DoorSymbols is { Count: > 0 } savedDoors) + foreach (var saved in savedDoors) + DrawDoorPlanSymbol(page, saved.Symbol, saved.Transform, scale, ToX, ToY, clipRect); + foreach (var door in content.DoorGaps) { if (!wallById.TryGetValue(door.HostId, out var wall)) continue; @@ -914,10 +1196,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double hx = wall.X1 + ux * door.From, hy = wall.Y1 + uy * door.From; double ex = wall.X1 + ux * door.To, ey = wall.Y1 + uy * door.To; double midX = (hx + ex) / 2, midY = (hy + ey) / 2; - // The swing side: the file stores a per-instance flip that the reader does not decode, so the - // side comes from the building centroid — and it opens away from it. Measured on the sample - // plan, opening away is the side the reference draws (A102 precision 90.3 -> 90.5, 6 in fewer - // unmatched segments, recall unchanged). + // shortcut: use the existing swing approximation when no matching saved cut symbol is available. double side = (centerX - midX) * nx + (centerY - midY) * ny >= 0 ? -1 : 1; double tipX = hx + nx * side * width, tipY = hy + ny * side * width; double ex0 = hx, ey0 = hy, ex1 = tipX, ey1 = tipY; @@ -931,15 +1210,15 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale page.DrawArc(ToX(hx), ToY(hy), width / scale, a0, a1, 0.15, 0.4); } - DimChains(page, content, ToX, ToY, clipRect); + if (drawFallbackDimensions) DimChains(page, content, ToX, ToY, clipRect); foreach (var opening in content.OpeningLoops) DrawClippedOutline(page, opening, ToX, ToY, 0.18, (PdfColor?)null, clipRect); - foreach (var column in content.Columns) - page.DrawRectangle(ToX(column.X), ToY(column.Y), column.Width / scale, column.Height / scale, columnLine, 1); + DrawColumns(page, document, content, scale, columnLine, ToX, ToY, clipRect); - if (sectionMarks is { Count: > 0 }) DrawSectionMarks(page, content, scale, originX, originY, sectionMarks, frame, sectionLine); + if (sectionMarks is { Count: > 0 }) + DrawSectionMarks(page, content, scale, originX, originY, sectionMarks, frame, document, planViewId); } /// Draws the plan of a level as one page of the document. @@ -1012,10 +1291,14 @@ void Corner(double cx, double cy, double from) /// Draws the section marks of a plan: the trace of each section plane across the drawing, a tick at both /// ends and a bubble with the letter of the view, as a plan shows where it is cut. - private static void DrawSectionMarks(PdfPage page, PlanContent content, double scale, double originX, + internal static void DrawSectionMarks(PdfPage page, PlanContent content, double scale, double originX, double originY, IReadOnlyList marks, - (double X0, double Y0, double X1, double Y1)? frame = null, double sectionLine = 0.1) + (double X0, double Y0, double X1, double Y1)? frame, RvtDocument? document, int? planViewId) { + if (marks.Count == 0) return; + double sectionLine = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Sections, false, (int)Math.Round(scale), out double width) + ? width : 0.1; double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; // The trace runs across the building, not across the site: its ends are the bounds of the walls. @@ -1059,6 +1342,10 @@ bool inside(double value, double direction, double low, double high) line = [(px + dx * tMin, py + dy * tMin), (px + dx * tMax, py + dy * tMax)]; } if (line.Count < 2) continue; + if (document != null && planViewId is int planId && mark.Bounded + && (line.Count == 2 || mark.UsesPlanExtent) + && TryDrawFilledSectionMark(page, document, planId, mark.ViewId, line, frame, sectionLine)) + continue; // The scorer counts vectors, not the page clip: cut every leg to the viewport frame at generation, // so nothing is inked outside the drawn frame. Legs clipped apart stay apart (no connectors). var runs = new List>(); @@ -1191,8 +1478,10 @@ static List Dedupe(List values) /// green, a hall blue, a kitchen tan, a laundry brown, a living room light green, a mechanical room green, a master /// bedroom blue violet, a master bath magenta, a bedroom cyan, an entry hall yellow, a linen teal; anything else light /// grey. - internal static PdfColor RoomFill(string name) + internal static PdfColor RoomFill(string name, IReadOnlyDictionary? colors = null) { + if (colors != null && colors.TryGetValue(name, out uint rgb)) + return new PdfColor((rgb & 255) / 255.0, ((rgb >> 8) & 255) / 255.0, ((rgb >> 16) & 255) / 255.0); string lower = name.ToLowerInvariant(); PdfColor color = lower switch { @@ -1215,7 +1504,7 @@ internal static PdfColor RoomFill(string name) } /// The signed area of a polygon (shoelace); its magnitude is the area and its sign the winding. - private static double SignedArea(List<(double X, double Y)> points) + internal static double SignedArea(List<(double X, double Y)> points) { double sum = 0; for (int i = 0; i < points.Count; i++) @@ -1227,58 +1516,8 @@ private static double SignedArea(List<(double X, double Y)> points) return sum / 2; } - /// The plan silhouette of a piece of furniture: the boundary of the union of all its faces projected on - /// XY, traced on a grid of millimetres. The non-convex plan shape (a chair back, the gap - /// between legs) survives, which the convex hull and the single top face both lose. - private static List<(double X1, double Y1, double X2, double Y2)> SilhouetteLines( - Element element, double cell) - { - if (element.Geometry is not { Faces.Count: > 0 } geometry) return []; - var faces = new List<(List<(double X, double Y)> Points, double MinX, double MaxX, double MinY, double MaxY)>(); - foreach (var face in geometry.Faces) - { - if (face.OuterVertices is not { Count: >= 3 } vertices) continue; - var points = vertices.Select(vertex => (X: vertex[0] * FeetToMillimetres, - Y: vertex[1] * FeetToMillimetres)).ToList(); - faces.Add((points, points.Min(point => point.X), points.Max(point => point.X), - points.Min(point => point.Y), points.Max(point => point.Y))); - } - if (faces.Count == 0) return []; - double x0 = faces.Min(face => face.MinX), x1 = faces.Max(face => face.MaxX); - double y0 = faces.Min(face => face.MinY), y1 = faces.Max(face => face.MaxY); - int nx = (int)Math.Ceiling((x1 - x0) / cell) + 1; - int ny = (int)Math.Ceiling((y1 - y0) / cell) + 1; - if (nx < 1 || ny < 1 || (long)nx * ny > 400_000) return []; - var inside = new bool[nx, ny]; - for (int i = 0; i < nx; i++) - for (int j = 0; j < ny; j++) - { - double cx = x0 + (i + 0.5) * cell, cy = y0 + (j + 0.5) * cell; - foreach (var face in faces) - { - if (cx < face.MinX || cx > face.MaxX || cy < face.MinY || cy > face.MaxY) continue; - if (!PointInPolygon(cx, cy, face.Points)) continue; - inside[i, j] = true; - break; - } - } - var lines = new List<(double X1, double Y1, double X2, double Y2)>(); - for (int i = 0; i < nx; i++) - for (int j = 0; j < ny; j++) - { - if (!inside[i, j]) continue; - double left = x0 + i * cell, right = left + cell; - double bottom = y0 + j * cell, top = bottom + cell; - if (i == 0 || !inside[i - 1, j]) lines.Add((left, bottom, left, top)); - if (i == nx - 1 || !inside[i + 1, j]) lines.Add((right, bottom, right, top)); - if (j == 0 || !inside[i, j - 1]) lines.Add((left, bottom, right, bottom)); - if (j == ny - 1 || !inside[i, j + 1]) lines.Add((left, top, right, top)); - } - return lines; - } - /// Even-odd point-in-polygon test on a closed outline. - private static bool PointInPolygon(double x, double y, IReadOnlyList<(double X, double Y)> polygon) + internal static bool PointInPolygon(double x, double y, IReadOnlyList<(double X, double Y)> polygon) { bool inside = false; for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) diff --git a/src/RvtIO/Print/RvtRaster.cs b/src/RvtIO/Print/RvtRaster.cs index 55aff259..0782eaf1 100644 --- a/src/RvtIO/Print/RvtRaster.cs +++ b/src/RvtIO/Print/RvtRaster.cs @@ -54,6 +54,31 @@ internal static class RvtRaster /// image the PDF writer embeds as it is. A rendering of a 3D view is stored that way, in the block of its image /// symbol's type. internal static PdfJpegImage? FindJpeg(string path, int elementId) + { + var block = FindBlock(path, elementId, 0x0890); + if (block == null) return null; + var payload = block.AsSpan(16); + int start = payload.IndexOf(new byte[] { 0xFF, 0xD8, 0xFF }); + int end = payload.LastIndexOf(new byte[] { 0xFF, 0xD9 }); + return start >= 0 && end > start ? new PdfJpegImage(payload[start..(end + 2)].ToArray()) : null; + } + + internal static PdfRasterImage? FindImagePng(string path, int elementId) + { + var block = FindBlock(path, elementId, 0x0890); + if (block == null) return null; + var payload = block.AsSpan(16); + int start = payload.IndexOf(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }); + return start >= 0 ? DecodePng(payload[start..].ToArray()) : null; + } + + internal static IReadOnlyList FindSheetImagePlacements(string path, int symbolId) + { + var block = FindBlock(path, symbolId, 0x07D7); + return block == null ? [] : GRepParserV2.ReadSheetImages(block); + } + + private static byte[]? FindBlock(string path, int elementId, int lowClass) { try { @@ -75,16 +100,8 @@ internal static class RvtRaster if (eid != (uint)elementId) continue; int size = BinaryPrimitives.ReadInt32LittleEndian(chunk.AsSpan(pos + 8)); uint classIdx = BinaryPrimitives.ReadUInt32LittleEndian(chunk.AsSpan(pos + 12)); - if (size <= 0 || pos + 16 + size > chunk.Length || (classIdx & 0xFFFF) != 0x0890) continue; - var payload = chunk.AsSpan(pos + 16, size); - int start = payload.IndexOf(new byte[] { 0xFF, 0xD8, 0xFF }); - if (start < 0) return null; - var jpeg = payload[start..].ToArray(); - // The end of the JPEG is its last end-of-image marker; anything after it is padding. - int end = jpeg.AsSpan().LastIndexOf(new byte[] { 0xFF, 0xD9 }); - if (end < 0) return null; - Array.Resize(ref jpeg, end + 2); - return new PdfJpegImage(jpeg); + if (size <= 0 || (long)pos + 16 + size > chunk.Length || (classIdx & 0xFFFF) != lowClass) continue; + return chunk.AsSpan(pos, 16 + size).ToArray(); } } } @@ -150,7 +167,7 @@ internal static class RvtRaster if (png.Length < 8 || png[0] != 0x89 || png[1] != 0x50 || png[2] != 0x4E || png[3] != 0x47) return null; int at = 8, width = 0, height = 0, depth = 0, colorType = 0; - var idat = new MemoryStream(); + using var idat = new MemoryStream(); byte[]? palette = null; byte[]? alpha = null; while (at + 8 <= png.Length) @@ -158,9 +175,10 @@ internal static class RvtRaster int length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(at)); string type = System.Text.Encoding.ASCII.GetString(png, at + 4, 4); int data = at + 8; - if (length < 0 || data + length + 4 > png.Length) return null; + if (length < 0 || length > png.Length - data - 4) return null; if (type == "IHDR") { + if (length != 13) return null; width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(data)); height = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(data + 4)); depth = png[data + 8]; @@ -175,16 +193,22 @@ internal static class RvtRaster } if (width <= 0 || height <= 0 || depth != 8) return null; int bpp = colorType switch { 2 => 3, 6 => 4, 3 => 1, 0 => 1, _ => 0 }; - if (bpp == 0) return null; + const int maxDecodedBytes = 128 * 1024 * 1024; + if (bpp == 0 || (long)width * bpp + 1 > maxDecodedBytes / height + || (long)width * height > maxDecodedBytes / 3) return null; + int stride = width * bpp; idat.Position = 0; - byte[] pixels; - using (var zlib = new ZLibStream(idat, CompressionMode.Decompress)) - using (var output = new MemoryStream()) + var pixels = new byte[(stride + 1) * height]; + try { - zlib.CopyTo(output); - pixels = output.ToArray(); + using var zlib = new ZLibStream(idat, CompressionMode.Decompress); + zlib.ReadExactly(pixels); + if (zlib.ReadByte() != -1) return null; + } + catch (Exception exception) when (exception is InvalidDataException or EndOfStreamException) + { + return null; } - int stride = width * bpp; var rows = new List(height); int pos = 0; byte[] previous = new byte[stride]; @@ -192,6 +216,7 @@ internal static class RvtRaster { if (pos + 1 + stride > pixels.Length) return null; byte filter = pixels[pos++]; + if (filter > 4) return null; var row = new byte[stride]; Array.Copy(pixels, pos, row, 0, stride); pos += stride; diff --git a/src/RvtIO/Print/ShadedViewport.cs b/src/RvtIO/Print/ShadedViewport.cs new file mode 100644 index 00000000..49ff8dd0 --- /dev/null +++ b/src/RvtIO/Print/ShadedViewport.cs @@ -0,0 +1,495 @@ +using System.Numerics; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; +using ShadowReceiver = RvtIO.Print.ViewportShadows.Receiver; + +namespace RvtIO.Print; + +internal static class ShadedViewport +{ + private readonly record struct Point(double X, double Y, double Depth); + private sealed record Surface(Point[][] Rings, double DepthX, double DepthY, int Rgb, ShadowReceiver Receiver, + double Transmission, ViewportSurfacePattern? Pattern, ViewportSurfaceEdges? Edges); + private readonly record struct Pane(Surface Surface, int Order, int FirstRow, int LastRow); + private readonly record struct PaneSpan(Pane Pane, int Start, int End); + private readonly record struct PaneHit(Pane Pane, double Depth, double PatternInk, double EdgeInk); + + internal static (double X, double Y, double Width, double Height)? Render(PdfPage page, RvtDocument document, + Element view, double anchorX, double anchorY, int scale) + { + if (view.ViewCrop is not { } camera || view.OrthographicModelBounds is not { } box + || scale <= 0 || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return null; + double factor = 304.8 / scale; + (double X, double Y) ProjectVector(double[] point) => + (factor * Dot(point[0], point[1], point[2], camera.Right), factor * Dot(point[0], point[1], point[2], camera.Up)); + Point Project(double[] point) + { + double x = point[0] - camera.OriginX, y = point[1] - camera.OriginY, z = point[2] - camera.OriginZ; + return new(anchorX + factor * Dot(x, y, z, camera.Right), + anchorY + factor * Dot(x, y, z, camera.Up), Dot(x, y, z, camera.Look)); + } + var solar = SolarStudyOverlay.Create(document, view, camera, factor, point => + { + var p = Project(point); + return (p.X, p.Y, p.Depth); + }); + var shadows = view.SolarStudy?.ShadowIntensity is > 0 and <= 100 and int intensity + && solar?.ModelSunDirection is { Z: > 0 } sun + ? new ViewportShadows(camera, sun, intensity, solar.GroundElevation) : null; + (Vector3 Sun, int Intensity)? sceneLight = view.SolarStudy?.SunlightIntensity is int sunlight + && solar?.ModelSunDirection is { Z: > 0 } terrainSun ? (terrainSun, sunlight) : null; + var annotation = solar is { AnnotationVisible: true } ? solar : null; + bool showPatterns = view.SolarStudy?.ShowSurfacePatterns == true; + bool showEdges = view.SolarStudy?.ShowEdges == true; + var patternOrigin = Project([0, 0, 0]); + var pens = new Dictionary(); + (double Width, int Color) Pen(int category) + { + if (pens.TryGetValue(category, out var value)) return value; + double width = PenWidths.TryGetWidth(document, category, false, scale, out double savedWidth) ? savedWidth : 0.1; + value = (width, PenWidths.TryGetStyle(document, category, false, out _, out int color) + && color is >= 0 and <= 0xffffff ? color : 0); + pens.Add(category, value); + return value; + } + + var planes = Enumerable.Range(0, 6).Where(i => box.Active[i]).Select(i => + { + double[] axis = box.Axes[i / 2]; + double sign = i % 2 == 0 ? 1 : -1; + double[] outward = [axis[0] * sign, axis[1] * sign, axis[2] * sign]; + double offset = sign * box.Offsets[i] + Dot(box.Origin[0], box.Origin[1], box.Origin[2], outward); + return (Index: i, Outward: outward, Offset: offset); + }).ToArray(); + bool InsideModelBox(double x, double y, double z) + { + foreach (var (_, outward, offset) in planes) + if (Dot(x, y, z, outward) > offset + 1e-7) return false; + return true; + } + + bool ClipsRpcOutline(Element element, Element type) + { + if (!element.BoundingBoxIsHeaderOutline || !ValidOutline(element.BoundingBox)) return false; + var bounds = element.BoundingBox!; + var placement = VerifiedRpcPlacement(element.Transform, type, bounds); + foreach (var (_, outward, offset) in planes) + { + double depth; + if (placement != null) + depth = Dot(placement.Origin[0], placement.Origin[1], placement.Origin[2], outward) + + OutlineSupport(type.BoundingBox!, Along(placement.BasisX), Along(placement.BasisY), Along(placement.BasisZ)); + // shortcut: the world outline is exact along Cartesian axes when the placed type outline is unverified. + else if (outward.Count(value => Math.Abs(value) > 1e-8) == 1) + depth = OutlineSupport(bounds, outward[0], outward[1], outward[2]); + else continue; + if (depth > offset + 1e-7) return true; + + double Along(double[] axis) => Dot(axis[0], axis[1], axis[2], outward); + } + return false; + } + + double Distance(double[] point, double[] outward, double offset) => + offset - Dot(point[0], point[1], point[2], outward); + + List<(double[] Point, bool IncomingEdge)> Clip(List ring) + { + var clipped = ring.Select(point => (Point: point, IncomingEdge: true)).ToList(); + foreach (var (_, outward, offset) in planes) + { + if (clipped.Count < 3) break; + clipped = ElevationPrinter.ClipHalfPlane3(clipped, point => Distance(point, outward, offset)); + } + return clipped; + } + + var materials = new Dictionary(); + (int Color, bool TransmitsLight, double Transmission) Material(int id) + { + if (materials.TryGetValue(id, out var material)) return material; + var element = document.GetElement(id); + int rgb = element?.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is int value and >= 0 and <= 0xffffff ? value : 0xc0c0c0; + // Reserve pure white for the image's transparent background. + if (rgb == 0xffffff) rgb = 0xfefefe; + double transparency = element?.SerializedMaterialTransparency is > 0 and <= 1 and double exact + ? exact : element?.LookupParameter(BuiltInParameter.MATERIAL_PARAM_TRANSPARENCY)?.Value + is int percent and > 0 and <= 100 ? percent / 100d : 0; + // Appearance assets can override the stored graphics transparency. + material = (rgb, element?.SerializedMaterialTransparency > 0, + element?.SerializedMaterialUsesRenderAppearance == true ? 0 : transparency); + materials.Add(id, material); + return material; + } + + var surfaces = new List(); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(view.Id); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(view.Id); + double left = double.PositiveInfinity, right = double.NegativeInfinity; + double bottom = double.PositiveInfinity, top = double.NegativeInfinity; + void AddSurface(Point[][] rings, double[] normal, double facing, int rgb, double transmission = 0, + ViewportSurfacePattern? pattern = null, ViewportSurfaceEdges? edges = null, bool prelit = false) + { + var outer = rings[0]; + if (transmission >= 1 || outer.Length < 3 || outer.Any(point => !double.IsFinite(point.X) + || !double.IsFinite(point.Y) || !double.IsFinite(point.Depth))) return; + left = Math.Min(left, outer.Min(p => p.X)); + right = Math.Max(right, outer.Max(p => p.X)); + bottom = Math.Min(bottom, outer.Min(p => p.Y)); + top = Math.Max(top, outer.Max(p => p.Y)); + var receiver = prelit ? ShadowReceiver.Prelit + : shadows?.FacesLight(normal) == true ? ShadowReceiver.FacingSun : ShadowReceiver.FacingAway; + surfaces.Add(new(rings, -Dot(normal[0], normal[1], normal[2], camera.Right) / (factor * facing), + -Dot(normal[0], normal[1], normal[2], camera.Up) / (factor * facing), rgb, receiver, transmission, pattern, edges)); + } + + double terrainBase = box.Origin[2] + box.Offsets[5]; + int cutMaterial = document.RawData.SiteCutGraphics?.MaterialId ?? -1; + var terrainSides = box.Active[5] && box.Axes[2][2] > 1 - 1e-8 && cutMaterial > 0 + ? planes.Where(plane => plane.Index < 4 && Math.Abs(plane.Outward[2]) < 1e-8 + && Dot(plane.Outward[0], plane.Outward[1], plane.Outward[2], camera.Look) < -1e-8) + .Select(side => + { + var outward = side.Outward; + int soil = Material(cutMaterial).Color; + int color = sceneLight is { } light ? ShadeTerrainCut(soil, outward, light.Sun, light.Intensity) : soil; + ViewportSurfacePattern? pattern = null; + if (showPatterns) + { + var origin = Project([outward[0] * side.Offset, outward[1] * side.Offset, 0]); + // Drafting dimensions are paper sizes before the cut plane is foreshortened by the camera. + var u = ProjectVector([-outward[1] * scale, outward[0] * scale, 0]); + var v = ProjectVector([0, 0, scale]); + pattern = ViewportSurfacePattern.CreateDraftingCut(document, cutMaterial, (origin.X, origin.Y), u, v, 0.1); + } + return (side.Outward, side.Offset, Color: color, Pattern: pattern); + }).ToArray() + : []; + foreach (var element in document.Elements) + { + if (element.Geometry is not { Faces.Count: > 0 } geometry || element.IsDiscovered + || element.OwnerViewId is > 0 || element.SerializedUnplacedOwnerId is > 0 || element.NativeIsSymbol == true + || element.RootClassIs("FamilySymbol") + || element.CategoryId is not int category || category >= 0 || hidden?.Contains(element.Id) == true + || hiddenCategories?.Contains(category) == true + || element.CategoryId is (int)BuiltInCategory.OST_Constraints or (int)BuiltInCategory.OST_CLines + or (int)BuiltInCategory.OST_Cameras or (int)BuiltInCategory.OST_LightingFixtureSource) continue; + Element? rpcType = category == (int)BuiltInCategory.OST_Planting && document.GetElement(element.TypeId) is { } type + && type.LookupParameter(BuiltInParameter.RENDER_RPC_FILENAME)?.Value is string { Length: > 0 } ? type : null; + if (rpcType != null && ClipsRpcOutline(element, rpcType)) continue; + foreach (var face in geometry.Faces) + { + if (face.OuterVertices is not { Count: >= 3 } ring) continue; + bool rpcMesh = rpcType != null && face.PolygonMesh; + var normal = face.Normal; + double facing = Dot(normal[0], normal[1], normal[2], camera.Look); + if (rpcMesh && facing > 1e-8) + { + normal = [-normal[0], -normal[1], -normal[2]]; + facing = -facing; + } + bool visible = facing < -1e-8; + double[]? casterNormal = null; + if (shadows?.FacesLight(normal) == true) casterNormal = normal; + else if (rpcMesh && shadows != null) + { + double[] otherSide = [-normal[0], -normal[1], -normal[2]]; + if (shadows.FacesLight(otherSide)) casterNormal = otherSide; + } + if (!visible && casterNormal == null) continue; + var clipped = Clip(ring); + if (clipped.Count < 3) continue; + var rings = new List { clipped.Select(vertex => vertex.Point).ToArray() }; + if (face.InnerVertices != null) + rings.AddRange(face.InnerVertices.Select(Clip).Where(hole => hole.Count >= 3) + .Select(hole => hole.Select(vertex => vertex.Point).ToArray())); + int materialId = face.RenderStyleId ?? face.NestedRenderStyleId ?? 0; + var material = Material(materialId); + // shortcut: opaque casters, until the renderer can accumulate transmission through separate panes. + if (casterNormal != null && !material.TransmitsLight) shadows!.AddCaster(rings, casterNormal); + if (!visible) continue; + ViewportSurfacePattern? pattern = null; + if (showPatterns && face.ModelPattern != null) + { + int pen = category == (int)BuiltInCategory.OST_Roofs ? (int)BuiltInCategory.OST_RoofsSurfacePattern : category; + pattern = ViewportSurfacePattern.Create(document, face, ProjectVector, patternOrigin.X, patternOrigin.Y, + Pen(pen).Width); + } + // shortcut: saved planar boundary loops, until non-planar source edges are projected. + ViewportSurfaceEdges? edges = showEdges && face.PlaneSurface && face.SourceLoops is { Count: > 0 } loops + ? SourceEdges(loops, category) : null; + int surfaceColor = material.Color; + if (rpcMesh && materialId <= 0 && sceneLight is { } light) + { + // Native unassigned RPC meshes use neutral gray under the shaded viewport light. + double diffuse = Math.Max(0, Dot(light.Sun.X, light.Sun.Y, light.Sun.Z, normal)); + surfaceColor = ShadeColor(0x808080, SolarStudyOverlay.LightFloor(light.Sun, light.Intensity) + diffuse); + } + AddSurface(rings.Select(loop => loop.Select(Project).ToArray()).ToArray(), normal, facing, + surfaceColor, material.Transmission, pattern, edges); + if (terrainSides.Length == 0 || element.CategoryId != (int)BuiltInCategory.OST_Topography + || normal[2] <= 0) continue; + for (int i = 0; i < clipped.Count; i++) + { + var a = clipped[i].Point; + var b = clipped[(i + 1) % clipped.Count].Point; + foreach (var (outward, offset, color, cutPattern) in terrainSides) + { + if (Math.Abs(Distance(a, outward, offset)) >= 1e-7 + || Math.Abs(Distance(b, outward, offset)) >= 1e-7) continue; + AddSurface([[Project(a), Project(b), Project([b[0], b[1], terrainBase]), + Project([a[0], a[1], terrainBase])]], outward, + Dot(outward[0], outward[1], outward[2], camera.Look), color, + pattern: cutPattern, prelit: sceneLight.HasValue); + } + } + } + } + ViewportSurfaceEdges? SourceEdges(IReadOnlyList> loops, int category) + { + var lines = new List<((double X, double Y) Start, (double X, double Y) End)>(); + foreach (var loop in loops) + { + var clipped = Clip(loop); + for (int i = 0; i < clipped.Count; i++) + { + // The box can introduce a new side on the clipped face. + if (!clipped[i].IncomingEdge) continue; + var a = Project(clipped[(i + clipped.Count - 1) % clipped.Count].Point); + var b = Project(clipped[i].Point); + lines.Add(((a.X, a.Y), (b.X, b.Y))); + } + } + if (lines.Count == 0) return null; + var (edgeWidth, color) = Pen(category); + return new(lines, edgeWidth, color); + } + if (shadows?.GroundShadowBounds is { } footprint) + { + left = Math.Min(left, anchorX + factor * footprint.Left); + right = Math.Max(right, anchorX + factor * footprint.Right); + bottom = Math.Min(bottom, anchorY + factor * footprint.Bottom); + top = Math.Max(top, anchorY + factor * footprint.Top); + } + if (annotation != null) + { + double span = annotation.Radius * 1.18; + left = Math.Min(left, annotation.X - span); + right = Math.Max(right, annotation.X + span); + bottom = Math.Min(bottom, annotation.Y - span); + top = Math.Max(top, annotation.Y + span); + } + left = Math.Max(left, camera.Active ? Math.Max(0, anchorX + camera.X0 * factor) : 0); + right = Math.Min(right, camera.Active ? Math.Min(page.Size.WidthMillimetres, anchorX + camera.X1 * factor) : page.Size.WidthMillimetres); + bottom = Math.Max(bottom, camera.Active ? Math.Max(0, anchorY + camera.Y0 * factor) : 0); + top = Math.Min(top, camera.Active ? Math.Min(page.Size.HeightMillimetres, anchorY + camera.Y1 * factor) : page.Size.HeightMillimetres); + double width = right - left, height = top - bottom; + if (!(width > 0 && height > 0)) return null; + + const double pixelsPerMillimetre = 144 / 25.4; + int columns = (int)Math.Clamp(Math.Ceiling(width * pixelsPerMillimetre), 1, 2048); + int rows = (int)Math.Clamp(Math.Ceiling(height * pixelsPerMillimetre), 1, 2048); + var depth = new double[columns * rows]; + var rgbBytes = new byte[depth.Length * 3]; + var shadowReceivers = shadows != null ? new ShadowReceiver[depth.Length] : null; + Array.Fill(depth, double.PositiveInfinity); + Array.Fill(rgbBytes, byte.MaxValue); + double stepX = width / columns, stepY = height / rows; + var crossings = new List(); + int FirstRow(Surface surface) => RasterIndex((top - surface.Rings[0].Max(p => p.Y)) / stepY, rows); + int LastRow(Surface surface) => RasterIndex((top - surface.Rings[0].Min(p => p.Y)) / stepY, rows); + int AtColumn(double x) => RasterIndex((x - left) / stepX, columns); + foreach (var surface in surfaces.Where(s => s.Transmission == 0)) + { + var outer = surface.Rings[0]; + var origin = outer[0]; + int first = FirstRow(surface), last = LastRow(surface); + for (int row = first; row < last; row++) + { + double y = top - (row + 0.5) * stepY; + GetCrossings(surface, y, crossings); + for (int i = 1; i < crossings.Count; i += 2) + { + int start = AtColumn(crossings[i - 1]); + int end = AtColumn(crossings[i]); + for (int column = start; column < end; column++) + { + double x = left + (column + 0.5) * stepX; + double z = origin.Depth + (x - origin.X) * surface.DepthX + (y - origin.Y) * surface.DepthY; + int pixel = row * columns + column; + if (!(z < depth[pixel])) continue; + depth[pixel] = z; + if (shadowReceivers != null) shadowReceivers[pixel] = surface.Receiver; + if (surface.Pattern == null && surface.Edges == null) + { + rgbBytes[3 * pixel] = (byte)surface.Rgb; + rgbBytes[3 * pixel + 1] = (byte)(surface.Rgb >> 8); + rgbBytes[3 * pixel + 2] = (byte)(surface.Rgb >> 16); + continue; + } + double patternInk = surface.Pattern?.Coverage(x, y, stepX, stepY) ?? 0; + double edgeInk = surface.Edges?.Coverage(x, y, stepX, stepY) ?? 0; + for (int channel = 0; channel < 3; channel++) + { + int tint = (surface.Rgb >> (channel * 8)) & 255; + rgbBytes[3 * pixel + channel] = (byte)Math.Round(ApplyInk(surface, channel, tint, patternInk, edgeInk)); + } + } + } + } + } + if (shadows != null && shadowReceivers != null) + shadows.Apply(rgbBytes, depth, shadowReceivers, columns, rows, left, top, stepX, stepY, anchorX, anchorY, + factor, InsideModelBox); + CompositePanes(); + annotation?.Paint(rgbBytes, columns, rows, left, top, stepX, stepY, depth); + page.DrawImage(new PdfRasterImage(columns, rows, rgbBytes) { TransparentWhite = true }, left, bottom, width, height); + if (annotation != null) + { + page.BeginClip(left, bottom, width, height); + annotation.DrawLabels(page); + page.EndClip(); + } + return (left, bottom, width, height); + + void CompositePanes() + { + var panes = surfaces.Select((surface, order) => (surface, order)).Where(pair => pair.surface.Transmission > 0) + .Select(pair => new Pane(pair.surface, pair.order, FirstRow(pair.surface), LastRow(pair.surface))) + .Where(pane => pane.FirstRow < pane.LastRow).OrderBy(pane => pane.FirstRow).ToArray(); + if (panes.Length == 0) return; + var activePanes = new List(); + var spans = new List(); + var activeSpans = new List(); + var hits = new List(); + int nextPane = 0, lastRow = panes.Max(pane => pane.LastRow); + for (int row = panes[0].FirstRow; row < lastRow; row++) + { + activePanes.RemoveAll(pane => pane.LastRow <= row); + while (nextPane < panes.Length && panes[nextPane].FirstRow == row) + activePanes.Add(panes[nextPane++]); + double y = top - (row + 0.5) * stepY; + spans.Clear(); + foreach (var pane in activePanes) + { + GetCrossings(pane.Surface, y, crossings); + for (int i = 1; i < crossings.Count; i += 2) + { + int start = AtColumn(crossings[i - 1]), end = AtColumn(crossings[i]); + if (start < end) spans.Add(new(pane, start, end)); + } + } + if (spans.Count == 0) continue; + spans.Sort(static (a, b) => a.Start.CompareTo(b.Start)); + activeSpans.Clear(); + int nextSpan = 0, lastColumn = spans.Max(span => span.End); + for (int column = spans[0].Start; column < lastColumn; column++) + { + activeSpans.RemoveAll(span => span.End <= column); + while (nextSpan < spans.Count && spans[nextSpan].Start == column) + activeSpans.Add(spans[nextSpan++]); + hits.Clear(); + int pixel = row * columns + column; + double x = left + (column + 0.5) * stepX; + foreach (var span in activeSpans) + { + var surface = span.Pane.Surface; + var origin = surface.Rings[0][0]; + double z = origin.Depth + (x - origin.X) * surface.DepthX + (y - origin.Y) * surface.DepthY; + if (z < depth[pixel]) hits.Add(new(span.Pane, z, surface.Pattern?.Coverage(x, y, stepX, stepY) ?? 0, + surface.Edges?.Coverage(x, y, stepX, stepY) ?? 0)); + } + if (hits.Count == 0) continue; + // Surfaces can cross in the view. Sort where each output ray actually meets them. + hits.Sort(static (a, b) => a.Depth == b.Depth + ? b.Pane.Order.CompareTo(a.Pane.Order) : b.Depth.CompareTo(a.Depth)); + for (int channel = 0; channel < 3; channel++) + { + double color = rgbBytes[3 * pixel + channel]; + foreach (var hit in hits) + { + var surface = hit.Pane.Surface; + int tint = (surface.Rgb >> (channel * 8)) & 255; + color = tint * (1 - surface.Transmission) + color * surface.Transmission; + color = ApplyInk(surface, channel, color, hit.PatternInk, hit.EdgeInk); + } + rgbBytes[3 * pixel + channel] = (byte)Math.Round(color); + } + } + } + } + } + + private static InstanceTransform? VerifiedRpcPlacement(InstanceTransform? candidate, Element type, double[] worldBounds) + { + if (candidate is not { Origin.Length: 3, BasisX.Length: 3, BasisY.Length: 3, BasisZ.Length: 3 } placement + || placement.SymbolId != type.Id || !type.BoundingBoxIsHeaderOutline || !ValidOutline(type.BoundingBox)) + return null; + + // Check that the placed type outline reproduces the saved world box before applying an oblique plane. + var local = type.BoundingBox!; + for (int axis = 0; axis < 3; axis++) + { + double x = placement.BasisX[axis], y = placement.BasisY[axis], z = placement.BasisZ[axis]; + double max = placement.Origin[axis] + OutlineSupport(local, x, y, z); + double min = placement.Origin[axis] - OutlineSupport(local, -x, -y, -z); + if (!(Math.Abs(max - worldBounds[3 + axis]) <= 1e-6 && Math.Abs(min - worldBounds[axis]) <= 1e-6)) + return null; + } + return placement; + } + + private static bool ValidOutline(double[]? bounds) => + bounds is { Length: 6 } && bounds.All(double.IsFinite) + && bounds[0] <= bounds[3] && bounds[1] <= bounds[4] && bounds[2] <= bounds[5]; + + private static double OutlineSupport(double[] bounds, double x, double y, double z) => + x * bounds[x < 0 ? 0 : 3] + y * bounds[y < 0 ? 1 : 4] + z * bounds[z < 0 ? 2 : 5]; + + private static int ShadeTerrainCut(int color, double[] normal, Vector3 sun, int intensity) + { + // shortcut: calibrated for vertical terrain cuts with zero configured ambient light. + double sky = SolarStudyOverlay.LightFloor(sun, intensity); + double direct = Math.Max(0, sun.X * normal[0] + sun.Y * normal[1]); + return ShadeColor(color, sky + direct); + } + + private static int ShadeColor(int color, double light) + { + // Saturate each colour channel, reserving pure white for the viewport background. + int Scale(int channel) => Math.Min(254, (int)Math.Round(((color >> channel) & 255) * light)); + return Scale(0) | Scale(8) << 8 | Scale(16) << 16; + } + + private static double ApplyInk(Surface surface, int channel, double color, double patternInk, double edgeInk) + { + if (surface.Pattern is { } pattern) + color += (((pattern.Color >> (channel * 8)) & 255) - color) * patternInk; + if (surface.Edges is { } edges) + color += (((edges.Color >> (channel * 8)) & 255) - color) * edgeInk; + return color; + } + + private static void GetCrossings(Surface surface, double y, List crossings) + { + crossings.Clear(); + // The even-odd crossings include the face's opening loops. + foreach (var ring in surface.Rings) + { + var previous = ring[^1]; + foreach (var next in ring) + { + if ((previous.Y > y) != (next.Y > y)) + crossings.Add(previous.X + (next.X - previous.X) * (y - previous.Y) / (next.Y - previous.Y)); + previous = next; + } + } + crossings.Sort(); + } + + private static double Dot(double x, double y, double z, double[] axis) => x * axis[0] + y * axis[1] + z * axis[2]; + + private static int RasterIndex(double coordinate, int count) => (int)Math.Clamp(Math.Ceiling(coordinate - 0.5), 0, count); +} diff --git a/src/RvtIO/Print/SheetComposer.ViewportTitles.cs b/src/RvtIO/Print/SheetComposer.ViewportTitles.cs new file mode 100644 index 00000000..8e88abb6 --- /dev/null +++ b/src/RvtIO/Print/SheetComposer.ViewportTitles.cs @@ -0,0 +1,57 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SheetComposer +{ + private static bool DrawViewportTitle(PdfPage page, RvtDocument document, Element viewport, Element? view, + string viewName, int scale, double originX, double originY) + { + if (document.RawData.ViewportTitles?.GetValueOrDefault(viewport.Id) is not { } title) return false; + if (!title.ShowLabel) return true; + if (viewport.ViewportLabelOrigin is not { Length: >= 2 } origin + || page.Owner.Font is not { } font + || document.RawData.ViewportTitleStyles?.GetValueOrDefault(title.SymbolId) is not { } style) + return false; + + double x = origin[0] * FeetToMillimetres - originX, y = origin[1] * FeetToMillimetres - originY; + double pen = PenWidths.TryAnnotationWidth(document, 1, out double width) ? width : 0.1; + if (title.ShowExtensionLine && viewport.ViewportLabelLength is > 0 and double length) + page.DrawLine(x, y, x + length * FeetToMillimetres, y, pen); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var arc in style.Arcs) + page.DrawArc(x + arc.X * FeetToMillimetres, y + arc.Y * FeetToMillimetres, + arc.Radius * FeetToMillimetres, arc.Start, arc.End, pen); + + string? sheetTitle = view?.LookupParameter(BuiltInParameter.VIEW_DESCRIPTION)?.Value as string; + foreach (var (label, fontPoints, wrap) in style.Labels) + { + string? value = (BuiltInParameter)label.ParamId switch + { + BuiltInParameter.VIEWPORT_VIEW_NAME => string.IsNullOrEmpty(sheetTitle) ? viewName : sheetTitle, + BuiltInParameter.VIEWPORT_DETAIL_NUMBER => + viewport.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string, + BuiltInParameter.VIEWPORT_SCALE => title.CustomScale + ?? (IsAnalysisView(view) ? null : $" 1 : {scale}"), + _ => null, + }; + if (string.IsNullOrEmpty(value)) continue; + var position = PlanPrinter.AnnotationLabelLayout(font, label, fontPoints, x, y); + string text = label.Prefix + value + label.Suffix; + double lineWidth = label.Width * FeetToMillimetres; + var lines = text.Contains('\n') || (wrap && lineWidth > 0 && page.MeasureText(text, position.Size) > lineWidth) + ? PlanPrinter.WrapPlanNoteText(page, text, position.Size, lineWidth, wrap && lineWidth > 0) + : [text]; + double lineHeight = label.Height * FeetToMillimetres; + double first = position.Baseline; + if ((label.Flags & 0x400) != 0) first += lineHeight * (lines.Count - 1) / 2; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], position.X, first - i * lineHeight, position.Size, position.Alignment); + } + return true; + } +} diff --git a/src/RvtIO/Print/SheetComposer.cs b/src/RvtIO/Print/SheetComposer.cs index 3edb2333..4ee22581 100644 --- a/src/RvtIO/Print/SheetComposer.cs +++ b/src/RvtIO/Print/SheetComposer.cs @@ -1,5 +1,7 @@ +using System.Globalization; using RvtIO.BuiltIns; using RvtIO.Model; +using RvtIO.Parsing; using RvtIO.Pdf; namespace RvtIO.Print; @@ -25,8 +27,19 @@ public sealed class SheetComposeOptions /// True (the default) draws the page border and, at its lower-right corner, the sheet number and name. /// This stands in for the title block while the linework of its family is not decoded. public bool DrawPageFrame { get; set; } = true; + + /// Rendered graphics by viewport element id. Bounds are in millimetres from the sheet's lower left. + public IReadOnlyDictionary? ViewportImages { get; set; } } +/// A rendered viewport and its bounds on a sheet, in millimetres. +/// The rendered graphics, drawn in place of the viewport's own content. +/// The left edge, from the lower left corner of the sheet. +/// The bottom edge, from the lower left corner of the sheet. +/// The width; positive and finite. +/// The height; positive and finite. +public sealed record SheetViewportImage(IPdfImage Image, double X, double Y, double Width, double Height); + /// A sheet that can be composed: the element id, its number and name, the page its title block spans and the /// number of placed viewports and text notes. /// The element id of the sheet. @@ -44,7 +57,7 @@ public sealed record ComposedSheet(int SheetId, string? Number, string? Name, Pd /// labelled with its name and scale, and the sheet's own text notes are written at their positions. The linework of the /// title block family and the fills of rooms are not decoded yet (see docs/printing.md). /// -public static class SheetComposer +public static partial class SheetComposer { private const double FeetToMillimetres = 304.8; @@ -93,6 +106,9 @@ public static PdfDocument Render(RvtDocument document, int sheetId, SheetCompose /// The element ids of the sheets. /// The paper and labels; null uses the defaults. /// An element id is not a sheet with a number. + /// holds an entry that is not a + /// viewport of the selected sheets, has no image, or has bounds that are not finite with a positive width and + /// height. public static PdfDocument RenderSheets(RvtDocument document, IReadOnlyList sheetIds, SheetComposeOptions? options = null) { @@ -100,6 +116,8 @@ public static PdfDocument RenderSheets(RvtDocument document, IReadOnlyList ArgumentNullException.ThrowIfNull(sheetIds); options ??= new SheetComposeOptions(); var pdf = new PdfDocument { Font = PdfFonts.TryFind(out _), Compress = true }; + if (ViewportImageProblem(document, sheetIds, options.ViewportImages) is { } problem) + throw new ArgumentException(problem, nameof(options)); var plans = new Dictionary(); foreach (var view in PlanPrinter.Views(document)) plans[view.ViewId] = view; foreach (int sheetId in sheetIds) @@ -114,6 +132,27 @@ public static PdfDocument RenderSheets(RvtDocument document, IReadOnlyList return pdf; } + /// Names the first entry of that cannot be drawn on the selected sheets, or null + /// when every entry can: the key is a viewport of one of the sheets, the entry has an image, and its bounds are + /// finite with a positive width and height. + internal static string? ViewportImageProblem(RvtDocument document, IReadOnlyList sheetIds, + IReadOnlyDictionary? images) + { + if (images == null) return null; + var selected = sheetIds.ToHashSet(); + foreach (var (id, raster) in images) + { + var viewport = document.GetElement(id); + if (viewport?.OwnerViewId is not int owner || !selected.Contains(owner) || viewport.ViewportViewId == null) + return $"Element {id} is not a viewport on the selected sheets."; + if (raster?.Image == null) return $"Viewport {id} has no image."; + if (!double.IsFinite(raster.X) || !double.IsFinite(raster.Y) || !double.IsFinite(raster.Width) + || !double.IsFinite(raster.Height) || raster.Width <= 0 || raster.Height <= 0) + return $"Viewport {id} needs finite image bounds with a positive width and height."; + } + return null; + } + private static void AddSheetPage(PdfDocument pdf, RvtDocument document, Element sheet, Dictionary plans, SheetComposeOptions options) { @@ -212,12 +251,19 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig centerY = offset[1] * FeetToMillimetres - originY; } double frameX = centerX, frameY = centerY, frameWidth = 0, frameHeight = 0; - if (placed && view?.RootClassName == "DBView3d" && !IsAnalysisView(view)) + var raster = options.ViewportImages?.GetValueOrDefault(element.Id); + bool rendered = raster != null; + if (raster != null) + page2.DrawImage(raster.Image, raster.X, raster.Y, raster.Width, raster.Height); + else if (placed && view?.RootClassName == "DBView3d" && IsAnalysisView(view)) { - // A 3D view: an isometric projection of the model, white faces with their outlines, as the massing the - // view would show without its rendering. A sun or lighting analysis prints as its shaded study, not - // as vector massing (the reference shows no such linework, and rvt-prt draws 3D only with a camera - // looking off-axis): those viewports print nothing vector, like an unplaced view. + effectiveScale = element.ViewportScale ?? scale; + if (ShadedViewport.Render(page2, document, view, centerX, centerY, effectiveScale) is { } frame) + (frameX, frameY, frameWidth, frameHeight) = frame; + } + else if (placed && view?.RootClassName == "DBView3d" && !IsAnalysisView(view)) + { + // A 3D view without a rendered study prints as isometric massing. var model = ElevationPrinter.Collect(document, "iso"); if (model != null) { @@ -237,18 +283,28 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig else if (placed && view?.RootClassName == "DBViewRendering") { // A rendering: the JPEG Revit stored for the view, placed at the offset of its viewport. - if (RenderingImage(document, viewId) is { } jpeg) + if (RenderingImage(document, viewId) is { } rendering) { + var jpeg = rendering.Image; double height = 110, width = height * jpeg.Width / jpeg.Height; - if (width > 240) + double x; + if (rendering.Size is { } size) + { + width = size.Width * FeetToMillimetres; + height = size.Height * FeetToMillimetres; + x = centerX - width / 2; + } + else { - width = 240; - height = width * jpeg.Height / jpeg.Width; + if (width > 240) + { + width = 240; + height = width * jpeg.Height / jpeg.Width; + } + double stripLeft = layout.WidthMillimetres - 5 + - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; + x = Math.Min(centerX - width / 2, stripLeft - width); } - // The images keep clear of the title block strip on the right. - double stripLeft = layout.WidthMillimetres - 5 - - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; - double x = Math.Min(centerX - width / 2, stripLeft - width); page2.DrawImage(jpeg, x, centerY - height / 2, width, height); } } @@ -284,22 +340,52 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig { ClipFrame(frameX, frameY, frameWidth, frameHeight); } + var planGrids = cropped && view != null && planCrop != null + ? PlanPrinter.CollectPlanGrids(document, view, planCrop, drawScale) : null; + var planDimensions = cropped && planCrop != null + ? PlanPrinter.CollectPlanDimensions(document, viewId, planCrop) : []; + var sectionMarks = ElevationPrinter.SectionMarks(document, viewId, viewScale); PlanPrinter.DrawContent(page2, content, drawScale, drawOriginX, drawOriginY, 0.9, - ElevationPrinter.SectionMarks(document, viewId, viewScale), document, + sectionMarks.Where(mark => !mark.UsesPlanExtent).ToArray(), document, (frameX, frameY, frameX + frameWidth, frameY + frameHeight), - clipRect: cropped && planCrop != null ? CropContentRect(planCrop) : null); + clipRect: cropped && planCrop != null ? CropContentRect(planCrop) : null, + drawGrids: planGrids == null, drawFallbackDimensions: planDimensions.Count == 0, planViewId: viewId); + PlanPrinter.DrawStairPaths(page2, document, viewId, plan.LevelId, content, drawScale, drawOriginX, drawOriginY); page2.EndClip(); + PlanPrinter.DrawSectionMarks(page2, content, drawScale, drawOriginX, drawOriginY, + sectionMarks.Where(mark => mark.UsesPlanExtent).ToArray(), null, document, viewId); + CircularAnnotations.DrawViewport(page2, document, view, CircularAnnotations.Project(document, viewId), + drawScale, drawOriginX, drawOriginY, content.MinX, content.MinY, cropped ? planCrop : null); + if (planGrids != null) + PlanPrinter.DrawPlanGrids(page2, document, planGrids, content, drawScale, drawOriginX, drawOriginY); + PlanPrinter.DrawPlanDimensions(page2, planDimensions, content, drawScale, drawOriginX, drawOriginY); + if (cropped && planCrop != null) + PlanPrinter.DrawPlanNotes(page2, document, viewId, planCrop, content, drawScale, drawOriginX, drawOriginY); + if (cropped && planCrop != null && view != null) + PlanElevationMarks.Draw(page2, document, view, planCrop, drawScale, centerX, centerY); effectiveScale = (int)Math.Round(drawScale); if (options.DrawRoomLegend && pdf.Font != null && content.Rooms.Count > 0) - DrawRoomLegend(page2, content.Rooms.Select(room => room.Name), Math.Max(frameX, 8), - frameY - 16); + { + var legend = document.Elements.FirstOrDefault(e => e.OwnerViewId == viewId && e.RoomLegendOrigin.HasValue); + var names = content.Rooms.Select(room => room.Name); + if (legend?.RoomLegendOrigin is { } anchor) + { + double x = drawOriginX + (anchor.X * FeetToMillimetres - content.MinX) / drawScale; + double y = drawOriginY + (anchor.Y * FeetToMillimetres - content.MinY) / drawScale; + var swatch = document.GetElement(legend.TypeId)?.ColorLegendSwatch; + DrawRoomLegend(page2, names, x, y, swatch, content.RoomColors); + } + else + { + DrawRoomLegend(page2, names, Math.Max(frameX, 8), frameY - 16, null, content.RoomColors); + } + } } } else if (placed && name.Contains("site", StringComparison.OrdinalIgnoreCase)) { - // A site view: the planting tags over the paper, not the plan of a level. The reference - // site plan draws no building, terrain or planting graphics, so no level is collected for it. - var site = SitePrinter.Collect(document); + // Site graphics and the building footprint share the site's view projection. + var site = SitePrinter.Collect(document, viewId); if (site != null) { // The building stands on the site: the walls of the level with most walls go on the same plan, @@ -319,13 +405,14 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig if (bestLevel is int levelId) sitePlan = PlanPrinter.CollectLevel(document, levelId); } - if (sitePlan != null) + if (sitePlan != null && view?.ViewCrop is not { Active: true }) site = KeepSiteNearBuilding(site, sitePlan); // A site view whose crop basis is turned prints its plan turned: the Site view's crop Right is // (0.7986, -0.6018), a -37 degree view, and the reference site plan is drawn turned with it. // Project the graphics on the view's own axes; the tags and the north arrow stay upright. - if (view?.ViewCrop is { Active: true } basisCrop - && Math.Abs(basisCrop.Right[1]) > 1e-6) + var basisCrop = view?.ViewCrop is { Active: true } basis && Math.Abs(basis.Right[1]) > 1e-6 + ? basis : null; + if (basisCrop != null) { site = SitePrinter.InViewBasis(site, basisCrop.Right, basisCrop.Up); if (sitePlan != null) @@ -362,7 +449,13 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig siteDrawOriginX = frameX; siteDrawOriginY = frameY; } - SitePrinter.DrawContent(page2, site, drawScale, siteDrawOriginX, siteDrawOriginY); + bool opaqueSite = document.RawData.OpaquePlanViews?.Contains(viewId) == true; + var graphics = opaqueSite ? SitePrinter.CollectOpaqueGraphics(document, viewId, basisCrop) : null; + var plantingTags = SitePrinter.CollectTags(document, viewId, basisCrop); + var outlines = document.RawData.PlanOutlineAnnotations?.GetValueOrDefault(viewId); + SitePrinter.DrawContent(page2, site, drawScale, siteDrawOriginX, siteDrawOriginY, document, + opaqueSite, graphics, drawFallbackTags: plantingTags.Count == 0, drawFallbackNorth: outlines == null, + viewId: viewId, basis: basisCrop); effectiveScale = (int)Math.Round(drawScale); if (sitePlan is { } building) { @@ -394,7 +487,19 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig wallsOriginX, wallsOriginY, 0.9, null, document); } + if (graphics != null) + SitePrinter.DrawSurfaces(page2, document, graphics, site, drawScale, siteDrawOriginX, siteDrawOriginY); page2.EndClip(); + SitePrinter.DrawTags(page2, document, plantingTags, site, drawScale, siteDrawOriginX, siteDrawOriginY); + SitePrinter.DrawPropertyTags(page2, document, viewId, basisCrop, + site, drawScale, siteDrawOriginX, siteDrawOriginY); + if (outlines != null) + SitePrinter.DrawOutlineAnnotations(page2, document, outlines, basisCrop, + site, drawScale, siteDrawOriginX, siteDrawOriginY); + CircularAnnotations.DrawViewport(page2, document, view, + CircularAnnotations.Project(document, viewId, basisCrop?.Right, basisCrop?.Up), + drawScale, siteDrawOriginX, siteDrawOriginY, site.MinX, site.MinY, + siteCropped ? view?.ViewCrop : null); // The planting schedule sits under the view title, clear of the site plan, unless its real // instance drew at its own origin below. if (pdf.Font != null && !SchedulesOnSheet(document, sheet).Any(schedule => schedule.CategoryId == PlantingCategoryId)) @@ -409,15 +514,17 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // An elevation or a section: the model faces projected on the view's plane when the reader decoded it // (a section is then cut at its plane), otherwise on the plane of the direction taken from the name. Element? viewElement = document.GetElement(viewId); + bool unshadedHiddenLine = document.RawData.UnshadedHiddenLineViews?.Contains(viewId) == true; // A detail section (1:10 to 1:50) is drawn from its own file crop frame: the crop rectangle is // the detail's true extent (a roof detail's crop sits at roof height), while the old // plane-origin window showed the wrong slice (the plane origin sits floors below the crop). // Without a usable crop the invented window stays as a fallback. A stair section is printed // whole like a building section, not as a detail; a stair detail (1:20) shows the stair in // its enclosure through the file's own crop frame, the way the reference places it next to - // the stair section. + // the stair section. With the authored crop, the surrounding cut belongs in the section. bool stairSection = name.Contains("stair", StringComparison.OrdinalIgnoreCase); - bool stairsOnly = stairSection && scale >= 50; + bool stairsOnly = stairSection && scale >= 50 + && !(view?.ViewCrop is { Active: true } stairCrop && ViewBasisMatches(viewElement, stairCrop)); double stripLeftForStair = layout.WidthMillimetres - 5 - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; bool detailSection = direction == "section" && scale < 100 && !stairSection @@ -429,10 +536,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig bool detailCropUsable = detailSection && viewElement?.ViewCrop is { Active: true } detailCrop && ViewBasisMatches(viewElement, detailCrop); (double Width, double Height)? detailWindow = detailSection && !detailCropUsable ? (3000, 2200) : null; - // A fallback-windowed detail the file puts against the border or outside the page is still - // printed: Revit lays such callouts out in a bottom row above their own titles (A104's four - // details), so the frame is anchored on the decoded title label instead of the file offset. - // A crop-drawn detail relocates the same way in the crop branch below. + // Without a model crop, an off-page detail uses the decoded title as its fallback anchor. bool detailRelocated = detailWindow != null && !(centerX > 40 && centerX < stripLeft - 40 && centerY > 40 && centerY < layout.HeightMillimetres - 40) && element.ViewportLabelOrigin is { Length: >= 2 } @@ -441,7 +545,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig ElevationPrinter.Collect(document, direction, stairsOnly, viewElement, detailWindow, isDetail: detailSection, cropWindow: detailSection && detailCropUsable && viewElement?.ViewCrop is { Active: true } dc - ? CropContentRect(dc) : null); + ? CropContentRect(dc) : null, viewportScale: scale); // A viewport whose view decoded a crop frame draws the crop at the view's own scale, placed by // the viewport offset (sheet = offset + view / scale): the frame is the crop rectangle and the // content is clipped to it, nothing is reduced to fit. The crop applies only where the collection @@ -456,13 +560,10 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig out frameX, out frameY, out frameWidth, out frameHeight, out double cropOriginX, out double cropOriginY)) { effectiveScale = scale; - // A crop-drawn detail the file parked off the page is laid out in a bottom row above its own - // title (A104's four details): anchor the frame on the decoded title label instead of the - // file offset. The viewport center anchors the view origin (view coordinates 0, 0), not the - // frame center, so back out the crop offset: the frame lands centered on the title with its - // bottom clearing the title text (about 20 mm above its line on A104). + // A detail's projected view origin can be far from its crop, especially at large scales. + // Fall back to the title only when the mapped crop is entirely off the sheet. if (detailSection - && !(centerX > 40 && centerX < stripLeft - 40 && centerY > 40 && centerY < layout.HeightMillimetres - 40) + && !CropOverlapsSheet(frameX, frameY, frameWidth, frameHeight, layout.WidthMillimetres, layout.HeightMillimetres) && element.ViewportLabelOrigin is { Length: >= 2 } cropLabelOrigin && element.ViewportLabelLength is double cropLabelLength && cropLabelLength > 0) { @@ -494,8 +595,16 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig double clipExtra = elevation.Levels.Count > 0 ? 45 : 0; page2.BeginClip(frameX, frameY, Math.Max(0, frameWidth + clipExtra), Math.Max(0, frameHeight)); ElevationPrinter.DrawContent(page2, elevation, scale, cropOriginX, cropOriginY, - direction == "section" ? 0.82 : 1, document, (cropX0, cropY0, cropX1, cropY1)); + direction == "section" ? 0.82 : 1, document, (cropX0, cropY0, cropX1, cropY1), + drawNativeDatums: false, unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); + ElevationPrinter.DrawNativeDatums(page2, elevation, scale, cropOriginX, cropOriginY, document, + (cropX0, cropY0, cropX1, cropY1)); + CircularAnnotations.DrawViewport(page2, document, viewElement, elevation.AnnotationSymbols ?? [], + scale, cropOriginX, cropOriginY, elevation.MinX, elevation.MinY, crop); + if (direction == "section" && viewElement != null) + DetailAnnotations.DrawCallouts(page2, document, sheet, viewElement, crop, scale, + cropOriginX - elevation.MinX / scale, cropOriginY - elevation.MinY / scale); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } else if (elevation != null) @@ -520,7 +629,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig effectiveScale = scale; page2.BeginClip(frameX, frameY, Math.Max(0, frameWidth), Math.Max(0, frameHeight)); ElevationPrinter.DrawContent(page2, elevation, drawScale, frameX, frameY, - direction == "section" ? 0.82 : 1, document); + direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } @@ -596,13 +706,15 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig } ClipFrame(frameX, frameY, frameWidth, frameHeight); ElevationPrinter.DrawContent(page2, elevation, drawScale, frameX, frameY, - direction == "section" ? 0.82 : 1, document); + direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } } } - if (placed && frameWidth > 0) + // The analysis viewport has its own scale label and does not determine the sheet scale. + if (placed && frameWidth > 0 && !(view?.RootClassName == "DBView3d" && IsAnalysisView(view))) { effectiveScales[effectiveScale] = effectiveScales.TryGetValue(effectiveScale, out int counted) ? counted + 1 : 1; @@ -611,7 +723,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // study is a raster) is not titled either — except the analysis views: their title line and label are // sheet annotation the reference prints, even though the study itself is an image. if (options.DrawViewLabels && pdf.Font != null - && (!placed || frameHeight > 0 || IsAnalysisView(view))) + && (!placed || frameHeight > 0 || rendered || IsAnalysisView(view)) + && !DrawViewportTitle(page2, document, element, view, name, effectiveScale, originX, originY)) { // The view title as Revit draws it: a circled detail number, the view name beside it, the scale below // and the extension line under the title. The file stores the line's origin on the sheet and its @@ -662,24 +775,14 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig page2.DrawText(detail, frameX + 3, labelY + 0.2, 2.4, PdfTextAlignment.Center); textX = frameX + 8; } - page2.DrawLine(ruleX0, ruleY, ruleX1, ruleY, gridPen); + if (document.RawData.ViewportTitles?.GetValueOrDefault(element.Id)?.ShowExtensionLine != false) + page2.DrawLine(ruleX0, ruleY, ruleX1, ruleY, gridPen); page2.DrawText(name, textX, labelY, 3.5); page2.DrawText($"1:{effectiveScale}", textX, labelY - 3.5, 2.5, PdfTextAlignment.Left, 0.45); } } - foreach (var element in document.Elements) - { - if (element.OwnerViewId != sheet.Id) continue; - if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) - continue; - double x = position[0] * FeetToMillimetres - originX; - double y = position[1] * FeetToMillimetres - originY; - double height = element.TextFontSizePoints is double points && points > 0 ? points * 25.4 / 72 : 2.5; - string[] lines = text.Split('\n'); - for (int line = 0; line < lines.Length; line++) - page2.DrawText(lines[line], x, y - line * height * 1.25, height); - } + SheetPrinter.DrawSheetNotes(page2, document, sheet.Id, -originX, -originY); // The title block goes last, over the drawings. Decoded linework draws at its sheet position with its // annotation pens (0.7 pt where the style has no pen, as rvt-prt draws it), with its fixed texts and @@ -688,6 +791,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // and no drawing line runs under the strip. if (options.DrawPageFrame && pdf.Font != null) { + var titleScales = effectiveScales.Keys; string scaleText = effectiveScales.Count > 0 ? "1:" + effectiveScales.OrderByDescending(pair => pair.Value).First().Key : ""; @@ -704,16 +808,24 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig if (scale == 0) continue; nominal[scale] = nominal.TryGetValue(scale, out int count) ? count + 1 : 1; } - if (nominal.Count > 0) scaleText = "1:" + nominal.OrderByDescending(pair => pair.Value).First().Key; + if (nominal.Count > 0) + { + titleScales = nominal.Keys; + scaleText = "1:" + nominal.OrderByDescending(pair => pair.Value).First().Key; + } } if (titleLines != null) { - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>? titleTexts = null; - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>? titleLabels = null; - document.RawData.TitleBlockTexts?.TryGetValue(titleSymbolId, out titleTexts); - document.RawData.TitleBlockLabels?.TryGetValue(titleSymbolId, out titleLabels); - DrawTitleBlockSymbol(page2, document, sheet, scaleText, titleLines, + var titleTexts = document.RawData.TitleBlockTexts?.GetValueOrDefault(titleSymbolId); + var titleLabels = document.RawData.TitleBlockLabels?.GetValueOrDefault(titleSymbolId); + var scaleOverride = sheet.LookupParameter(BuiltInParameter.SHEET_SCALE_OVERRIDE)?.Value as string; + string titleScale = !string.IsNullOrWhiteSpace(scaleOverride) ? scaleOverride + : TitleBlockScale(titleScales, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"); + DrawTitleBlockSymbol(page2, document, sheet, titleScale, titleLines, titleTexts, titleLabels, originX, originY); + foreach (var (image, x, y, width, height) in TitleBlockImages(document, titleSymbolId)) + page2.DrawImage(image, x * FeetToMillimetres - originX, y * FeetToMillimetres - originY, + width * FeetToMillimetres, height * FeetToMillimetres); } else { @@ -726,6 +838,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // their stored rows, the header and grid always drawn (rvt-prt tables.py). DrawSchedules(page2, document, sheet, originX, originY); } + CircularAnnotations.Draw(page2, document, CircularAnnotations.Project(document, sheet.Id), 1, + x => x - originX, y => y - originY); } private const int RevisionsCategoryId = -2006070; @@ -737,8 +851,13 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig internal sealed record ScheduleOnSheet(int InstanceId, int ScheduleId, double Ox, double Oy, List<(string Heading, double WidthFt)> Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, string Title, - double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, - int GridStyleId, int OutlineStyleId, double FixedHeightFt); + double TitleHeightFt, TfBlockDeserializer.ScheduleTextStyle TitleStyle, + List<(double HeightFt, string Text, TfBlockDeserializer.ScheduleTextStyle Style)> TitleBands, + List BodySections, + int GridStyleId, int OutlineStyleId, double FixedHeightFt) + { + internal (double Header, double Body)? RevisionCapHeightsFt { get; init; } + } /// The schedule instances placed on the sheet whose placement and table both decoded: the revision /// schedules of the title block, the planting schedule and the How-do-I table. @@ -757,8 +876,9 @@ internal static List SchedulesOnSheet(RvtDocument document, Ele result.Add(new(element.Id, placement.ScheduleId, placement.Ox, placement.Oy, table.Columns, table.CategoryId, table.ShowTitle, table.ShowHeaders, table.ShowGridLines, table.ShowOutline, title, - table.TitleHeightFt, table.TitleBands, table.BodySections, - table.GridStyleId, table.OutlineStyleId, table.FixedHeightFt)); + table.TitleHeightFt, table.TitleStyle, table.TitleBands, table.BodySections, + table.GridStyleId, table.OutlineStyleId, table.FixedHeightFt) + { RevisionCapHeightsFt = table.RevisionCapHeightsFt }); } return result; } @@ -772,6 +892,16 @@ private static void DrawSchedules(PdfPage page, RvtDocument document, Element sh DrawSchedule(page, document, sheet, schedule, originX, originY); } + internal static double? ScheduleTextSize(PdfTrueTypeFont? font, TfBlockDeserializer.ScheduleTextStyle style) + { + if (font is not { CapHeight: > 0 } || style is not + { CapHeightPixels: > 0 and <= 256, HorizontalAlignment: 0 or 1, VerticalAlignment: 4 or 8 }) return null; + // The schedule style stores cap height in 96-dpi pixels; PDF places an em at the corresponding half-point size. + double emPoints = style.CapHeightPixels * 72 / 96 * font.UnitsPerEm / font.CapHeight; + double points = Math.Round(emPoints * 2, MidpointRounding.AwayFromZero) / 2; + return points > 0 ? points * 25.4 / 72 : null; + } + private static void DrawSchedule(PdfPage page, RvtDocument document, Element sheet, ScheduleOnSheet schedule, double originX, double originY) { @@ -779,7 +909,7 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she const double PtToMm = 25.4 / 72.0; const double InchToMm = 25.4; bool revision = schedule.CategoryId == RevisionsCategoryId; - // Measured styles (rvt-prt tables.py SCHEDULE_STYLES): the file decodes no text sizes. + // Defaults for table areas whose text style has not been decoded. // The revision body pitch is measured on the sample's reference (16.30 pt rows of 12 pt Arial); // rvt-prt's 0.2559 in overshoots here and would drift the grid out of tolerance within a few rows. double titleH = revision ? 0 : 0.37 * InchToMm; @@ -787,6 +917,28 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she double bodyH = revision ? 16.30 * PtToMm : 0.2395 * InchToMm; double titlePt = 19, headPt = revision ? 19 : 12.5, bodyPt = 12.5; double insetMm = 0.037 * InchToMm; + const double pixelMm = InchToMm / 96; + IReadOnlyList? revisionHeaderStyles = null; + double revisionHeaderCapMm = 0; + if (revision && schedule.RevisionCapHeightsFt is { } cap + && page.Owner.Font is { CapHeight: > 0 } revisionFont + && string.Equals(revisionFont.Name, "Arial", StringComparison.OrdinalIgnoreCase) + && schedule.BodySections is [{ HeaderStyles: { } savedRevisionStyles }] + && savedRevisionStyles.Count == schedule.Columns.Count + && savedRevisionStyles.All(style => style is { HorizontalAlignment: 1, VerticalAlignment: 8, Flags: 1 } + && string.Equals(style.FontName, "Arial", StringComparison.OrdinalIgnoreCase) + && Math.Abs(style.CapHeightPixels * pixelMm - cap.Header * FeetToMillimetres) < 1e-6)) + { + // shortcut: the measured Arial revision-cell metrics, until other fonts and styles are verified. + const double revisionRowPerCapHeight = 23d / 12; + revisionHeaderStyles = savedRevisionStyles; + revisionHeaderCapMm = cap.Header * FeetToMillimetres; + double bodyCapMm = cap.Body * FeetToMillimetres; + headH = revisionHeaderCapMm * revisionRowPerCapHeight; + bodyH = bodyCapMm * revisionRowPerCapHeight; + bodyPt = Math.Round(bodyCapMm * revisionFont.UnitsPerEm / revisionFont.CapHeight / PtToMm * 2, + MidpointRounding.AwayFromZero) / 2; + } // The stored title height wins where the file decodes it (the How-do-I title area: stored 20.2 pt // against measured 26.6; the planting title: stored 30 pt against measured 26.6). if (!revision && schedule.TitleHeightFt > 0) @@ -801,6 +953,15 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she for (int i = 0; i < widths.Length; i++) edges[i + 1] = edges[i] + widths[i]; List> rows = new(); + bool russian = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + string yes = russian ? "Да" : "Yes", no = russian ? "Нет" : "No"; + var authoredRows = document.RawData.EvaluatedScheduleRows?.GetValueOrDefault(schedule.ScheduleId) + ?.Select(row => row.Select(cell => cell.Boolean switch + { + true => yes, + false => no, + _ => cell.Text, + }).ToList()).ToList(); if (revision) { // The revisions explicitly present on this sheet (rvt-prt sheet_revs): the reference lists none, @@ -824,11 +985,6 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she foreach (var (mark, name, count) in PlantingRows(document)) rows.Add([mark, name, count]); } - else - { - // Other schedules draw their stored body sections below (one header per section, then the - // stored body row count as an empty grid: the body cells carry no evaluated text). - } foreach (var row in rows) while (row.Count < widths.Length) row.Add(""); @@ -850,63 +1006,86 @@ double AnnotationWidth(int categoryId, double fallback) double y = yTop; double tableTop = yTop; - // Schedule titles print one ascent below the row top (measured 18.4 pt below at 19 pt on both - // the How-do-I and planting titles), not centred in the row. bool drewTitleArea = false; if (schedule.ShowTitle && titlePt > 0 && schedule.Title.Length > 0 && !schedule.Title.StartsWith("<", StringComparison.Ordinal)) { - page.DrawText(schedule.Title, (edges[0] + edges[^1]) / 2, y - 0.97 * titlePt * PtToMm, - titlePt * PtToMm, PdfTextAlignment.Center); + if (ScheduleTextSize(page.Owner.Font, schedule.TitleStyle) is double size) + DrawCellText([schedule.Title], titleH, size, schedule.TitleStyle, edges[0], edges[^1]); + else + page.DrawText(schedule.Title, (edges[0] + edges[^1]) / 2, y - 0.97 * titlePt * PtToMm, + titlePt * PtToMm, PdfTextAlignment.Center); y -= titleH; drewTitleArea = true; if (schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); } - // Stored title bands (the How-do-I long-text band): merged rows with no internal grid, the text - // top-aligned (measured 5.5 pt below the band top at 12.5 pt). + // Stored title bands are merged rows with no internal grid. foreach (var band in schedule.TitleBands) { double bandH = band.HeightFt * FeetToMillimetres; if (!(bandH > 0) || bandH > 1000) continue; if (band.Text.Length > 0) - page.DrawText(band.Text, edges[0] + insetMm, y - 5.5 * PtToMm, bodyPt * PtToMm); + { + page.BeginClip(edges[0], y - bandH, edges[^1] - edges[0], bandH); + if (ScheduleTextSize(page.Owner.Font, band.Style) is double size) + { + var lines = Wrap(band.Text, edges[^1] - edges[0] - 6 * pixelMm, size); + DrawCellText(lines, bandH, size, band.Style, edges[0], edges[^1]); + } + else + { + double fallbackSize = bodyPt * PtToMm; + double baseline = y - insetMm - fallbackSize * 0.85; + foreach (string line in Wrap(band.Text, edges[^1] - edges[0] - 2 * insetMm, fallbackSize)) + { + page.DrawText(line, edges[0] + insetMm, baseline, fallbackSize); + baseline -= fallbackSize * 1.125; + } + } + page.EndClip(); + } y -= bandH; drewTitleArea = true; if (schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); } + void DrawCellText(IReadOnlyList lines, double height, double size, + TfBlockDeserializer.ScheduleTextStyle style, double left, double right) + { + var font = page.Owner.Font!; + double linePitch = Math.Round(size * (font.Ascent - font.Descent) / font.UnitsPerEm / pixelMm) * pixelMm; + double baseline = style.VerticalAlignment == 8 + ? y - height + 3 * pixelMm - size * font.Descent / font.UnitsPerEm + (lines.Count - 1) * linePitch + : y - height / 2 - size * (font.Ascent + font.Descent) / (2 * font.UnitsPerEm) + + (lines.Count - 1) * linePitch / 2; + var alignment = style.HorizontalAlignment == 1 ? PdfTextAlignment.Center : PdfTextAlignment.Left; + double x = alignment == PdfTextAlignment.Center ? (left + right) / 2 : left + 3 * pixelMm; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], x, baseline - i * linePitch, size, alignment); + } // Header texts wrap into their columns ("Type Mark" wraps to two lines in its narrow column): - // the header grows one body row per wrapped line after the first (measured 31.8 pt for two lines - // against 17.3 for one), each column's lines centred as a block. - List> WrapHeaders(List header, double sizeMm) + // The header expands for the tallest wrapped column before each cell applies its alignment. + List Wrap(string text, double width, double size) { - var wrapped = new List>(widths.Length); - for (int i = 0; i < widths.Length; i++) + var lines = new List(); + foreach (string word in text.Split(' ')) { - string text = i < header.Count ? header[i] : ""; - var lines = new List(); - if (text.Length > 0) - { - foreach (string word in text.Split(' ')) - { - string candidate = lines.Count == 0 ? word : lines[^1] + " " + word; - if (lines.Count > 0 && page.MeasureText(candidate, sizeMm) <= widths[i]) - lines[^1] = candidate; - else - lines.Add(word); - } - } - if (lines.Count == 0) lines.Add(""); - wrapped.Add(lines); + string candidate = lines.Count == 0 ? word : lines[^1] + " " + word; + if (lines.Count > 0 && page.MeasureText(candidate, size) <= width) + lines[^1] = candidate; + else + lines.Add(word); } - return wrapped; + return lines; } + // Header texts come from the stored section header where the file decodes one, else from the // schedule fields; other schedules draw one header per stored body section. - List<(List Header, List> Rows)> sections = new(); + List<(List Header, List> Rows, TfBlockDeserializer.ScheduleBodySection? Layout)> sections = new(); if (revision || schedule.CategoryId == PlantingCategoryId) { - sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), rows)); + sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), rows, + revision ? null : schedule.BodySections.FirstOrDefault())); } else { @@ -915,13 +1094,14 @@ List> WrapHeaders(List header, double sizeMm) var header = bodySection.Header.Count == widths.Length ? bodySection.Header.ToList() : schedule.Columns.Select(column => column.Heading).ToList(); - var body = new List>(); - for (int i = 0; i < bodySection.BodyRows && body.Count < 10000; i++) - body.Add(Enumerable.Repeat("", widths.Length).ToList()); - sections.Add((header, body)); + var body = authoredRows ?? new List>(); + if (authoredRows == null) + for (int i = 0; i < bodySection.BodyRows && body.Count < 10000; i++) + body.Add(Enumerable.Repeat("", widths.Length).ToList()); + sections.Add((header, body, bodySection)); } if (sections.Count == 0) - sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), new())); + sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), new(), null)); } // The grid starts below the title area. Outer verticals run header-top to table bottom at the // outline weight when the schedule shows its outline (else the header box stands alone at the grid @@ -931,21 +1111,53 @@ List> WrapHeaders(List header, double sizeMm) // A wrapped header line after the first adds the measured extra line pitch (the planting header: // 31.8 pt for two lines against 17.3 for one). double extraHeaderLineMm = 14.55 * PtToMm; - foreach (var (header, body) in sections) + foreach (var (header, body, layout) in sections) { + bool styledBody = authoredRows != null && layout?.UniformBodyStyle is + { CapHeightPixels: 12, HorizontalAlignment: 0, VerticalAlignment: 0, Flags: 1 } bodyStyle + && string.Equals(bodyStyle.FontName, "Arial", StringComparison.OrdinalIgnoreCase) + && string.Equals(page.Owner.Font?.Name, bodyStyle.FontName, StringComparison.OrdinalIgnoreCase); + // Plain Arial at 12 cap-height pixels uses the print layout's 23-pixel row and 16.8-pixel baseline. + double rowHeight = styledBody ? 23 * pixelMm : bodyH; + double styledBaseline = 16.8 * pixelMm; + double styledInset = 3.6 * pixelMm; if (schedule.ShowHeaders) { // The header top rule is the title-area rule above, drawn where nothing stands over it. if (firstHeader && !drewTitleArea && schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); - var wrapped = revision - ? header.Select(text => new List { text }).ToList() - : WrapHeaders(header, headPt * PtToMm); - int headerLines = Math.Max(1, wrapped.Max(lines => lines.Count)); - double headerH = revision ? headH : bodyH + (headerLines - 1) * extraHeaderLineMm; + var headers = new (IReadOnlyList Lines, double? Size, TfBlockDeserializer.ScheduleTextStyle Style)[widths.Length]; + var styles = revisionHeaderStyles ?? layout?.HeaderStyles; for (int i = 0; i < widths.Length; i++) { - var lines = i < wrapped.Count ? wrapped[i] : new List { "" }; + string text = i < header.Count ? header[i] : ""; + var style = styles?.Count == widths.Length ? styles[i] : default; + double? size = ScheduleTextSize(page.Owner.Font, style); + headers[i] = (revision ? [text] : Wrap(text, widths[i], size ?? headPt * PtToMm), size, style); + } + int headerLines = Math.Max(1, headers.Max(cell => cell.Lines.Count)); + double headerH = revision ? headH : rowHeight + (headerLines - 1) * extraHeaderLineMm; + for (int i = 0; i < widths.Length; i++) + { + var (lines, size, style) = headers[i]; + if (size is double nativeSize) + { + if (revisionHeaderStyles != null) + { + // The supported Arial revision heading baseline sits 1.42 caps below the top rule. + page.DrawText(lines[0], (edges[i] + edges[i + 1]) / 2, + y - revisionHeaderCapMm * 1.42, nativeSize, PdfTextAlignment.Center); + } + else if (styledBody && headerLines == 1 && style is + { CapHeightPixels: 12, HorizontalAlignment: 1, VerticalAlignment: 8, Flags: 1 } + && string.Equals(style.FontName, "Arial", StringComparison.OrdinalIgnoreCase)) + { + page.DrawText(lines[0], (edges[i] + edges[i + 1]) / 2, + y - styledBaseline, nativeSize, PdfTextAlignment.Center); + } + else DrawCellText(lines, headerH, nativeSize, style, edges[i], edges[i + 1]); + continue; + } for (int j = 0; j < lines.Count; j++) { if (lines[j].Length == 0) continue; @@ -975,13 +1187,16 @@ List> WrapHeaders(List header, double sizeMm) string cell = i < row.Count ? row[i] : ""; if (cell.Length == 0) continue; double sizeMm = bodyPt * PtToMm; - if (revision || i == 0) - page.DrawText(cell, edges[i] + insetMm, y - bodyH / 2 - 0.35 * sizeMm, sizeMm); + int alignment = layout?.BodyAlignment is { } saved && saved.Count == widths.Length ? saved[i] : -1; + if (styledBody) + page.DrawText(cell, edges[i] + styledInset, y - styledBaseline, sizeMm); + else if (alignment == 0 || alignment != 1 && (revision || authoredRows != null || i == 0)) + page.DrawText(cell, edges[i] + insetMm, y - rowHeight / 2 - 0.35 * sizeMm, sizeMm); else - page.DrawText(cell, (edges[i] + edges[i + 1]) / 2, y - bodyH / 2 - 0.35 * sizeMm, sizeMm, + page.DrawText(cell, (edges[i] + edges[i + 1]) / 2, y - rowHeight / 2 - 0.35 * sizeMm, sizeMm, PdfTextAlignment.Center); } - y -= bodyH; + y -= rowHeight; if (schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); } @@ -1037,8 +1252,8 @@ List> WrapHeaders(List header, double sizeMm) /// style has no pen, as rvt-prt draws it), each fixed text and label at its anchor. private static void DrawTitleBlockSymbol(PdfPage page, RvtDocument document, Element sheet, string scaleText, IReadOnlyList<(double X0, double Y0, double X1, double Y1, int StyleId)> lines, - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>? texts, - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>? labels, + IReadOnlyList? texts, + IReadOnlyList? labels, double originX, double originY) { const double FeetToMillimetres = 304.8; @@ -1060,42 +1275,107 @@ private static void DrawTitleBlockSymbol(PdfPage page, RvtDocument document, Ele if (parsed?.Text is not { Length: > 0 } plain) continue; double sizeMm = parsed.Value.FontSizePoints is double points && points > 0 ? points * 25.4 / 72.0 : 2.5; - DrawTitleBlockText(page, plain, text.Ox * FeetToMillimetres - originX, - text.Oy * FeetToMillimetres - originY, sizeMm, text.Flags, text.Bx, text.By); + DrawTitleBlockText(page, plain.Split('\n'), text.Ox * FeetToMillimetres - originX, + text.Oy * FeetToMillimetres - originY, sizeMm, text.Height * FeetToMillimetres, + text.Flags, text.Bx, text.By, text.Hx, text.Hy); } } - if (labels != null) + if (labels != null && page.Owner.Font is { } font) { foreach (var label in labels) { string value = TitleBlockLabelValue(document, sheet, scaleText, label.ParamId); if (value.Length == 0) continue; value = label.Prefix + value + label.Suffix; - // A label with no decoded text type prints at its box height, as rvt-prt sizes it. - double sizeMm = label.Height * 304.8 / 1.257; - DrawTitleBlockText(page, value, label.Ox * FeetToMillimetres - originX, - label.Oy * FeetToMillimetres - originY, sizeMm, label.Flags, label.Bx, label.By); + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double sizeMm = SymbolLabelTextSize(font, height, cap); + double width = label.Width * FeetToMillimetres; + bool wrap = label.Wrap && width > 0 && page.MeasureText(value, sizeMm) > width; + var wrapped = PlanPrinter.WrapPlanNoteText(page, value, sizeMm, width, wrap); + DrawTitleBlockText(page, wrapped, label.Ox * FeetToMillimetres - originX, + label.Oy * FeetToMillimetres - originY, sizeMm, height * wrapped.Count, + label.Flags, label.Bx, label.By, label.Hx, label.Hy); } } } - private static void DrawTitleBlockText(PdfPage page, string text, double x, double y, - double sizeMm, int flags, double bx, double by) + internal static double SymbolLabelTextSize(PdfTrueTypeFont font, double frameHeight, double capHeightFeet) { - if (string.IsNullOrEmpty(text) || sizeMm <= 0) return; + // The font element stores physical cap height. Text sizes are written in half points. + double nominalSize = capHeightFeet > 0 && font.CapHeight > 0 + ? capHeightFeet * FeetToMillimetres * font.UnitsPerEm / font.CapHeight + : frameHeight * font.UnitsPerEm / (font.Ascent - font.Descent); + return Math.Round(nominalSize * 144 / 25.4, MidpointRounding.AwayFromZero) * 25.4 / 144; + } + + internal static void DrawTitleBlockText(PdfPage page, IReadOnlyList parts, double x, double y, + double sizeMm, double height, int flags, double bx, double by, double ux, double uy, bool opaque = false, + bool useArialLayout = false) + { + if (parts.Count == 0 || !(sizeMm > 0 && double.IsFinite(sizeMm)) + || !double.IsFinite(x) || !double.IsFinite(y) + || !double.IsFinite(bx) || !double.IsFinite(by) || !double.IsFinite(ux) || !double.IsFinite(uy) + || page.Owner.Font is not { } font) return; + if (!(height > 0 && double.IsFinite(height))) height = 0; var alignment = (flags & 0x80) != 0 ? PdfTextAlignment.Center : (flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; double angle = Math.Atan2(by, bx) * 180.0 / Math.PI; - string[] parts = text.Split('\n'); - for (int i = 0; i < parts.Length; i++) + double ascent = sizeMm * font.Ascent / font.UnitsPerEm; + double first = TitleBlockFirstBaseline(ascent, height, flags); + double spacing = height > 0 ? height / parts.Count : sizeMm * 1.25; + for (int i = 0; i < parts.Count; i++) { if (parts[i].Length == 0) continue; - double lineY = y - i * sizeMm * 1.25; - if (Math.Abs(angle) < 1e-6) page.DrawText(parts[i], x, lineY, sizeMm, alignment); - else page.DrawTextRotated(parts[i], x, lineY, sizeMm, angle, alignment); + double offset = first - i * spacing; + double lineX = x + ux * offset, lineY = y + uy * offset; + if (Math.Abs(angle) < 1e-6) + { + if (useArialLayout && WindowsArialLayout.TryMeasure(parts[i], sizeMm, out double layoutWidth, out double layoutAscent)) + { + double left = TextLeft(lineX, layoutWidth); + lineY += ascent - layoutAscent; + if (opaque) page.DrawRectangle(left, lineY + layoutAscent - spacing, layoutWidth, spacing, 0, 1); + page.DrawText(parts[i], left, lineY, sizeMm); + } + else + { + if (opaque) + { + double width = page.MeasureText(parts[i], sizeMm); + page.DrawRectangle(TextLeft(lineX, width), lineY + ascent - spacing, width, spacing, 0, 1); + } + page.DrawText(parts[i], lineX, lineY, sizeMm, alignment); + } + } + else page.DrawTextRotated(parts[i], lineX, lineY, sizeMm, angle, alignment); } + + double TextLeft(double anchor, double width) => alignment switch + { + PdfTextAlignment.Center => anchor - width / 2, + PdfTextAlignment.Right => anchor - width, + _ => anchor, + }; } + internal static double TitleBlockFirstBaseline(double ascent, double height, int flags) + => (flags & 0xe00) switch + { + 0x200 => -ascent, + 0x400 => height / 2 - ascent, + 0x800 => height - ascent, + _ => 0, + }; + + internal static string TitleBlockScale(IReadOnlyCollection scales, bool russian) + => scales.Count switch + { + 0 => "", + 1 => FormattableString.Invariant($" 1 : {scales.Single()}"), + _ => russian ? "Как указано" : "As indicated", + }; + /// The printed value of a title block label: the sheet number and name, the drawn/checked by, the /// print time, the view scale, or a project information field, as rvt-prt resolves them. private static string TitleBlockLabelValue(RvtDocument document, Element sheet, string scaleText, int paramId) @@ -1121,12 +1401,35 @@ static string Text(Element element, BuiltInParameter id) => private static readonly System.Collections.Concurrent.ConcurrentDictionary Logos = new(); - private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int ViewId), PdfJpegImage?> + private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int SymbolId), + IReadOnlyList<(PdfRasterImage Image, double X, double Y, double Width, double Height)>> TitleImages = new(); + + private static IReadOnlyList<(PdfRasterImage Image, double X, double Y, double Width, double Height)> + TitleBlockImages(RvtDocument document, int symbolId) + { + if (document.SourcePath is not { Length: > 0 } path) return []; + return TitleImages.GetOrAdd((path, symbolId), key => + { + var images = new List<(PdfRasterImage, double, double, double, double)>(); + foreach (var placement in RvtRaster.FindSheetImagePlacements(key.Path, key.SymbolId)) + { + var symbol = document.GetElement(placement.SymbolId); + if (symbol?.ImagePaperSize is not { } size || symbol.ImageHolderId is not int holder + || RvtRaster.FindImagePng(key.Path, holder) is not { } image) continue; + double width = size.Width * placement.ScaleX, height = size.Height * placement.ScaleY; + images.Add((image, placement.X - width / 2, placement.Y - height / 2, width, height)); + } + return images; + }); + } + + private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int ViewId), + (PdfJpegImage Image, (double Width, double Height)? Size)?> Renderings = new(); /// The JPEG a rendering view stores: the image symbol the view owns carries its type, and the type's block /// holds the image. - private static PdfJpegImage? RenderingImage(RvtDocument document, int viewId) + private static (PdfJpegImage Image, (double Width, double Height)? Size)? RenderingImage(RvtDocument document, int viewId) { if (document.SourcePath is not { Length: > 0 } path) return null; return Renderings.GetOrAdd((path, viewId), key => @@ -1136,7 +1439,16 @@ static string Text(Element element, BuiltInParameter id) => if (element.OwnerViewId != key.ViewId || element.RootClassName != "ImageSymbol") continue; if (element.TypeId <= 0) continue; var image = RvtRaster.FindJpeg(key.Path, element.TypeId); - if (image != null) return image; + if (image == null) continue; + var size = element.ImagePaperSize; + if (size is { } bounds) + { + var placement = document.Elements.FirstOrDefault(e => e.OwnerViewId == key.ViewId + && e.RootClassName == "ImageInstance" && e.TypeId == element.Id); + if (placement?.ImageInstanceScale is { } scale) + size = (bounds.Width * scale.Width, bounds.Height * scale.Height); + } + return (image, size); } return null; }); @@ -1191,7 +1503,8 @@ private static void DrawPlantingSchedule(PdfPage page, RvtDocument document, dou /// Writes the room legend: a title and one row per kind of room, a colour swatch and the name. The rows /// start at (x, y) and go down. - private static void DrawRoomLegend(PdfPage page, IEnumerable names, double x, double y) + private static void DrawRoomLegend(PdfPage page, IEnumerable names, double x, double y, + (double Width, double Height)? swatch, IReadOnlyDictionary? colors) { var seen = new List(); foreach (string name in names) @@ -1201,12 +1514,28 @@ private static void DrawRoomLegend(PdfPage page, IEnumerable names, doub seen.Add(name); } if (seen.Count == 0) return; + if (swatch is { } style) + { + double width = style.Width * FeetToMillimetres, height = style.Height * FeetToMillimetres; + // shortcut: scale text and spacing from the swatch until the legend's font and row styles are decoded. + page.DrawText("Room Legend", x, y + height * 0.92, height * 0.93); + double rowTop = y; // The stored origin is the top left of the first swatch. + foreach (string name in seen.OrderBy(name => name, StringComparer.OrdinalIgnoreCase)) + { + double bottom = rowTop - height; + page.DrawPolyline([(x, bottom), (x + width, bottom), (x + width, rowTop), (x, rowTop)], 0.15, true, + PlanPrinter.RoomFill(name, colors)); + page.DrawText(name, x + width + height / 4, bottom + height * 0.27, height * 0.67); + rowTop -= height * 4 / 3; + } + return; + } page.DrawText("Room Legend", x, y, 3.5); double row = y - 6; foreach (string name in seen) { page.DrawPolyline([(x, row), (x + 4, row), (x + 4, row + 4), (x, row + 4)], 0.15, true, - PlanPrinter.RoomFill(name)); + PlanPrinter.RoomFill(name, colors)); page.DrawText(name, x + 6, row + 0.8, 2.8); row -= 5.5; } @@ -1319,6 +1648,10 @@ internal static bool TryCropFrame(double centerXMm, double centerYMm, double sca return true; } + internal static bool CropOverlapsSheet(double frameX, double frameY, double frameWidth, double frameHeight, + double sheetWidth, double sheetHeight) => + frameX + frameWidth > 0 && frameY + frameHeight > 0 && frameX < sheetWidth && frameY < sheetHeight; + /// True when the view's decoded plane matches the crop frame's basis and origin: the collection /// projected the model with these very axes, so the crop rectangle maps onto its content. Guards the crop /// path where the collection fell back to compass axes. @@ -1334,8 +1667,7 @@ static bool Same(double[] a, double[] b) => && Math.Abs(origin[0] - crop.OriginX) + Math.Abs(origin[1] - crop.OriginY) + Math.Abs(origin[2] - crop.OriginZ) < 1e-3; } - /// True when the view is a sun, lighting or energy analysis: it prints as its shaded study, - /// not as vector massing, so a sheet viewport of it draws nothing (the reference shows no such linework). + /// True for sun, lighting and energy analysis views, whose sheets use a shaded viewport. internal static bool IsAnalysisView(Element? view) => view?.Name is string name && (name.Contains("Solar", StringComparison.OrdinalIgnoreCase) || name.Contains("Lighting", StringComparison.OrdinalIgnoreCase) @@ -1386,9 +1718,13 @@ void Grow(double x, double y) foreach (var line in contours) { Grow(line.X1, line.Y1); Grow(line.X2, line.Y2); } foreach (var plant in plants) { Grow(plant.X - plant.Radius, plant.Y - plant.Radius); Grow(plant.X + plant.Radius, plant.Y + plant.Radius); } foreach (var polygon in entourage) foreach (var point in polygon) Grow(point.X, point.Y); + if (site.PropertyLines != null) + foreach (var line in site.PropertyLines) + foreach (var point in line) Grow(point.X, point.Y); Grow(building.MinX, building.MinY); Grow(building.MaxX, building.MaxY); if (!(minX <= maxX) || !(minY <= maxY)) return site; - return new SitePrinter.SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + return new SitePrinter.SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + site.PropertyLines, site.NativePrimaryLevels); } } diff --git a/src/RvtIO/Print/SheetPrinter.cs b/src/RvtIO/Print/SheetPrinter.cs index 26d8b9bc..c51f0e9e 100644 --- a/src/RvtIO/Print/SheetPrinter.cs +++ b/src/RvtIO/Print/SheetPrinter.cs @@ -18,8 +18,7 @@ public sealed class SheetPrintOptions /// How far the linework extent may be from a standard paper size and still snap to it. public double PaperToleranceMillimetres { get; set; } = 8; - /// True writes the sheet number and name in the upper-left corner; the title block text itself is not - /// decoded. + /// True writes the sheet number and name in a corner when the sheet has no decoded text notes. public bool DrawSheetFields { get; set; } = true; } @@ -30,15 +29,13 @@ public sealed class SheetPrintOptions /// The width of the decoded linework in millimetres, 0 when nothing is drawn. /// The height of the decoded linework in millimetres. /// The number of location curves of the sheet's own elements. -/// The number of text notes of the sheet (their text is not decoded). +/// The number of text notes belonging to the sheet. public sealed record PrintableSheet(int SheetId, string? Number, string? Name, double WidthMillimetres, double HeightMillimetres, int CurveCount, int TextCount); /// -/// Prints a sheet to a PDF page from the linework the reader decodes: the location curves of the elements the sheet -/// owns (the border, the title block frame and its rules) at their sheet coordinates. Text notes are not decoded, so a -/// title block is printed as its linework with the sheet number and name written in a corner; the placed views are not -/// composed yet (see docs/printing.md). +/// Prints a sheet's decoded linework and text notes at their sheet coordinates. +/// Use to print the placed views and title block. /// public static class SheetPrinter { @@ -196,24 +193,7 @@ void Grow(double x, double y) // The text notes of the sheet, at the positions the file stores (sheet coordinates, feet). The text is real, // selectable PDF text when the document has an embedded font. - bool drewText = false; - if (pdf.Font != null) - { - foreach (var element in document.Elements) - { - if (element.OwnerViewId != sheet.Id) continue; - if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) - continue; - double x = position[0] * FeetToMillimetres + offsetX; - double y = position[1] * FeetToMillimetres + offsetY; - double height = element.TextFontSizePoints is double points && points > 0 - ? points * 25.4 / 72 : 2.5; - string[] lines = text.Split('\n'); - for (int line = 0; line < lines.Length; line++) - page.DrawText(lines[line], x, y - line * height * 1.25, height); - drewText = true; - } - } + bool drewText = pdf.Font != null && DrawSheetNotes(page, document, sheet.Id, offsetX, offsetY); // The number and name in a corner only when the sheet has no decoded text of its own (the stamp labels are // then missing and the corner identifies the page). @@ -226,6 +206,33 @@ void Grow(double x, double y) } } + internal static bool DrawSheetNotes(PdfPage page, RvtDocument document, int sheetId, double offsetX, double offsetY) + { + var nativeNotes = document.RawData.PlanNotes?.GetValueOrDefault(sheetId)?.ToDictionary(note => note.ElementId); + double X(double feet) => feet * FeetToMillimetres + offsetX; + double Y(double feet) => feet * FeetToMillimetres + offsetY; + bool drewText = false; + foreach (var element in document.Elements) + { + if (element.OwnerViewId != sheetId) continue; + if (nativeNotes?.TryGetValue(element.Id, out var note) == true + && PlanPrinter.DrawTextNote(page, document, note, X, Y)) + { + drewText = true; + continue; + } + if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) + continue; + double x = X(position[0]), y = Y(position[1]); + double size = element.TextFontSizePoints is double points && points > 0 ? points * 25.4 / 72 : 2.5; + string[] lines = text.Split('\n'); + for (int i = 0; i < lines.Length; i++) + page.DrawText(lines[i], x, y - i * size * 1.25, size); + drewText = true; + } + return drewText; + } + /// The paper that holds the extent: the standard size it matches within the tolerance, else the extent /// itself plus a small margin. private static PdfPageSize PaperFor(double width, double height, double tolerance) diff --git a/src/RvtIO/Print/SitePrinter.ContourLabels.cs b/src/RvtIO/Print/SitePrinter.ContourLabels.cs new file mode 100644 index 00000000..6e58c049 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.ContourLabels.cs @@ -0,0 +1,76 @@ +using RvtIO.Compact; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private sealed record PrintedContourLabel(double X, double Y, double Level, double Height, double HalfWidth, + double Baseline, double Angle, double Cosine, double Sine, string Text); + + private static List ContourLabels(PdfPage page, RvtDocument? document, int? viewId, + ViewCropFrame? basis, Func toX, Func toY) + { + var result = new List(); + if (viewId is not int view || page.Owner.Font is not { CapHeight: > 0 } font + || document?.RawData.SerializedFormatSettings is not { } formatting + || document.RawData.SiteContourLabels?.GetValueOrDefault(view) is not { } labels) + return result; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(view); + foreach (var label in labels) + { + if (hidden?.Contains(label.ElementId) == true || hidden?.Contains(label.SurfaceId) == true) continue; + double level = label.Position[2]; + string? text = CompactValueFormatter.Format(level, IfcNumericUnitPlan.LengthSpecName, formatting); + if (string.IsNullOrEmpty(text)) continue; + var (x, y) = Project(label.Position); + var (dx, dy) = Project(label.Direction); + if (dx == 0 && dy == 0) continue; + if (dx < 0) { dx = -dx; dy = -dy; } + double angle = Math.Atan2(dy, dx); + double height = label.TextHeightFeet * FeetToMillimetres; + double capHeight = height * font.CapHeight / font.UnitsPerEm; + double halfWidth = (page.MeasureText(text, height) + height) / 2; + result.Add(new(toX(x * FeetToMillimetres), toY(y * FeetToMillimetres), level * FeetToMillimetres, + height, halfWidth, capHeight / 2, angle, Math.Cos(angle), Math.Sin(angle), text)); + } + return result; + + (double X, double Y) Project(double[] point) => basis == null ? (point[0], point[1]) + : (point[0] * basis.Right[0] + point[1] * basis.Right[1], point[0] * basis.Up[0] + point[1] * basis.Up[1]); + } + + private static IEnumerable<(double Start, double End)> ContourSpans(double x1, double y1, double x2, double y2, + double level, List labels) + { + var gaps = new List<(double Start, double End)>(); + foreach (var label in labels) + { + if (Math.Abs(level - label.Level) > 1e-6) continue; + var (ax, ay) = InLabel(x1, y1); + var (bx, by) = InLabel(x2, y2); + if (!ElevationPrinter.ClipSegment(ax, ay, bx, by, + -label.HalfWidth, -label.Height / 2, label.HalfWidth, label.Height / 2, + out double sx, out double sy, out double ex, out double ey)) continue; + bool horizontal = Math.Abs(bx - ax) >= Math.Abs(by - ay); + gaps.Add(horizontal ? ((sx - ax) / (bx - ax), (ex - ax) / (bx - ax)) + : ((sy - ay) / (by - ay), (ey - ay) / (by - ay))); + + (double X, double Y) InLabel(double x, double y) + { + x -= label.X; + y -= label.Y; + return (x * label.Cosine + y * label.Sine, -x * label.Sine + y * label.Cosine); + } + } + double start = 0; + foreach (var gap in gaps.OrderBy(gap => gap.Start)) + { + if (gap.Start > start) yield return (start, gap.Start); + start = Math.Max(start, gap.End); + } + if (start < 1) yield return (start, 1); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Equipment.cs b/src/RvtIO/Print/SitePrinter.Equipment.cs new file mode 100644 index 00000000..42f6c0da --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Equipment.cs @@ -0,0 +1,87 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private static PlanFixtureProjection? CollectEquipment(RvtDocument document, int viewId, + double bottom, double cut, IReadOnlySet? hidden, out HashSet shadowCasters) + { + shadowCasters = []; + int? detail = document.GetElement(viewId)?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int?; + if (detail is not (1 or 2)) return null; + + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + var lines = new List(); + var masks = new List>(); + foreach (var element in document.Elements) + { + if (element.CategoryId is not ((int)BuiltInCategory.OST_ElectricalEquipment or (int)BuiltInCategory.OST_Site) + || element.IsDiscovered || element.SerializedUnplacedOwnerId is > 0 + || element.NativeIsSymbol == true || element.RootClassIs("FamilySymbol") + || element.OwnerViewId is > 0 && element.OwnerViewId != viewId + || hidden?.Contains(element.Id) == true || hiddenCategories?.Contains(element.CategoryId.Value) == true + || element.BoundingBox is not { Length: 6 } box || !(box[2] >= bottom && box[5] <= cut) + || element.PlacedPlanFixtureGraphics is not { } graphics) + continue; + + var projection = detail == 1 ? graphics.CoarseProjection : graphics.MediumProjection; + if (projection == null) continue; + var visibleLines = projection.Lines.Where(line => + document.RawData.GraphicsStylePens?.TryGetValue(line.StyleId, out var style) != true + || hiddenCategories?.Contains(style.CategoryId) != true).ToArray(); + if (visibleLines.Length == 0) continue; + lines.AddRange(visibleLines); + masks.AddRange(projection.Masks); + if (element.CategoryId == (int)BuiltInCategory.OST_Site) shadowCasters.Add(element.Id); + } + return lines.Count == 0 ? null : new(lines, masks); + } + + private static void DrawEquipment(PdfPage page, RvtDocument document, SiteGraphics graphics, ViewCropFrame? basis, + double scale, Func toX, Func toY) + { + var equipment = graphics.Equipment!; + var masks = new List>(); + foreach (var mask in equipment.Masks) + { + var ring = mask.Select(point => + { + var (x, y) = InView(point); + return (toX(x), toY(y)); + }).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (!double.IsFinite(area) || Math.Abs(area) < 1e-9) continue; + if (area < 0) ring.Reverse(); + masks.Add(ring); + } + if (masks.Count > 0) + { + page.FillPolygonUnion(masks, 1); + // The mask hides contours behind the symbol. Cast shadows can still cross it. + if (graphics.GroundShadows.Count > 0) + { + page.BeginPolygonClip(masks, evenOdd: false); + page.FillPolygonUnion(graphics.GroundShadows.Select(ring => ring.Select(p => (toX(p.X), toY(p.Y))).ToList()), + graphics.ShadowGray); + page.EndClip(); + } + } + + var lines = equipment.Lines.Select(line => + { + var (ax, ay) = InView(line.Start); + var (bx, by) = InView(line.End); + return (ax, ay, bx, by, line.StyleId); + }).ToList(); + PlanPrinter.DrawFixtureLines(page, document, lines, scale, 0.1, toX, toY, null); + + (double X, double Y) InView(double[] point) => basis == null + ? (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres) + : ((point[0] * basis.Right[0] + point[1] * basis.Right[1]) * FeetToMillimetres, + (point[0] * basis.Up[0] + point[1] * basis.Up[1]) * FeetToMillimetres); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Planting.cs b/src/RvtIO/Print/SitePrinter.Planting.cs new file mode 100644 index 00000000..6f0c6ecc --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Planting.cs @@ -0,0 +1,45 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + // The shared stock RPC plan symbol, measured in model axes on the Revit export. + private static readonly double[] RpcSpokeAngles = + [15, 30.75, 61, 71.75, 83.25, 104.75, 110, 160.5, 184.25, 190.25, 225, 265.75, 275, 302.75, 329.75, 342.25]; + + private static double? RpcPlanRadius(RvtDocument document, Element element) + { + var type = document.GetElement(element.TypeId); + if (type?.LookupParameter(BuiltInParameter.RENDER_RPC_FILENAME)?.Value is not string { Length: > 0 }) + return null; + var height = element.LookupParameter(BuiltInParameter.RENDER_PLANT_HEIGHT)?.Value + ?? type.LookupParameter(BuiltInParameter.RENDER_PLANT_HEIGHT)?.Value; + // The common plan mark scales with the saved RPC height, independently of the mesh bounds. + return height is double feet && feet > 0 && double.IsFinite(feet) ? feet * 0.275 * FeetToMillimetres : null; + } + + private static void DrawRpcPlant(PdfPage page, double x, double y, double radius, ViewCropFrame? basis, + double width, PdfColor color) + { + const int perimeterSegments = 64; + var previous = (X: x + radius, Y: y); + for (int i = 1; i <= perimeterSegments; i++) + { + double angle = i * (2 * Math.PI / perimeterSegments); + var point = (X: x + Math.Cos(angle) * radius, Y: y + Math.Sin(angle) * radius); + page.DrawLine(previous.X, previous.Y, point.X, point.Y, width, color); + previous = point; + } + foreach (double angle in RpcSpokeAngles) + { + double radians = angle * Math.PI / 180; + double dx = Math.Cos(radians), dy = Math.Sin(radians); + double projectedX = basis == null ? dx : dx * basis.Right[0] + dy * basis.Right[1]; + double projectedY = basis == null ? dy : dx * basis.Up[0] + dy * basis.Up[1]; + page.DrawLine(x, y, x + projectedX * radius, y + projectedY * radius, width, color); + } + } +} diff --git a/src/RvtIO/Print/SitePrinter.PropertyTags.cs b/src/RvtIO/Print/SitePrinter.PropertyTags.cs new file mode 100644 index 00000000..dc704e62 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.PropertyTags.cs @@ -0,0 +1,97 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Compact; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal static void DrawPropertyTags(PdfPage page, RvtDocument document, int viewId, ViewCropFrame? basis, + SiteContent site, double scale, double originX, double originY) + { + var raw = document.RawData; + // shortcut: quadrant bearings in degrees, minutes and seconds using the resolved active location. + if (raw.PropertyBearingFormat != (1, 1) || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } shared + || raw.SitePropertyTags?.GetValueOrDefault(viewId) is not { } tags + || raw.SitePropertyTagStyles is not { } styles + || raw.SerializedFormatSettings is not { } formatting || page.Owner.Font is not { } font) return; + + var hidden = raw.ViewHiddenElements?.GetValueOrDefault(viewId); + // A tag follows its boundary: no tag is left standing where the view hides the lines. + var hiddenCategories = raw.ViewHiddenCategories?.GetValueOrDefault(viewId); + if (PropertyLineHidden(hiddenCategories)) return; + bool russian = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + foreach (var tag in tags) + { + if (hidden?.Contains(tag.ElementId) == true || !styles.TryGetValue(tag.SymbolId, out var labels) + || document.GetElement(tag.ElementId) is not { SitePropertyCurve: { Count: >= 2 } curve } segment + || segment.CategoryId is int category && hiddenCategories?.Contains(category) == true) + continue; + var a = curve[0]; + var b = curve[^1]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double distance = Math.Sqrt(dx * dx + dy * dy); + if (!(distance > 0) || !double.IsFinite(distance)) continue; + + double east = dx * shared[0] + dy * shared[3], north = dx * shared[1] + dy * shared[4]; + var (ns, bearing, ew) = PropertyBearing(east, north, russian); + var tangent = segment.SitePropertyArcCenter is { } center + ? (X: center.Y - tag.Y, Y: tag.X - center.X) : (X: dx, Y: dy); + if (curve.Count > 2 && segment.SitePropertyArcCenter == null) continue; + var (tx, ty) = InView(tangent.X, tangent.Y); + if (tx == 0 && ty == 0) continue; + if (tx < 0 || (tx == 0 && ty < 0)) { tx = -tx; ty = -ty; } + double angle = Math.Atan2(ty, tx), cos = Math.Cos(angle), sin = Math.Sin(angle); + + var (x, y) = InView(tag.X, tag.Y); + double hx = originX + (x * FeetToMillimetres - site.MinX) / scale; + double hy = originY + (y * FeetToMillimetres - site.MinY) / scale; + foreach (var (label, fontPoints) in labels) + { + string? value = (BuiltInParameter)label.ParamId switch + { + BuiltInParameter.PROPERTY_SEGMENT_N_S => ns, + BuiltInParameter.PROPERTY_SEGMENT_BEARING => bearing, + BuiltInParameter.PROPERTY_SEGMENT_E_W => ew, + BuiltInParameter.PROPERTY_SEGMENT_DISTANCE => + PropertyDistance(distance, label.SingleParameterFormat, formatting, russian), + _ => null, + }; + if (string.IsNullOrEmpty(value)) continue; + var layout = PlanPrinter.AnnotationLabelLayout(font, label, fontPoints, 0, 0); + double px = hx + layout.X * cos - layout.Baseline * sin; + double py = hy + layout.X * sin + layout.Baseline * cos; + page.DrawTextRotated(label.Prefix + value + label.Suffix, px, py, + layout.Size, angle * 180 / Math.PI, layout.Alignment); + } + } + + (double X, double Y) InView(double x, double y) => basis == null ? (x, y) + : (x * basis.Right[0] + y * basis.Right[1], x * basis.Up[0] + y * basis.Up[1]); + } + + internal static (string NorthSouth, string Bearing, string EastWest) PropertyBearing( + double east, double north, bool russian) + { + string ns = north < 0 ? (russian ? "Ю" : "S") : (russian ? "С" : "N"); + string ew = east < 0 ? (russian ? "З" : "W") : (russian ? "В" : "E"); + int seconds = (int)Math.Round(Math.Atan2(Math.Abs(east), Math.Abs(north)) * (648000 / Math.PI), + MidpointRounding.AwayFromZero); + return (ns, FormattableString.Invariant($"{seconds / 3600}° {seconds / 60 % 60:00}' {seconds % 60:00}\""), ew); + } + + private static string? PropertyDistance(double feet, TfBlockDeserializer.UnitFormatOption? option, + CompactFormatSettings formatting, bool russian) + { + if (option is not { UseDefault: 0 }) return null; + if (russian && option.Symbol == "autodesk.unit.symbol:footSingleQuote-1.0.1" + && option.Unit == "autodesk.unit.unit:feet-1.0.1") + return CompactValueFormatter.Format(feet, option with { Symbol = "" }, formatting) is { } value + ? value + "фут" : null; + return CompactValueFormatter.Format(feet, option, formatting); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Roof.cs b/src/RvtIO/Print/SitePrinter.Roof.cs new file mode 100644 index 00000000..1eb3c521 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Roof.cs @@ -0,0 +1,231 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal sealed record SiteGraphics( + IReadOnlyList Surfaces, + IReadOnlyList> GroundShadows, + double ShadowGray, + PlanFixtureProjection? Equipment); + internal sealed record SiteSurface(List> Rings, FillHatch.ModelGrid? Grid, + IReadOnlyList>? Glazing = null, + IReadOnlyList>? Shadows = null, + IReadOnlyList>? Visible = null, + BuiltInCategory Category = BuiltInCategory.OST_Roofs, + int RailId = 0); + + internal static SiteGraphics? CollectOpaqueGraphics(RvtDocument document, int viewId, ViewCropFrame? basis) + { + if (PlanPrinter.GetPlanRange(document, -1, viewId) is not { } range) return null; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + bool showPatterns = document.RawData.OpaqueViewsWithSurfacePatterns?.Contains(viewId) == true; + var roofWindows = document.Elements.Where(window => + window.CategoryId == (int)BuiltInCategory.OST_Windows && !window.IsDiscovered + && window.NativeIsSymbol != true && window.SerializedUnplacedOwnerId is not > 0 + && !window.RootClassIs("FamilySymbol") && window.SerializedHostId is > 0 + && hidden?.Contains(window.Id) != true + && hiddenCategories?.Contains((int)BuiltInCategory.OST_Windows) != true + && window.Geometry is { Faces.Count: > 0 }) + .ToLookup(window => window.SerializedHostId!.Value); + var surfaces = new List<(double Height, GeoFace Face, SiteSurface Surface)>(); + var clippedFaces = new HashSet(); + var addedCasters = new Dictionary>(); + var opaquePanes = new List(); + foreach (var element in document.Elements) + { + if (element.CategoryId is not ((int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Stairs + or (int)BuiltInCategory.OST_Floors + or (int)BuiltInCategory.OST_RailingTopRail) + || element.IsDiscovered || hidden?.Contains(element.Id) == true + || element.Geometry is not { Faces.Count: > 0 } geometry) + continue; + var category = (BuiltInCategory)element.CategoryId.Value; + bool horizontal = category is BuiltInCategory.OST_Stairs or BuiltInCategory.OST_Floors; + bool rail = category == BuiltInCategory.OST_RailingTopRail; + if (horizontal && (element.NativeIsSymbol == true || element.SerializedUnplacedOwnerId is > 0 + || !element.RootClassIs(category == BuiltInCategory.OST_Stairs ? "StairsElement" : "Floor") + || hiddenCategories?.Contains((int)category) == true)) + continue; + if (rail && !VisibleTopRail(element)) continue; + var railFaces = rail ? new List() : null; + List>? glazing = null; + foreach (var face in geometry.Faces) + { + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } outer || !InRange(outer) + || face.InnerVertices?.Any(hole => hole.Any(p => !Valid(p))) == true) continue; + if (rail) + { + if (!face.PlaneSurface || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + || document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is > 0) continue; + railFaces!.Add(face); + } + if (face.Normal is not { Length: 3 } normal || !(normal[2] > (rail ? 1e-9 : 0))) continue; + if (horizontal && (!face.PlaneSurface || outer.Any(point => Math.Abs(point[2] - outer[0][2]) > 1e-8) + || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 })) continue; + var rings = Rings(face); + if (rings.Count == 0) continue; + if (category == BuiltInCategory.OST_Roofs && rings.Count > 1) + glazing ??= CollectSkylights(element.Id); + if (horizontal || rail) clippedFaces.Add(face); + surfaces.Add((outer.Average(p => p[2]), face, new SiteSurface(rings, + showPatterns && category == BuiltInCategory.OST_Roofs + ? FillHatch.ProjectModelGrid(document, face, InView) : null, + rings.Count > 1 && glazing is { Count: > 0 } ? glazing : null, + Category: category, RailId: rail ? element.Id : 0))); + } + if (railFaces is { Count: > 0 }) addedCasters.Add(element.Id, railFaces); + } + + var equipment = CollectEquipment(document, viewId, range.Bottom, range.Cut, hidden, out var equipmentCasters); + var surfaceFaces = surfaces.Select(entry => entry.Face).ToHashSet(); + var (shadows, gray) = CollectShadows(document, viewId, basis, range.Cut, hidden, equipmentCasters, + addedCasters, opaquePanes, surfaceFaces, clippedFaces, out var surfaceShadows, out var visibility); + return surfaces.Count == 0 && shadows.Count == 0 && equipment == null ? null + : new SiteGraphics(surfaces.OrderBy(entry => entry.Surface.Category != BuiltInCategory.OST_Roofs) + .ThenBy(entry => entry.Height).Select(entry => + entry.Surface with + { + Shadows = surfaceShadows.GetValueOrDefault(entry.Face), + Visible = visibility.GetValueOrDefault(entry.Face), + }).ToList(), + shadows, gray, equipment); + + bool VisibleTopRail(Element rail) => + rail is { RootClassName: "TopRail", NativeIsSymbol: not true, SerializedUnplacedOwnerId: not > 0, + SerializedOwningElementId: > 0 and int ownerId } + && hiddenCategories?.Contains((int)BuiltInCategory.OST_RailingTopRail) != true + && hidden?.Contains(ownerId) != true + && document.GetElement(ownerId) is { RootClassName: "BaseRailing", CategoryId: int ownerCategory, + IsDiscovered: false, NativeIsSymbol: not true, SerializedUnplacedOwnerId: not > 0 } + && hiddenCategories?.Contains(ownerCategory) != true; + + List> CollectSkylights(int hostId) + { + var panes = new List>(); + foreach (var window in roofWindows[hostId]) + { + var frameFaces = new List(); + foreach (var face in window.Geometry!.Faces) + { + if (!face.PlaneSurface || face.CurvedSurface + || face.OuterVertices is not { Count: >= 3 } vertices || !InRange(vertices)) continue; + var material = document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1); + if (material?.SerializedMaterialTransparency == 0) + frameFaces.Add(face); + else if (material?.SerializedMaterialTransparency is > 0 and <= 1 + && face.Normal is [_, _, > 0] + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && Project(vertices, true) is { } pane) + { + panes.Add(pane); + opaquePanes.Add(face); + } + } + if (frameFaces.Count > 0) addedCasters.Add(window.Id, frameFaces); + } + return panes; + } + + static bool Valid(double[] point) => point.Length == 3 && point.All(double.IsFinite); + bool InRange(List vertices) => + vertices.All(p => Valid(p) && p[2] >= range.Bottom - 1e-9 && p[2] <= range.Cut + 1e-9); + + (double X, double Y) InView(double[] point) => basis == null + ? (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres) + : ((point[0] * basis.Right[0] + point[1] * basis.Right[1]) * FeetToMillimetres, + (point[0] * basis.Up[0] + point[1] * basis.Up[1]) * FeetToMillimetres); + + List> Rings(GeoFace face) + { + var outer = Project(face.OuterVertices!, true); + if (outer == null) return []; + var result = new List> { outer }; + foreach (var hole in face.InnerVertices ?? []) + if (Project(hole, false) is { } ring) result.Add(ring); + return result; + } + + List<(double X, double Y)>? Project(List vertices, bool exterior) + { + var ring = vertices.Select(InView).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (!double.IsFinite(area) || Math.Abs(area) < 1e-6) return null; + if ((area > 0) != exterior) ring.Reverse(); + return ring; + } + } + + internal static void DrawSurfaces(PdfPage page, RvtDocument document, SiteGraphics graphics, SiteContent site, + double scale, double originX, double originY) + { + int printedScale = (int)Math.Round(scale); + double roofPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Roofs, false, + printedScale, out double width) ? width : 0.1; + double stairPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Stairs, false, + printedScale, out width) ? width : 0.1; + double floorPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Floors, false, + printedScale, out width) ? width : 0.1; + double railPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_RailingTopRail, false, + printedScale, out width) ? width : stairPen; + foreach (var surface in graphics.Surfaces) + { + if (surface.Visible is { Count: 0 }) continue; + double pen = surface.Category switch + { + BuiltInCategory.OST_Stairs => stairPen, + BuiltInCategory.OST_Floors => floorPen, + _ => roofPen, + }; + var projected = surface.Rings.Select(OnPage).ToList(); + if (surface.Visible is { } visible) page.BeginPolygonClip(visible.Select(OnPage), evenOdd: false); + page.FillPolygonUnion(projected, 1); + if (surface.Shadows is { Count: > 0 } shadows) + { + page.BeginPolygonClip(projected); + page.FillPolygonUnion(shadows.Select(OnPage), graphics.ShadowGray); + page.EndClip(); + } + if (surface.Grid is { } grid) + page.FillWithParallelLines(projected, grid.Spacing / scale, grid.Angle, + originX + (grid.X - site.MinX) / scale, originY + (grid.Y - site.MinY) / scale, pen); + if (surface.Glazing is { Count: > 0 } glazing) + { + // The hidden-line pane covers the view through the opening. Keep the roof and its + // pattern above panes that project beyond the opening's perimeter. + page.BeginPolygonClip(projected.Skip(1)); + page.FillPolygonUnion(glazing.Select(OnPage), 1); + page.EndClip(); + } + if (surface.RailId == 0) + foreach (var ring in projected) page.DrawPolyline(ring, pen, true); + if (surface.Visible != null) page.EndClip(); + } + foreach (var rail in graphics.Surfaces.Where(surface => surface.RailId > 0).GroupBy(surface => surface.RailId)) + { + var visible = rail.SelectMany(surface => surface.Visible ?? surface.Rings).ToList(); + if (visible.Count == 0) continue; + bool clipped = rail.Any(surface => surface.Visible != null); + if (clipped) page.BeginPolygonClip(visible.Select(OnPage), evenOdd: false); + var outlines = ElevationPrinter.OutlineJoinedRings(rail.SelectMany(surface => surface.Rings).ToList(), + (int)BuiltInCategory.OST_RailingTopRail); + foreach (var edge in outlines) + { + var (x1, y1) = PagePoint((edge.X1, edge.Y1)); + var (x2, y2) = PagePoint((edge.X2, edge.Y2)); + page.DrawLine(x1, y1, x2, y2, railPen); + } + if (clipped) page.EndClip(); + } + + List<(double X, double Y)> OnPage(List<(double X, double Y)> ring) => ring.Select(PagePoint).ToList(); + (double X, double Y) PagePoint((double X, double Y) point) => + (originX + (point.X - site.MinX) / scale, originY + (point.Y - site.MinY) / scale); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Shadows.cs b/src/RvtIO/Print/SitePrinter.Shadows.cs new file mode 100644 index 00000000..3cf279a5 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Shadows.cs @@ -0,0 +1,164 @@ +using RvtIO.BuiltIns; +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private static (List> Rings, double Gray) CollectShadows( + RvtDocument document, int viewId, ViewCropFrame? basis, double cut, IReadOnlySet? hidden, + IReadOnlySet equipmentCasters, IReadOnlyDictionary> addedCasters, + IReadOnlyList opaquePanes, IReadOnlySet surfaceFaces, IReadOnlySet clippedFaces, + out Dictionary>> surfaceShadows, + out Dictionary>> visibility) + { + surfaceShadows = []; + visibility = []; + double ground = double.NegativeInfinity, rightShift = 0, upShift = 0, gray = 1; + if (document.RawData.ViewGroundShadows?.GetValueOrDefault(viewId) is { GroundLevel: > 0, Intensity: > 0 } sun + && document.GetElement(sun.GroundLevel)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value + is double level && double.IsFinite(level)) + { + double dx = Math.Sin(sun.Azimuth) / Math.Tan(sun.Altitude); + double dy = -Math.Cos(sun.Azimuth) / Math.Tan(sun.Altitude); + if (double.IsFinite(dx) && double.IsFinite(dy)) + (ground, rightShift, upShift, gray) = (level, dx, dy, 1 - sun.Intensity / 100d); + } + bool castShadows = double.IsFinite(ground); + if (!castShadows && clippedFaces.Count == 0) return ([], 1); + double[] right = basis?.Right ?? [1, 0, 0], up = basis?.Up ?? [0, 1, 0]; + double[] down = [0, 0, -1]; + var shadows = new ElevationPrinter.ElevationShadows(right, up, down, rightShift, upShift, gray); + var sourceFaces = new Dictionary, GeoFace>(); + var paneCovers = new List(); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + double minX = double.PositiveInfinity, minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity; + + foreach (var element in document.Elements) + { + bool equipment = equipmentCasters.Contains(element.Id); + var added = addedCasters.GetValueOrDefault(element.Id); + if (!equipment && added == null + && element.CategoryId is not ((int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Stairs + or (int)BuiltInCategory.OST_Topography or (int)BuiltInCategory.OST_BuildingPad) + || element.IsDiscovered || element.SerializedUnplacedOwnerId is > 0 + || element.NativeIsSymbol == true || element.RootClassIs("FamilySymbol") + || element.CategoryId is int category + && category is ((int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_Floors) + && hiddenCategories?.Contains(category) == true + || hidden?.Contains(element.Id) == true || element.Geometry is not { Faces.Count: > 0 } geometry) + continue; + foreach (var face in added ?? geometry.Faces) + { + // shortcut: use planar faces wholly below the cut, pending cut-solid reconstruction for shadows. + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } outer + || outer.Any(point => !Valid(point) || point[2] > cut) + || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + || face.InnerVertices?.Any(ring => ring.Count < 3 || ring.Any(point => !Valid(point))) == true) + continue; + + bool aboveGround = outer.Any(point => point[2] > ground); + if (!aboveGround && clippedFaces.Count == 0) continue; + if (castShadows && aboveGround) + { + shadows.AddCaster(face, outer.Select(Millimetres).ToList()); + foreach (var vertex in outer) + { + var (x, y) = InView(vertex); + double height = vertex[2] - ground; + x -= height * rightShift; + y -= height * upShift; + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } + } + if (equipment || added != null && element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail + || face.Normal is not { Length: 3 } normal || !(normal[2] > 1e-9)) continue; + var source = surfaceFaces.Contains(face) ? face : null; + bool receivesShadow = castShadows && (aboveGround + || source != null && outer.All(point => point[2] >= ground)); + AddReceiverFacets(outer, face, source, receivesShadow); + } + } + + // The site view paints the transparent pane white. Include that cover when clipping the + // projected model below it, while retaining the existing shadow geometry behind the pane. + foreach (var pane in opaquePanes) + AddReceiverFacets(pane.OuterVertices!, pane, null, receivesShadow: false, paneCover: true); + + var targets = sourceFaces.Where(entry => clippedFaces.Contains(entry.Value)).Select(entry => entry.Key).ToHashSet(); + var clipped = shadows.ClippedReceivers(targets, paneCovers); + foreach (var source in clipped.Keys.Select(facet => sourceFaces[facet]).Distinct()) + visibility.Add(source, []); + foreach (var target in targets) + if (visibility.TryGetValue(sourceFaces[target], out var visible)) + visible.AddRange(clipped.TryGetValue(target, out var parts) ? parts : [target]); + + if (minX < maxX && minY < maxY) + { + var plane = new GeoFace { Normal = [0, 0, 1] }; + AddReceiver([World(minX, minY), World(maxX, minY), World(maxX, maxY), World(minX, maxY)], plane); + } + + var projected = castShadows ? shadows.Project(double.NegativeInfinity) : null; + if (projected != null) + foreach (var (facet, source) in sourceFaces) + { + if (!projected.TryGetValue(facet, out var shadow)) continue; + if (!surfaceShadows.TryGetValue(source, out var rings)) surfaceShadows.Add(source, rings = []); + rings.AddRange(shadow.Rings); + } + return (projected?.Values.SelectMany(shadow => shadow.Rings).ToList() ?? [], gray); + + void AddReceiverFacets(List outer, GeoFace face, GeoFace? source, bool receivesShadow, bool paneCover = false) + { + if (outer.Count == 3 && face.InnerVertices is not { Count: > 0 }) + { + AddReceiver(outer, face, source, receivesShadow, paneCover); + return; + } + var vertices = outer.ToList(); + var loops = new List { Enumerable.Range(0, outer.Count).ToArray() }; + foreach (var inner in face.InnerVertices ?? []) + { + loops.Add(Enumerable.Range(vertices.Count, inner.Count).ToArray()); + vertices.AddRange(inner); + } + var plane = new GeoFace { Normal = face.Normal }; + var outerFlags = new bool[loops.Count]; + outerFlags[0] = true; + foreach (var (a, b, c) in GeTess.TriangulateProfile(vertices.Select(InView).ToArray(), loops, outerFlags)) + AddReceiver([vertices[a], vertices[b], vertices[c]], plane, source, receivesShadow, paneCover); + } + + void AddReceiver(List vertices, GeoFace face, GeoFace? source = null, bool receivesShadow = true, + bool paneCover = false) + { + var points = vertices.Select(InView).Select(point => (point.X * FeetToMillimetres, + point.Y * FeetToMillimetres)).ToList(); + if (Math.Abs(PlanPrinter.SignedArea(points)) <= 1e-6) return; + var corners = vertices.Select(Millimetres).ToList(); + if (paneCover) + { + var cover = ElevationPrinter.ElevationShadows.CreateVisibleFacet(right, up, down, points, face, corners); + if (cover != null) paneCovers.Add(cover); + return; + } + shadows.AddVisibleFacet(points, face, corners, receivesShadow: receivesShadow); + if (source != null) sourceFaces.Add(points, source); + } + + (double X, double Y) InView(double[] point) => + (point[0] * right[0] + point[1] * right[1], point[0] * up[0] + point[1] * up[1]); + + double[] World(double x, double y) => [x * right[0] + y * up[0], x * right[1] + y * up[1], ground]; + + static double[] Millimetres(double[] vertex) => + [vertex[0] * FeetToMillimetres, vertex[1] * FeetToMillimetres, vertex[2] * FeetToMillimetres]; + + static bool Valid(double[] vertex) => vertex.Length == 3 && vertex.All(double.IsFinite); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Tags.cs b/src/RvtIO/Print/SitePrinter.Tags.cs new file mode 100644 index 00000000..0c0946a0 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Tags.cs @@ -0,0 +1,83 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal sealed record PlantingAnnotation(string Mark, RevitFileInfo.PlanOpeningTagStyle Style, + (double X, double Y) Head, (double X, double Y) Elbow, (double X, double Y) End); + + internal static IReadOnlyList CollectTags(RvtDocument document, int viewId, ViewCropFrame? basis) + { + if (document.RawData.SitePlantingTags?.GetValueOrDefault(viewId) is not { } tags + || document.RawData.PlanOpeningTagStyles is not { } styles) return []; + var result = new List(); + foreach (var tag in tags) + { + if (!styles.TryGetValue(tag.SymbolId, out var style) || style.Lines.Count == 0 + || !IsLocalPlantingTag(document.GetElement(tag.ElementId), style.Label.ParamId, out string mark)) continue; + result.Add(new(mark, style, ToView(tag.X, tag.Y), ToView(tag.Elbow.X, tag.Elbow.Y), + ToView(tag.End.X, tag.End.Y))); + } + return result; + + (double X, double Y) ToView(double x, double y) => basis == null + ? (x * FeetToMillimetres, y * FeetToMillimetres) + : ((x * basis.Right[0] + y * basis.Right[1]) * FeetToMillimetres, + (x * basis.Up[0] + y * basis.Up[1]) * FeetToMillimetres); + + bool IsLocalPlantingTag(Element? plant, int param, out string mark) + { + mark = ""; + if (plant == null || param != (int)BuiltInParameter.ALL_MODEL_TYPE_MARK) return false; + mark = PlantingTypeOf(document, plant).Mark; + return mark.Length > 0; + } + } + + internal static void DrawOutlineAnnotations(PdfPage page, RvtDocument document, + IReadOnlyList markers, ViewCropFrame? basis, SiteContent site, + double scale, double originX, double originY) + { + foreach (var (transform, lines, arcs) in markers) + { + if (CircularAnnotations.ProjectTransform(transform, basis?.Right, basis?.Up) is not { } marker) continue; + double x = originX + (marker.X - site.MinX) / scale; + double y = originY + (marker.Y - site.MinY) / scale; + double unit = FeetToMillimetres * marker.Factor / scale; + foreach (var line in lines) + page.DrawLine(x + line.X0 * unit, y + line.Y0 * unit, x + line.X1 * unit, y + line.Y1 * unit, + Width(line.StyleId)); + foreach (var arc in arcs) + page.DrawArc(x + arc.X * unit, y + arc.Y * unit, arc.Radius * unit, arc.Start, arc.End, + Width(arc.StyleId)); + } + + double Width(int id) => document.RawData.GraphicsStylePens?.GetValueOrDefault(id) is { } style + && PenWidths.TryAnnotationWidth(document, style.PenNumber, out double width) ? width : 0.1; + } + + internal static void DrawTags(PdfPage page, RvtDocument document, IReadOnlyList tags, + SiteContent site, double scale, double originX, double originY) + { + if (page.Owner.Font == null || tags.Count == 0) return; + double pen = PlanPrinter.PlanAnnotationWidth(document, (int)BuiltInCategory.OST_PlantingTags, 0.1); + foreach (var (mark, style, head, elbow, end) in tags) + { + var (hx, hy) = PagePoint(head); + var (ex, ey) = PagePoint(elbow); + var (tx, ty) = PagePoint(end); + double edge = ex < hx ? style.Lines.Min(line => Math.Min(line.X0, line.X1)) + : style.Lines.Max(line => Math.Max(line.X0, line.X1)); + double start = hx + edge * FeetToMillimetres; + page.DrawLine(start, hy, ex, ey, pen); + page.DrawLine(ex, ey, tx, ty, pen); + PlanPrinter.DrawTagSymbol(page, style, mark, hx, hy, pen); + } + + (double X, double Y) PagePoint((double X, double Y) point) => + (originX + (point.X - site.MinX) / scale, originY + (point.Y - site.MinY) / scale); + } +} diff --git a/src/RvtIO/Print/SitePrinter.cs b/src/RvtIO/Print/SitePrinter.cs index eaf0a49f..e038468b 100644 --- a/src/RvtIO/Print/SitePrinter.cs +++ b/src/RvtIO/Print/SitePrinter.cs @@ -5,22 +5,23 @@ namespace RvtIO.Print; /// -/// Prints a site plan: the topography of the model (the edges of its faces seen from above) and the planting of the -/// site (a circle with four spokes at each plant). A site view is not the plan of a level, so it is drawn from the site -/// entities rather than from walls and rooms. +/// Prints the site terrain, property boundaries and symbols for placed planting and entourage. /// -public static class SitePrinter +public static partial class SitePrinter { private const double FeetToMillimetres = 304.8; - /// The projected site: the topography outlines, the plants and the extents they span, in millimetres. - /// Each plant carries its schedule key: the type mark (T1, T2, ...) for its tag, empty when unknown. + internal sealed record SitePlant(double X, double Y, double Radius, string Type, string Mark, bool Rpc = false); + + /// The projected site: the topography outlines, the plants and the extents they span, in millimetres. internal sealed record SiteContent( List> Topography, List<(double X1, double Y1, double X2, double Y2, double Z)> Contours, - List<(double X, double Y, double Radius, string Type, string Mark)> Plants, + List Plants, List> Entourage, - double MinX, double MinY, double MaxX, double MaxY); + double MinX, double MinY, double MaxX, double MaxY, + IReadOnlyList>? PropertyLines = null, + IReadOnlySet? NativePrimaryLevels = null); /// The same site seen in a rotated view: every point is projected on the view's own axes /// ( across the sheet, up the sheet), so a site plan whose crop @@ -41,10 +42,12 @@ internal static SiteContent InViewBasis(SiteContent site, double[] right, double var plants = site.Plants.Select(plant => { var centre = Map(plant.X, plant.Y); - return (centre.X, centre.Y, plant.Radius, plant.Type, plant.Mark); + return plant with { X = centre.X, Y = centre.Y }; }).ToList(); var entourage = site.Entourage .Select(polygon => polygon.Select(point => Map(point.X, point.Y)).ToList()).ToList(); + var propertyLines = site.PropertyLines? + .Select(line => line.Select(point => Map(point.X, point.Y)).ToList()).ToList(); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; void Grow(double x, double y) { @@ -57,14 +60,23 @@ void Grow(double x, double y) foreach (var plant in plants) Grow(plant.X, plant.Y); foreach (var polygon in entourage) foreach (var point in polygon) Grow(point.X, point.Y); + if (propertyLines != null) + foreach (var line in propertyLines) + foreach (var point in line) Grow(point.X, point.Y); if (minX > maxX) return site; - return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + propertyLines, site.NativePrimaryLevels); } - /// Projects the topography and the planting of the document on the plan. Null when the model has neither. + /// Projects the topography, planting and property boundaries of the document on the plan. /// - internal static SiteContent? Collect(RvtDocument document) + internal static SiteContent? Collect(RvtDocument document, int? viewId = null) { + var hidden = viewId is int view ? document.RawData.ViewHiddenElements?.GetValueOrDefault(view) : null; + var hiddenCategories = viewId is int categoryView + ? document.RawData.ViewHiddenCategories?.GetValueOrDefault(categoryView) : null; + var contours = new List<(double X1, double Y1, double X2, double Y2, double Z)>(); + HashSet? nativePrimaryLevels = null; var topography = new List>(); var topography3 = new List>(); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -76,7 +88,30 @@ void Grow(double x, double y) foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Topography) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Topography || !IsPlaced(element)) continue; + bool hasContours = document.RawData.SiteContours?.TryGetValue(element.Id, out _) == true; + if (hasContours) + { + nativePrimaryLevels ??= []; + foreach (var contour in document.RawData.SiteContours![element.Id]) + { + double level = contour.Elevation * FeetToMillimetres; + if (contour.Primary) nativePrimaryLevels.Add(level); + foreach (var line in contour.Lines) + { + for (int i = 1; i < line.Count; i++) + { + var a = line[i - 1]; + var b = line[i]; + if (a == b) continue; + contours.Add((a.X * FeetToMillimetres, a.Y * FeetToMillimetres, + b.X * FeetToMillimetres, b.Y * FeetToMillimetres, level)); + Grow(a.X * FeetToMillimetres, a.Y * FeetToMillimetres); + Grow(b.X * FeetToMillimetres, b.Y * FeetToMillimetres); + } + } + } + } if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; foreach (var face in geometry.Faces) { @@ -92,32 +127,32 @@ void Grow(double x, double y) Grow(x, y); } topography.Add(polygon); - topography3.Add(corners); + if (!hasContours) topography3.Add(corners); if (topography.Count >= 20000) break; } } - var plants = new List<(double X, double Y, double Radius, string Type, string Mark)>(); + var plants = new List(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Planting) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Planting || !IsPlaced(element)) continue; double[]? box = element.BoundingBox ?? element.Geometry?.BoundingBox; if (box is not { Length: 6 } || box[3] <= box[0] || box[4] <= box[1]) continue; - double x = (box[0] + box[3]) / 2 * FeetToMillimetres; - double y = (box[1] + box[4]) / 2 * FeetToMillimetres; - double radius = Math.Min(box[3] - box[0], box[4] - box[1]) / 2 * FeetToMillimetres; + double x = (element.InstanceOriginXY?.X ?? (box[0] + box[3]) / 2) * FeetToMillimetres; + double y = (element.InstanceOriginXY?.Y ?? (box[1] + box[4]) / 2) * FeetToMillimetres; + double? rpcRadius = RpcPlanRadius(document, element); + double radius = rpcRadius ?? Math.Min(box[3] - box[0], box[4] - box[1]) / 2 * FeetToMillimetres; if (radius <= 0) continue; - plants.Add((x, y, radius, element.Name ?? "", PlantingTypeOf(document, element).Mark)); + plants.Add(new(x, y, radius, element.Name ?? "", PlantingTypeOf(document, element).Mark, rpcRadius.HasValue)); Grow(x - radius, y - radius); Grow(x + radius, y + radius); } - // The cars and the people of the site (the entourage) print as their outlines seen from above, as the - // reference site plan shows a car on the drive. + // Visible entourage uses the placed instance bounds for its plan outline. var entourage = new List>(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Entourage) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Entourage || !IsPlaced(element)) continue; double[]? box = element.BoundingBox ?? element.Geometry?.BoundingBox; if (box is not { Length: 6 }) continue; double x0 = box[0] * FeetToMillimetres, y0 = box[1] * FeetToMillimetres; @@ -145,7 +180,6 @@ void Grow(double x, double y) // The contours of the terrain: the mesh is sliced at every half metre (a metre on a high site) and each slice // is drawn as the lines a site plan prints, the way the reference shows the fall of the ground. - var contours = new List<(double X1, double Y1, double X2, double Y2, double Z)>(); if (topography3.Count > 0) { double zMin = topography3.Min(corners => corners.Min(corner => corner[2])); @@ -172,10 +206,29 @@ void Grow(double x, double y) } } - if (topography.Count == 0 && plants.Count == 0) return null; - return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + var propertyLines = new List>(); + foreach (var element in document.Elements) + { + if (PropertyLineHidden(hiddenCategories) || !IsPlaced(element) || element.SitePropertyCurve is not { Count: >= 2 } curve) + continue; + var line = curve.Select(p => (X: p.X * FeetToMillimetres, Y: p.Y * FeetToMillimetres)).ToList(); + propertyLines.Add(line); + foreach (var point in line) Grow(point.X, point.Y); + } + if (topography.Count == 0 && contours.Count == 0 && plants.Count == 0 && propertyLines.Count == 0) return null; + return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + propertyLines, nativePrimaryLevels); + + bool IsPlaced(Element element) => !element.IsDiscovered && element.SerializedUnplacedOwnerId is not > 0 + && element.NativeIsSymbol != true && !element.RootClassIs("FamilySymbol") && hidden?.Contains(element.Id) != true + && (element.CategoryId is not int category || hiddenCategories?.Contains(category) != true); } + /// True when the view hides the property boundaries. A segment carries its own category, but a view hides + /// the boundary through "Property Lines", the category the lines are inked with. + internal static bool PropertyLineHidden(HashSet? hiddenCategories) => + hiddenCategories?.Contains((int)BuiltInCategory.OST_SiteProperty) == true; + /// The schedule key of a planting instance: the type mark (its ALL_MODEL_TYPE_MARK) and the /// common name (its ALL_MODEL_DESCRIPTION, the "Common Name" the planting schedule lists), read from its /// type when the type carries them, else from the instance itself. Empty when the file names neither. @@ -191,18 +244,29 @@ internal static (string Mark, string CommonName) PlantingTypeOf(RvtDocument docu } /// Draws the site with (MinX, MinY) at (originX, originY), one model unit per 1/scale. - internal static void DrawContent(PdfPage page, SiteContent content, double scale, double originX, double originY) + internal static void DrawContent(PdfPage page, SiteContent content, double scale, double originX, double originY, + RvtDocument? document = null, bool opaqueGround = false, SiteGraphics? graphics = null, bool drawFallbackTags = true, + bool drawFallbackNorth = true, int? viewId = null, ViewCropFrame? basis = null) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; - // A light green wash under the site; only the outer edge of the terrain mesh is inked, so the triangulation does - // not cover the plan. + (double Width, PdfColor Color)? ProjectionPen(BuiltInCategory category) + { + if (document?.RawData.PenWidthTable is not { } table + || !PenWidths.TryGetStyle(document, (int)category, false, out int pen, out int rgb) + || rgb < 0 || rgb > 0xFFFFFF + || !PenWidths.TryPenWidth(table, pen, (int)Math.Round(scale), out double width)) return null; + return (width, new PdfColor((rgb & 255) / 255d, ((rgb >> 8) & 255) / 255d, (rgb >> 16) / 255d)); + } + + // Only the outer edge of the terrain mesh is inked, so the triangulation does not cover the plan. + PdfColor ground = opaqueGround ? new PdfColor(1, 1, 1) : new PdfColor(0.92, 0.95, 0.9); var edges = new Dictionary(StringComparer.Ordinal); var edgeLines = new Dictionary(StringComparer.Ordinal); foreach (var polygon in content.Topography) { var points = polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); - page.DrawPolyline(points, 0, true, new PdfColor(0.92, 0.95, 0.9)); + page.DrawPolyline(points, 0, true, ground); for (int i = 0; i < points.Count; i++) { var a = points[i]; @@ -221,17 +285,68 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale if (count != 1 || !edgeLines.TryGetValue(key, out var line)) continue; page.DrawLine(line.A.Item1, line.A.Item2, line.B.Item1, line.B.Item2, 0.15, 0.45); } - // The contours of the terrain go over the wash, under the planting; every fifth one is an index contour drawn - // heavier, the way a site plan reads the fall of the ground. - var contourLevels = content.Contours.Select(contour => contour.Z).Distinct().OrderBy(level => level).ToList(); + if (graphics is { GroundShadows.Count: > 0 }) + page.FillPolygonUnion(graphics.GroundShadows.Select(ring => ring.Select(p => (ToX(p.X), ToY(p.Y))).ToList()), + graphics.ShadowGray); + + var primary = content.NativePrimaryLevels == null ? null : ProjectionPen(BuiltInCategory.OST_TopographyContours); + var secondary = content.NativePrimaryLevels == null ? null : ProjectionPen(BuiltInCategory.OST_SecondaryTopographyContours); + var contourLevels = content.NativePrimaryLevels == null + ? content.Contours.Select(contour => contour.Z).Distinct().OrderBy(level => level).ToList() : null; + var contourLabels = ContourLabels(page, document, viewId, basis, ToX, ToY); foreach (var (x1, y1, x2, y2, level) in content.Contours) { - bool index = contourLevels.IndexOf(level) % 5 == 0; - page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), index ? 0.16 : 0.07, index ? 0.5 : 0.62); + bool index = content.NativePrimaryLevels?.Contains(level) ?? contourLevels!.IndexOf(level) % 5 == 0; + var pen = index ? primary : secondary; + double ax = ToX(x1), ay = ToY(y1), bx = ToX(x2), by = ToY(y2); + foreach (var (start, end) in ContourSpans(ax, ay, bx, by, level, contourLabels)) + { + double sx = ax + start * (bx - ax), sy = ay + start * (by - ay); + double ex = ax + end * (bx - ax), ey = ay + end * (by - ay); + if (pen is { } style) page.DrawLine(sx, sy, ex, ey, style.Width, style.Color); + else page.DrawLine(sx, sy, ex, ey, index ? 0.16 : 0.07, index ? 0.5 : 0.62); + } } - foreach (var (x, y, radius, _, _) in content.Plants) + if (graphics is { Equipment: not null } && document != null) + DrawEquipment(page, document, graphics, basis, scale, ToX, ToY); + foreach (var label in contourLabels) + page.DrawTextRotated(label.Text, label.X + label.Sine * label.Baseline, + label.Y - label.Cosine * label.Baseline, label.Height, label.Angle * 180 / Math.PI, + PdfTextAlignment.Center); + if (content.PropertyLines is { Count: > 0 } properties) { - double pageX = ToX(x), pageY = ToY(y), r = radius / scale; + double pen = 0.18; + int category = (int)BuiltInCategory.OST_SiteProperty; + if (document != null && PenWidths.TryGetWidth(document, category, false, (int)Math.Round(scale), out double width)) + pen = width; + double[]? dashes = document != null && LinePatterns.TryGetDashes(document, category, out double[] pattern) + ? pattern : null; + foreach (var line in properties) + { + var points = line.Select(p => (X: ToX(p.X), Y: ToY(p.Y))).ToList(); + if (dashes == null) + { + page.DrawPolyline(points, pen); + continue; + } + double length = 0; + for (int i = 1; i < points.Count; i++) + { + double dx = points[i].X - points[i - 1].X, dy = points[i].Y - points[i - 1].Y; + length += Math.Sqrt(dx * dx + dy * dy); + } + page.DrawRoundDashedPolyline(points, pen, LinePatterns.FitEndpointDashes(length * (72 / 25.4), dashes)); + } + } + var plantingPen = ProjectionPen(BuiltInCategory.OST_Planting) ?? (0.1, new PdfColor(0, 0, 0)); + foreach (var plant in content.Plants) + { + double pageX = ToX(plant.X), pageY = ToY(plant.Y), r = plant.Radius / scale; + if (plant.Rpc) + { + DrawRpcPlant(page, pageX, pageY, r, basis, plantingPen.Item1, plantingPen.Item2); + continue; + } var circle = new List<(double X, double Y)>(24); for (int i = 0; i < 24; i++) { @@ -251,7 +366,7 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale var types = content.Plants.Where(plant => plant.Type.Length > 0).Select(plant => plant.Type) .Distinct().OrderBy(name => name, StringComparer.OrdinalIgnoreCase).ToList(); var tagged = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (page.Owner.Font != null) + if (drawFallbackTags && page.Owner.Font != null) { foreach (var plant in content.Plants) { @@ -269,6 +384,7 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale } } + if (!drawFallbackNorth) return; // The north arrow at the lower right of the site. double boxRight = (content.MaxX - content.MinX) / scale + originX; double boxBottom = originY; @@ -285,4 +401,4 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale page.DrawLine(northX, northY, northX, northY + 5, 0.18); page.DrawText("N", northX, northY + 6, 2.6, PdfTextAlignment.Center); } -} \ No newline at end of file +} diff --git a/src/RvtIO/Print/SolarStudyOverlay.cs b/src/RvtIO/Print/SolarStudyOverlay.cs new file mode 100644 index 00000000..c9d2e468 --- /dev/null +++ b/src/RvtIO/Print/SolarStudyOverlay.cs @@ -0,0 +1,474 @@ +using System.Globalization; +using System.Numerics; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal sealed class SolarStudyOverlay +{ + private const double CompassOutside = 1.05; + private const int DeclinationSteps = 2048; + private const double Radians = Math.PI / 180; + private readonly Vector3 _right, _up, _look; + private readonly double _centerDepth, _modelRadius; + private readonly double _latitude, _longitude, _zone; + private readonly (double Start, double End)[][]? _hours; + private readonly double _minDeclination, _maxDeclination; + private readonly DateTime _start, _end; + private readonly DateTime? _active; + private readonly Vector3? _sun; + private readonly double? _domeLightFloor; + private readonly Vector3 _domeHalfVector; + private readonly int _studyDays; + + internal double X { get; } + internal double Y { get; } + internal double Radius { get; } + internal double GroundElevation { get; } + internal bool AnnotationVisible { get; } + internal Vector3? ModelSunDirection { get; } + + private SolarStudyOverlay((double X, double Y, double Depth) center, double radius, double modelRadius, + double groundElevation, Vector3 right, Vector3 up, Vector3 look, ViewSolarStudy study, RevitFileInfo raw, + double[] location, bool annotationVisible) + { + X = center.X; + Y = center.Y; + Radius = radius; + GroundElevation = groundElevation; + _centerDepth = center.Depth; + _modelRadius = modelRadius; + _right = right; + _up = up; + _look = look; + AnnotationVisible = annotationVisible; + if (raw.SiteLatitudeRadians is not double latitude || raw.SiteLongitudeRadians is not double longitude + || raw.SiteTimeZoneHours is not double zone + || !TryDecodeDate(study.Start, out _start) || !TryDecodeDate(study.End, out _end) + || _start.Date >= _end.Date || _start.TimeOfDay >= _end.TimeOfDay) + return; + (_latitude, _longitude, _zone) = (latitude, longitude, zone); + // A full leap cycle bounds the annual study paths. + _studyDays = Math.Min((_end.Date - _start.Date).Days, 4 * 366 + 365); + if (AnnotationVisible) + (_hours, _minDeclination, _maxDeclination) = StudyHours(); + // shortcut: hourly frames, until the other stored interval ordinals are verified. + if (study.Interval != 3 || study.ActiveFrame is not (>= 1 and <= int.MaxValue) + || study.ActiveFrame != Math.Truncate(study.ActiveFrame)) return; + int samplesPerDay = 1 + (int)(_end.TimeOfDay - _start.TimeOfDay).TotalHours; + int index = (int)study.ActiveFrame - 1; + int day = index / samplesPerDay; + if (day <= (_end.Date - _start.Date).Days) + { + var active = _start.AddDays(day).AddHours(index % samplesPerDay); + _active = active; + var (declination, equation) = StudyEphemeris(active, active.TimeOfDay.TotalHours); + var sun = SunVector(declination, HourAngle(active.TimeOfDay.TotalMinutes, equation)); + _sun = sun; + ModelSunDirection = ToModelDirection(sun, location); + if (sun.Z > 0 && study.SunlightIntensity is int intensity) + { + _domeLightFloor = LightFloor(sun, intensity); + var half = sun - look; + if (half.LengthSquared() > 1e-8f) _domeHalfVector = Vector3.Normalize(half); + } + } + } + + internal static SolarStudyOverlay? Create(RvtDocument document, Element view, + ViewCropFrame camera, double millimetresPerFoot, Func project) + { + var raw = document.RawData; + if (view.SolarStudy is not { } study || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } location + || document.GetElement(study.GroundLevelId)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value + is not double elevation || !double.IsFinite(elevation)) return null; + double[] box = study.Outline; + double w = (box[3] - box[0]) / 2, d = (box[4] - box[1]) / 2; + double h = Math.Max(Math.Abs(box[5] - elevation), Math.Abs(box[2] - elevation)); + double modelRadius = Math.Sqrt(w * w + d * d + h * h) * study.SizePercent / 100; + double radius = modelRadius * millimetresPerFoot; + if (!(radius > 0) || !double.IsFinite(radius)) return null; + var center = project([box[0] + w, box[1] + d, elevation]); + Vector3 ToShared(double[] v) => new( + (float)(v[0] * location[0] + v[1] * location[3]), + (float)(v[0] * location[1] + v[1] * location[4]), (float)v[2]); + bool visible = study.AnnotationId > 0 + && raw.ViewHiddenElements?.GetValueOrDefault(view.Id)?.Contains(study.AnnotationId) != true; + if (!visible && study.ShadowIntensity <= 0 && study.SunlightIntensity == null) return null; + return new(center, radius, modelRadius, elevation, ToShared(camera.Right), ToShared(camera.Up), ToShared(camera.Look), + study, raw, location, visible); + } + + internal static Vector3? StillSunDirection(RevitFileInfo raw, int viewId) + { + if (raw.ViewStillSunDates?.TryGetValue(viewId, out uint packedDate) != true + || !TryDecodeDate(packedDate, out var date) || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } location + || raw.SiteLatitudeRadians is not double latitude || raw.SiteLongitudeRadians is not double longitude + || raw.SiteTimeZoneHours is not double zone) return null; + var (declination, equation) = Ephemeris(date, date.TimeOfDay.TotalHours); + double angle = HourAngle(date.TimeOfDay.TotalMinutes, equation, longitude, zone); + var sun = SunVector(declination, angle, latitude); + return sun.Z > 0 ? ToModelDirection(sun, location) : null; + } + + private static Vector3 ToModelDirection(Vector3 sun, double[] location) => + new((float)(sun.X * location[0] + sun.Y * location[1]), + (float)(sun.X * location[3] + sun.Y * location[4]), sun.Z); + + // Calibrated from native shaded output with zero configured ambient light. + internal static double LightFloor(Vector3 sun, int intensity) => 0.2 + intensity / 100d * sun.Z * sun.Z; + + internal static bool TryDecodeDate(uint value, out DateTime date) + { + date = default; + int year = (int)(value >> 20), month = (int)(value >> 16 & 15), day = (int)(value >> 11 & 31); + int hour = (int)(value >> 6 & 31), minute = (int)(value & 63); + if (year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) + || hour > 23 || minute > 59) return false; + date = new(year, month, day, hour, minute, 0); + return true; + } + + // NOAA's general solar position equations use local standard time and radian angles. + private static (double Declination, double Equation) Ephemeris(DateTime date, double hour) + { + double g = Math.Tau * (date.DayOfYear - 1 + (hour - 12) / 24) / (DateTime.IsLeapYear(date.Year) ? 366 : 365); + double c = Math.Cos(g), s = Math.Sin(g), c2 = Math.Cos(2 * g), s2 = Math.Sin(2 * g); + return (0.006918 - 0.399912 * c + 0.070257 * s - 0.006758 * c2 + 0.000907 * s2 + - 0.002697 * Math.Cos(3 * g) + 0.00148 * Math.Sin(3 * g), + 229.18 * (0.000075 + 0.001868 * c - 0.032077 * s - 0.014615 * c2 - 0.040849 * s2)); + } + + private double HourAngle(double minutes, double equation) => HourAngle(minutes, equation, _longitude, _zone); + + private static double HourAngle(double minutes, double equation, double longitude, double zone) => + ((minutes + equation - 60 * zone) / 4 - 180) * Radians + longitude; + + // Apparent solar longitude and obliquity from NOAA's Meeus-based solar calculator. + private (double Declination, double Equation) StudyEphemeris(DateTime date, double hour) + { + double t = ((date.Date - new DateTime(2000, 1, 1, 12, 0, 0)).TotalDays + (hour - _zone) / 24) / 36525; + double longitude = (280.46646 + t * (36000.76983 + 0.0003032 * t)) % 360 * Radians; + double anomaly = (357.52911 + t * (35999.05029 - 0.0001537 * t)) * Radians; + double eccentricity = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); + double center = ((1.914602 - t * (0.004817 + 0.000014 * t)) * Math.Sin(anomaly) + + (0.019993 - 0.000101 * t) * Math.Sin(2 * anomaly) + 0.000289 * Math.Sin(3 * anomaly)) * Radians; + double node = (125.04 - 1934.136 * t) * Radians; + double apparentLongitude = longitude + center - (0.00569 + 0.00478 * Math.Sin(node)) * Radians; + double obliquity = (23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - 0.001813 * t))) / 60) / 60 + + 0.00256 * Math.Cos(node)) * Radians; + double y = Math.Tan(obliquity / 2); + y *= y; + double equation = y * Math.Sin(2 * longitude) - 2 * eccentricity * Math.Sin(anomaly) + + 4 * eccentricity * y * Math.Sin(anomaly) * Math.Cos(2 * longitude) + - 0.5 * y * y * Math.Sin(4 * longitude) - 1.25 * eccentricity * eccentricity * Math.Sin(2 * anomaly); + return (Math.Asin(Math.Sin(obliquity) * Math.Sin(apparentLongitude)), 4 * equation / Radians); + } + + private ((double Start, double End)[][] Hours, double Min, double Max) StudyHours() + { + var samples = new (double Declination, double Start, double End)[_studyDays + 1]; + for (int i = 0; i < samples.Length; ++i) + { + var (declination, equation) = StudyEphemeris(_start.AddDays(i), 12); + samples[i] = (Math.Sin(declination), HourAngle(_start.TimeOfDay.TotalMinutes, equation), + HourAngle(_end.TimeOfDay.TotalMinutes, equation)); + } + double min = samples.Min(s => s.Declination), max = samples.Max(s => s.Declination); + var hours = new (double Start, double End)[DeclinationSteps + 1][]; + for (int i = 0; i <= DeclinationSteps; ++i) + { + double d = min + (max - min) * i / DeclinationSteps; + var intervals = new List<(double Start, double End)>(); + for (int day = 1; day < samples.Length; ++day) + { + var a = samples[day - 1]; + var b = samples[day]; + if (d < Math.Min(a.Declination, b.Declination) || d > Math.Max(a.Declination, b.Declination)) continue; + double t = a.Declination == b.Declination ? 0 : (d - a.Declination) / (b.Declination - a.Declination); + intervals.Add((a.Start + (b.Start - a.Start) * t, a.End + (b.End - a.End) * t)); + } + hours[i] = intervals.ToArray(); + } + return (hours, min, max); + } + + private (double X, double Y) Project(double east, double north, double up) => + (X + Radius * (east * _right.X + north * _right.Y + up * _right.Z), + Y + Radius * (east * _up.X + north * _up.Y + up * _up.Z)); + + private Vector3 SunVector(double declination, double angle) => SunVector(declination, angle, _latitude); + + private static Vector3 SunVector(double declination, double angle, double latitude) + { + double decSin = Math.Sin(declination), decCos = Math.Cos(declination); + double meridian = decCos * Math.Cos(angle), sinLat = Math.Sin(latitude), cosLat = Math.Cos(latitude); + return new((float)(-decCos * Math.Sin(angle)), (float)(cosLat * decSin - sinLat * meridian), + (float)(sinLat * decSin + cosLat * meridian)); + } + + private (double X, double Y) ProjectSun(double declination, double angle) + { + var vector = SunVector(declination, angle); + return Project(vector.X, vector.Y, vector.Z); + } + + private static bool SameCalendarDay(DateTime a, DateTime b) => a.Month == b.Month && a.Day == b.Day; + + internal void Paint(byte[] rgb, int columns, int rows, double left, double top, double dx, double dy, + double[]? modelDepth = null) + { + double determinant = _right.X * _up.Y - _right.Y * _up.X; + double sinLat = Math.Sin(_latitude), cosLat = Math.Cos(_latitude); + double pen = Math.Max(dx, dy) / Radius * 0.6; + for (int row = 0; row < rows; ++row) + { + double v = (top - (row + 0.5) * dy - Y) / Radius; + for (int col = 0; col < columns; ++col) + { + double u = (left + (col + 0.5) * dx - X) / Radius; + int pixel = 3 * (row * columns + col); + bool hasModel = rgb[pixel] != 255 || rgb[pixel + 1] != 255 || rgb[pixel + 2] != 255; + if (Math.Abs(determinant) > 1e-6) + { + double east = (_up.Y * u - _right.Y * v) / determinant; + double north = (_right.X * v - _up.X * u) / determinant; + double r = Math.Sqrt(east * east + north * north); + double compassDepth = _centerDepth + _modelRadius * (east * _look.X + north * _look.Y); + if (r <= 1.09 && (modelDepth == null || compassDepth <= modelDepth[pixel / 3] + 1e-5)) + { + double degrees = Math.Atan2(-east, north) / Radians; + double sector = (degrees + 360) % 30; + double tick = Math.Abs(sector - Math.Round(sector / 5) * 5); + bool major = Math.Abs(sector - Math.Round(sector / 15) * 15) * Radians * r < pen; + if (r >= 1 && r <= CompassOutside) + Blend(pixel, sector < 15 ? 138 : 250, sector < 15 ? 138 : 250, + sector < 15 ? 138 : 250, sector < 15 ? 1 : 0.45); + bool circle = Math.Abs(r - 1) < pen || Math.Abs(r - CompassOutside) < pen; + bool onTick = (major && r >= 0.97 && r <= 1.08) + || (sector >= 15 && r >= 1 && r <= CompassOutside && tick * Radians * r < pen); + if (circle || onTick) Blend(pixel, 115, 115, 115, 0.53); + if (rgb[pixel] == 255 && rgb[pixel + 1] == 255 && rgb[pixel + 2] == 255 + && Math.Min(Math.Abs(east), Math.Abs(north)) < pen) + Blend(pixel, 170, 170, 170, 0.4); + } + } + if (_hours == null || u * u + v * v >= 1) continue; + double depth = Math.Sqrt(1 - u * u - v * v); + bool front = InBand(u, v, -depth, sinLat, cosLat, out var direction); + bool back = InBand(u, v, depth, sinLat, cosLat, out _); + double incidence = _sun is Vector3 sun && front ? Vector3.Dot(sun, direction) : 1; + if (front && !back && _domeLightFloor is double lightFloor) + { + // shortcut: native single-surface tint, until overlapping band layers are verified. + double highlight = incidence > 0 ? Math.Max(0, Vector3.Dot(_domeHalfVector, direction)) : 0; + double light = lightFloor + Math.Max(0, incidence) + 0.5 * Math.Pow(highlight, 64); + Blend(pixel, (int)Math.Min(254, Math.Round(255 * light)), + (int)Math.Min(254, Math.Round(160 * light)), 0, 0.75); + continue; + } + bool unlitBackground = front && !hasModel && incidence <= 0; + if (front && !unlitBackground) + { + // shortcut: diffuse dome shading, until the native study shader is reproduced. + double diffuse = Math.Max(0, incidence); + double intensity = hasModel ? Math.Min(1, 0.38 + diffuse) : 1; + double green = hasModel ? 175 + 80 * Math.Pow(diffuse, 6) : 165 + 70 * direction.Z; + Blend(pixel, (int)(255 * intensity), (int)(green * intensity), 6, 0.74); + } + if (back || unlitBackground) Blend(pixel, 135, 105, 62, front && !unlitBackground ? 0.63 : 1); + } + } + if (_hours != null) + { + PaintGuide(TimeBoundary(_start.TimeOfDay.TotalMinutes)); + PaintGuide(TimeBoundary(_end.TimeOfDay.TotalMinutes)); + PaintGuide(HorizonBoundary(-1)); + PaintGuide(HorizonBoundary(1)); + PaintGuide(DayGuide(_start)); + if (!SameCalendarDay(_start, _end)) PaintGuide(DayGuide(_end)); + if (_sun is Vector3 sun) + { + var center = Project(sun.X, sun.Y, sun.Z); + double sunRadius = Radius * 0.05; + int fromRow = Math.Max(0, (int)Math.Floor((top - center.Y - sunRadius) / dy)); + int toRow = Math.Min(rows - 1, (int)Math.Ceiling((top - center.Y + sunRadius) / dy)); + int fromCol = Math.Max(0, (int)Math.Floor((center.X - sunRadius - left) / dx)); + int toCol = Math.Min(columns - 1, (int)Math.Ceiling((center.X + sunRadius - left) / dx)); + for (int row = fromRow; row <= toRow; ++row) + for (int col = fromCol; col <= toCol; ++col) + { + double a = (left + (col + 0.5) * dx - center.X) / sunRadius; + double b = (top - (row + 0.5) * dy - center.Y) / sunRadius; + double r2 = a * a + b * b; + if (r2 <= 1) Blend(3 * (row * columns + col), 255, r2 < 0.88 ? 245 : 175, + r2 < 0.88 ? 91 : 11, 0.85); + } + } + } + + IEnumerable DayGuide(DateTime day) + { + var (dec, _) = StudyEphemeris(day, 12); + var horizon = Horizon(dec, 0); + if (horizon <= 0) yield break; + int samples = (int)Math.Ceiling(4 * horizon / Radians); + for (int i = 0; i <= samples; ++i) + yield return SunVector(dec, horizon * (2.0 * i / samples - 1)); + } + + IEnumerable TimeBoundary(double minutes) + { + for (int day = 0; day <= _studyDays; day++) + { + var (dec, equation) = StudyEphemeris(_start.AddDays(day), minutes / 60); + yield return SunVector(dec, HourAngle(minutes, equation)); + } + } + + IEnumerable HorizonBoundary(int sign) + { + for (int i = 0; i <= DeclinationSteps; i++) + { + double dec = Math.Asin(_minDeclination + (_maxDeclination - _minDeclination) * i / DeclinationSteps); + double horizon = Horizon(dec, 0); + yield return horizon is > 0 and < Math.PI && ContainsStudyHour(i, sign * horizon) + ? SunVector(dec, sign * horizon) with { Z = 0 } : null; + } + } + + void PaintGuide(IEnumerable vertices) + { + Vector3? previous = null; + int previousPixel = -1; + foreach (var vertex in vertices) + { + if (previous is Vector3 a && vertex is Vector3 b && Math.Max(a.Z, b.Z) >= -1e-7f) + { + if (Math.Min(a.Z, b.Z) < -1e-7f) + { + var horizon = Vector3.Lerp(a, b, a.Z / (a.Z - b.Z)); + if (a.Z < 0) a = horizon; + else b = horizon; + } + var from = Project(a.X, a.Y, a.Z); + var to = Project(b.X, b.Y, b.Z); + double vx = (to.X - from.X) / dx, vy = (from.Y - to.Y) / dy; + double x = (from.X - left) / dx, y = (top - from.Y) / dy; + int samples = (int)Math.Clamp(Math.Ceiling(2 * Math.Max(Math.Abs(vx), Math.Abs(vy))), 1, 30_000); + for (int i = 0; i <= samples; i++) + { + double t = i / (double)samples; + int col = (int)Math.Floor(x + t * vx), row = (int)Math.Floor(y + t * vy); + if (col < 0 || col >= columns || row < 0 || row >= rows) continue; + int pixel = 3 * (row * columns + col); + if (pixel == previousPixel) continue; + Blend(pixel, 238, 147, 12, 0.85); + previousPixel = pixel; + } + } + previous = vertex; + } + } + + void Blend(int p, int r, int g, int b, double opacity) + { + rgb[p] = (byte)Math.Min(254, Math.Round(rgb[p] + (r - rgb[p]) * opacity)); + rgb[p + 1] = (byte)Math.Min(254, Math.Round(rgb[p + 1] + (g - rgb[p + 1]) * opacity)); + rgb[p + 2] = (byte)Math.Min(254, Math.Round(rgb[p + 2] + (b - rgb[p + 2]) * opacity)); + } + } + + private bool InBand(double u, double v, double depth, double sinLat, double cosLat, out Vector3 direction) + { + direction = default; + double height = u * _right.Z + v * _up.Z + depth * _look.Z; + if (_hours == null || height < 0) return false; + double north = u * _right.Y + v * _up.Y + depth * _look.Y; + double declination = north * cosLat + height * sinLat; + if (declination < _minDeclination || declination > _maxDeclination || !(_maxDeclination > _minDeclination)) + return false; + double east = u * _right.X + v * _up.X + depth * _look.X; + direction = new((float)east, (float)north, (float)height); + double hour = Math.Atan2(-east, height * cosLat - north * sinLat); + int row = (int)Math.Round((declination - _minDeclination) / (_maxDeclination - _minDeclination) * DeclinationSteps); + return ContainsStudyHour(row, hour); + } + + private bool ContainsStudyHour(int row, double hour) + { + foreach (var (from, to) in _hours![row]) + if (hour >= from && hour <= to || hour + Math.Tau >= from && hour + Math.Tau <= to + || hour - Math.Tau >= from && hour - Math.Tau <= to) return true; + return false; + } + + private double Horizon(double declination, double altitude) => Math.Acos(Math.Clamp( + (Math.Sin(altitude) - Math.Sin(_latitude) * Math.Sin(declination)) / + (Math.Cos(_latitude) * Math.Cos(declination)), -1, 1)); + + internal void DrawLabels(PdfPage page) + { + bool russian = page.Owner.Font != null && CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + Cardinal(russian ? "С" : "N", 0, 1.15); + Cardinal(russian ? "В" : "E", 1.15, 0); + Cardinal(russian ? "Ю" : "S", 0, -1.15); + Cardinal(russian ? "З" : "W", -1.15, 0); + if (_hours == null) return; + var ink = new PdfColor(0.94, 0.49, 0.01); + var timeDay = _active?.Date ?? _start.Date; + bool sharedDate = SameCalendarDay(_start, _end); + DateLabel(_start, bold: sharedDate); + if (!sharedDate) DateLabel(_end, bold: false); + if (!SameCalendarDay(timeDay, _start) && !SameCalendarDay(timeDay, _end)) DateLabel(timeDay, bold: false); + foreach (double minutes in new[] { _start.TimeOfDay.TotalMinutes, _end.TimeOfDay.TotalMinutes }) + { + var (declination, equation) = StudyEphemeris(timeDay, minutes / 60); + TimeLabel(ProjectSun(declination, HourAngle(minutes, equation)), minutes, ink); + } + if (_active is { } active && _sun is Vector3 sun) + { + DrawHorizonTimes(active); + var (x, y) = Project(sun.X, sun.Y, sun.Z); + TimeLabel((x - 4, y + Radius * 0.075), active.TimeOfDay.TotalMinutes, new PdfColor(0.85, 0.28, 0.08)); + } + + void Cardinal(string value, double east, double north) + { + var point = Project(east, north, 0); + page.DrawText(value, point.X, point.Y - 1, 4, PdfTextAlignment.Center); + } + + void DateLabel(DateTime day, bool bold) + { + var (dec, _) = StudyEphemeris(day, 12); + double horizon = Horizon(dec, 0); + if (!(horizon > 0 && horizon < Math.PI)) return; + var rise = ProjectSun(dec, -horizon); + var culture = russian ? CultureInfo.GetCultureInfo("ru-RU") : CultureInfo.GetCultureInfo("en-US"); + page.DrawStyledText(day.ToString(russian ? "d MMMM" : "MMM d", culture), rise.X + 1, rise.Y - 4, + 3.4, PdfTextAlignment.Left, 0, bold, ink); + } + + void DrawHorizonTimes(DateTime day) + { + var (dec, equation) = StudyEphemeris(day, 12); + double horizon = Horizon(dec, 0); + if (!(horizon > 0 && horizon < Math.PI)) return; + double noon = 720 - equation - 4 * _longitude / Radians + 60 * _zone; + TimeLabel(ProjectSun(dec, -horizon), Math.Ceiling(noon - 4 * horizon / Radians), ink); + TimeLabel(ProjectSun(dec, horizon), Math.Floor(noon + 4 * horizon / Radians), new PdfColor(1, 0.18, 0.2)); + } + + void TimeLabel((double X, double Y) point, double minutes, PdfColor ink) + { + int time = ((int)Math.Round(minutes) % 1440 + 1440) % 1440; + page.DrawStyledText(FormattableString.Invariant($"{time / 60}:{time % 60:00}"), + point.X + 1, point.Y + 1, 2.6, PdfTextAlignment.Left, 0, false, ink); + } + } +} diff --git a/src/RvtIO/Print/ViewportShadows.cs b/src/RvtIO/Print/ViewportShadows.cs new file mode 100644 index 00000000..cefa3933 --- /dev/null +++ b/src/RvtIO/Print/ViewportShadows.cs @@ -0,0 +1,153 @@ +using System.Numerics; +using RvtIO.Model; + +namespace RvtIO.Print; + +internal sealed class ViewportShadows +{ + internal enum Receiver : byte + { + FacingAway, + FacingSun, + Prelit, + } + + private const int GridSize = 64; + private readonly (double X, double Y, double Z) _direction, _right, _up; + private readonly ViewCropFrame _camera; + private readonly List _casters = []; + private readonly double _shade; + private readonly double? _ground; + private double _left = double.PositiveInfinity, _bottom = double.PositiveInfinity; + private double _rightEdge = double.NegativeInfinity, _top = double.NegativeInfinity; + + private sealed record Caster((double X, double Y)[][] Rings, double Z, double SlopeX, double SlopeY, + double MinX, double MinY, double MaxX, double MaxY); + + internal ViewportShadows(ViewCropFrame camera, Vector3 direction, int intensity, double? groundElevation = null) + { + _camera = camera; + double x = direction.X, y = direction.Y, z = direction.Z; + double horizontal = Math.Sqrt(x * x + y * y), magnitude = Math.Sqrt(horizontal * horizontal + z * z); + _direction = (x / magnitude, y / magnitude, z / magnitude); + _right = horizontal > 0 ? (-y / horizontal, x / horizontal, 0) : (1, 0, 0); + _up = (-_direction.Z * _right.Y, _direction.Z * _right.X, + _direction.X * _right.Y - _direction.Y * _right.X); + _shade = 1 - intensity / 100d; + if (groundElevation is double elevation && double.IsFinite(elevation) && _direction.Z > 0 + && Math.Abs(camera.Look[2]) > 1e-8) + _ground = elevation - camera.OriginZ; + } + + internal (double Left, double Bottom, double Right, double Top)? GroundShadowBounds => + _left < _rightEdge && _bottom < _top ? (_left, _bottom, _rightEdge, _top) : null; + + internal bool FacesLight(double[] normal) => Dot(normal[0], normal[1], normal[2], _direction) > 1e-8; + + internal void AddCaster(IReadOnlyList rings, double[] normal) + { + double facing = Dot(normal[0], normal[1], normal[2], _direction); + if (!(facing > 1e-8)) return; + double[] first = rings[0][0]; + double z = Dot(first[0] - _camera.OriginX, first[1] - _camera.OriginY, first[2] - _camera.OriginZ, _direction); + var projected = rings.Select(ring => ring.Select(point => + { + double x = point[0] - _camera.OriginX, y = point[1] - _camera.OriginY, h = point[2] - _camera.OriginZ; + return (X: Dot(x, y, h, _right), Y: Dot(x, y, h, _up)); + }).ToArray()).ToArray(); + var outer = projected[0]; + if (!double.IsFinite(z) || outer.Any(point => !double.IsFinite(point.X) || !double.IsFinite(point.Y))) return; + _casters.Add(new(projected, z, + -Dot(normal[0], normal[1], normal[2], _right) / facing, + -Dot(normal[0], normal[1], normal[2], _up) / facing, + outer.Min(p => p.X), outer.Min(p => p.Y), outer.Max(p => p.X), outer.Max(p => p.Y))); + if (_ground is not double ground || rings[0].All(point => point[2] <= ground + _camera.OriginZ)) return; + foreach (var point in rings[0]) + { + double t = (point[2] - _camera.OriginZ - ground) / _direction.Z; + double x = point[0] - _camera.OriginX - t * _direction.X; + double y = point[1] - _camera.OriginY - t * _direction.Y; + double u = x * _camera.Right[0] + y * _camera.Right[1] + ground * _camera.Right[2]; + double v = x * _camera.Up[0] + y * _camera.Up[1] + ground * _camera.Up[2]; + _left = Math.Min(_left, u); + _rightEdge = Math.Max(_rightEdge, u); + _bottom = Math.Min(_bottom, v); + _top = Math.Max(_top, v); + } + } + + internal void Apply(byte[] rgb, double[] depth, Receiver[] receivers, int columns, int rows, + double left, double top, double stepX, double stepY, double anchorX, double anchorY, double scale, + Func? containsGroundPoint = null) + { + // Approximate the tone of surfaces facing away from the active sun with the saved shadow strength. + for (int pixel = 0; pixel < depth.Length; pixel++) + if (receivers[pixel] == Receiver.FacingAway && double.IsFinite(depth[pixel])) + Shade(pixel); + if (_casters.Count == 0) return; + double minX = _casters.Min(p => p.MinX), maxX = _casters.Max(p => p.MaxX); + double minY = _casters.Min(p => p.MinY), maxY = _casters.Max(p => p.MaxY); + if (!(maxX > minX && maxY > minY)) return; + double cellX = (maxX - minX) / GridSize, cellY = (maxY - minY) / GridSize; + int GridX(double x) => Math.Clamp((int)((x - minX) / cellX), 0, GridSize - 1); + int GridY(double y) => Math.Clamp((int)((y - minY) / cellY), 0, GridSize - 1); + var grid = new List?[GridSize * GridSize]; + foreach (var caster in _casters) + { + int lastX = GridX(caster.MaxX), lastY = GridY(caster.MaxY); + for (int y = GridY(caster.MinY); y <= lastY; y++) + for (int x = GridX(caster.MinX); x <= lastX; x++) + (grid[y * GridSize + x] ??= []).Add(caster); + } + + // The grid indexes polygons. The actual hit still uses their plane and opening loops. + for (int row = 0; row < rows; row++) + { + double y = (top - (row + 0.5) * stepY - anchorY) / scale; + for (int column = 0; column < columns; column++) + { + int pixel = row * columns + column; + double z = depth[pixel]; + bool groundPixel = double.IsPositiveInfinity(z) && _ground.HasValue; + if (receivers[pixel] != Receiver.FacingSun && !groundPixel) continue; + double x = (left + (column + 0.5) * stepX - anchorX) / scale; + if (groundPixel) + { + if (x < _left || x > _rightEdge || y < _bottom || y > _top) continue; + z = (_ground!.Value - x * _camera.Right[2] - y * _camera.Up[2]) / _camera.Look[2]; + } + double wx = x * _camera.Right[0] + y * _camera.Up[0] + z * _camera.Look[0]; + double wy = x * _camera.Right[1] + y * _camera.Up[1] + z * _camera.Look[1]; + double wz = x * _camera.Right[2] + y * _camera.Up[2] + z * _camera.Look[2]; + if (groundPixel && containsGroundPoint?.Invoke(wx + _camera.OriginX, wy + _camera.OriginY, + wz + _camera.OriginZ) == false) continue; + double lx = Dot(wx, wy, wz, _right), ly = Dot(wx, wy, wz, _up); + if (lx < minX || lx > maxX || ly < minY || ly > maxY + || grid[GridY(ly) * GridSize + GridX(lx)] is not { } candidates) continue; + double receiver = Dot(wx, wy, wz, _direction); + foreach (var caster in candidates) + { + if (lx < caster.MinX || lx > caster.MaxX || ly < caster.MinY || ly > caster.MaxY) continue; + var first = caster.Rings[0][0]; + double blocker = caster.Z + (lx - first.X) * caster.SlopeX + (ly - first.Y) * caster.SlopeY; + if (!(blocker - receiver > 1e-6)) continue; + bool hit = false; + foreach (var polygon in caster.Rings) + if (PlanPrinter.PointInPolygon(lx, ly, polygon)) hit = !hit; + if (!hit) continue; + Shade(pixel); + break; + } + } + } + + void Shade(int pixel) + { + for (int channel = 0; channel < 3; channel++) + rgb[3 * pixel + channel] = (byte)Math.Round(rgb[3 * pixel + channel] * _shade); + } + } + + private static double Dot(double x, double y, double z, (double X, double Y, double Z) axis) => + x * axis.X + y * axis.Y + z * axis.Z; +} diff --git a/src/RvtIO/Print/ViewportSurfaceEdges.cs b/src/RvtIO/Print/ViewportSurfaceEdges.cs new file mode 100644 index 00000000..9c40ba94 --- /dev/null +++ b/src/RvtIO/Print/ViewportSurfaceEdges.cs @@ -0,0 +1,44 @@ +namespace RvtIO.Print; + +internal sealed class ViewportSurfaceEdges +{ + private readonly record struct Segment(double X, double Y, double Dx, double Dy, double LengthSquared, double Length); + + private readonly Segment[] _segments; + private readonly double _width; + internal int Color { get; } + + internal ViewportSurfaceEdges(IEnumerable<((double X, double Y) Start, (double X, double Y) End)> lines, + double width, int color) + { + _segments = lines.Select(line => + { + double dx = line.End.X - line.Start.X, dy = line.End.Y - line.Start.Y; + double squared = dx * dx + dy * dy; + return new Segment(line.Start.X, line.Start.Y, dx, dy, squared, Math.Sqrt(squared)); + }).Where(edge => edge.LengthSquared > 1e-12 && double.IsFinite(edge.LengthSquared)).ToArray(); + _width = width; + Color = color == 0xffffff ? 0xfefefe : color; + } + + internal double Coverage(double x, double y, double stepX, double stepY) + { + double maximum = 0; + double halfWidth = _width / 2; + double margin = halfWidth + (stepX + stepY) / 2; + foreach (var edge in _segments) + { + double dx = x - edge.X, dy = y - edge.Y; + if (dx < Math.Min(0, edge.Dx) - margin || dx > Math.Max(0, edge.Dx) + margin + || dy < Math.Min(0, edge.Dy) - margin || dy > Math.Max(0, edge.Dy) + margin) continue; + double along = Math.Clamp((dx * edge.Dx + dy * edge.Dy) / edge.LengthSquared, 0, 1); + double u = dx - along * edge.Dx, v = dy - along * edge.Dy; + double distance = Math.Sqrt(u * u + v * v); + double footprint = (Math.Abs(edge.Dy) * stepX + Math.Abs(edge.Dx) * stepY) / edge.Length; + double lo = Math.Max(distance - footprint / 2, -halfWidth); + double hi = Math.Min(distance + footprint / 2, halfWidth); + maximum = Math.Max(maximum, (hi - lo) / footprint); + } + return maximum; + } +} diff --git a/src/RvtIO/Print/ViewportSurfacePattern.cs b/src/RvtIO/Print/ViewportSurfacePattern.cs new file mode 100644 index 00000000..bca5c017 --- /dev/null +++ b/src/RvtIO/Print/ViewportSurfacePattern.cs @@ -0,0 +1,90 @@ +using RvtIO.Model; + +namespace RvtIO.Print; + +internal sealed class ViewportSurfacePattern +{ + private readonly (FillHatch.ModelGrid Model, double Cos, double Sin, double Period)[] _grids; + private readonly double _width; + internal int Color { get; } + + private ViewportSurfacePattern(IEnumerable grids, double width, int color) + { + _grids = grids.Select(grid => (grid, Math.Cos(grid.Angle), Math.Sin(grid.Angle), grid.Segments?.Sum() ?? 0)).ToArray(); + _width = width; + Color = color == 0xffffff ? 0xfefefe : color; + } + + internal static ViewportSurfacePattern? Create(RvtDocument document, GeoFace face, + Func project, double offsetX, double offsetY, double width) + { + IReadOnlyList? grids = FillHatch.ProjectModelGrid(document, face, project) is { } solid + ? [solid] : FillHatch.ProjectDashedModelGrids(document, face, project); + if (grids == null) return null; + int color = 0; + if ((face.RenderStyleId ?? face.NestedRenderStyleId) is int materialId + && document.RawData.MaterialPatterns?.TryGetValue(materialId, out var material) == true + && material.SurfacePatternId == face.ModelPattern?.PatternId + && material.SurfacePatternColor is >= 0 and <= 0xffffff and int savedColor) + color = savedColor; + return new(grids.Select(grid => grid with { X = grid.X + offsetX, Y = grid.Y + offsetY }), width, color); + } + + internal static ViewportSurfacePattern? CreateDraftingCut(RvtDocument document, int materialId, + (double X, double Y) origin, (double X, double Y) u, (double X, double Y) v, double width) + { + if (document.RawData.MaterialPatterns?.TryGetValue(materialId, out var material) != true + || document.RawData.FillPatterns?.TryGetValue(material.CutPatternId, out var pattern) != true + || pattern.Grids.Count == 0 + || !pattern.Grids.All(grid => grid is { Target: 0, Orientation: 0 })) return null; + var grids = new List(pattern.Grids.Count); + foreach (var grid in pattern.Grids) + { + if (FillHatch.ProjectGrid(grid, origin, u, v) is not { } projected) return null; + grids.Add(projected); + } + return new(grids, width, document.RawData.MaterialCutPatternColors?.GetValueOrDefault(materialId) ?? 0); + } + + internal double Coverage(double x, double y, double stepX, double stepY) + { + double uncovered = 1; + foreach (var (grid, cos, sin, period) in _grids) + { + double dx = x - grid.X, dy = y - grid.Y; + double perpendicular = -dx * sin + dy * cos; + double footprint = Math.Abs(sin) * stepX + Math.Abs(cos) * stepY; + if (grid.Segments is not { } segments) + { + // Integrate the parallel bands over the pixel's projected width, including subpixel grids. + double width = Math.Min(_width, grid.Spacing); + double InkLength(double p) + { + double bands = Math.Floor(p / grid.Spacing); + return bands * width + Math.Min(p - bands * grid.Spacing, width); + } + double edge = perpendicular + width / 2 - footprint / 2; + uncovered *= 1 - Math.Clamp((InkLength(edge + footprint) - InkLength(edge)) / footprint, 0, 1); + continue; + } + + double row = Math.Round(perpendicular / grid.Spacing); + double distance = perpendicular - row * grid.Spacing; + double lo = Math.Max(distance - footprint / 2, -_width / 2); + double hi = Math.Min(distance + footprint / 2, _width / 2); + if (hi <= lo) continue; + double phase = dx * cos + dy * sin - row * grid.Shift; + phase -= Math.Floor(phase / period) * period; + for (int i = 0; i < segments.Length; i++) + { + if (phase < segments[i]) + { + if (i % 2 == 0) uncovered *= 1 - (hi - lo) / footprint; + break; + } + phase -= segments[i]; + } + } + return 1 - uncovered; + } +} diff --git a/src/RvtIO/RvtFileReader.CircularAnnotations.cs b/src/RvtIO/RvtFileReader.CircularAnnotations.cs new file mode 100644 index 00000000..9a1fb626 --- /dev/null +++ b/src/RvtIO/RvtFileReader.CircularAnnotations.cs @@ -0,0 +1,124 @@ +using System.Text; +using System.Text.RegularExpressions; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO; + +public partial class RvtFileReader +{ + private static void ReadCircularAnnotations(RevitFileInfo info, ParsingState state, + IReadOnlyList frames) + { + var placed = info.Elements.Where(e => e.CategoryId == (int)BuiltInCategory.OST_GenericAnnotation + && e.OwnerViewId is > 0 && e.TypeId > 0 && e.RootClassName == "FamilyInstance").ToList(); + var keys = new Dictionary(); + foreach (int id in placed.Select(e => e.TypeId).Distinct()) + { + if (state.TitleBlockTexts.GetValueOrDefault((uint)id) is not { BlockCount: 1, Texts.Count: 1 } + || state.NativeParams.GetValueOrDefault((uint)id)?.Fields.GetValueOrDefault("1829:m_familyId") + is not (> 0 and int family)) continue; + if (state.NativeParams.GetValueOrDefault((uint)family)?.StringFields.GetValueOrDefault("1740:contentDoc") is { } key) + keys.Add(id, key); + } + if (keys.Count == 0) return; + + var members = keys.Values.Distinct().ToDictionary(key => key, + _ => new Dictionary(), StringComparer.Ordinal); + foreach (var frame in frames) + { + if (frame?.FamilyAnnotationItems is not { } items) continue; + foreach (var (key, item) in items) + { + if (item.Owner > int.MaxValue || !members.TryGetValue(key, out var group) + || group.ContainsKey((int)item.Owner)) continue; + var (data, start, _) = frame.Bytes(item); + group.Add((int)item.Owner, (data, start, BitConverter.ToUInt32(data, start + 8), + BitConverter.ToUInt16(data, start + 12))); + } + } + + var styles = new Dictionary(); + foreach (var (symbol, key) in keys) + { + var group = members[key]; + var regions = group.Values.Where(r => r.ClassId == 1860).ToArray(); + var curves = group.Values.Where(r => r.ClassId == 838).ToArray(); + var text = state.TitleBlockTexts[(uint)symbol].Texts![0]; + if (regions.Length != 1 || curves.Length != 1 || (text.Bx, text.By, text.Hx, text.Hy) != (1d, 0d, 0d, 1d)) + continue; + var region = regions[0]; + var fields = TfBlockDeserializer.ExtractParams(region.Data, region.Start, region.Size, region.ClassId)?.Fields; + if (fields == null || fields.GetValueOrDefault("1860:m_bMasking", -1) != 0 + || fields.GetValueOrDefault("1860:m_attrId") is not (> 0 and int attributeId) + || !group.TryGetValue(attributeId, out var attribute) || attribute.ClassId != 1862) continue; + var attr = TfBlockDeserializer.ExtractParams(attribute.Data, attribute.Start, attribute.Size, attribute.ClassId)?.Fields; + if (attr == null || attr.GetValueOrDefault("1862:m_backgroundPatternElemId") != -1 + || info.FillPatterns?.GetValueOrDefault(attr.GetValueOrDefault("1862:m_fillPatternElemId")).Grids is not { Count: 0 } + || attr.GetValueOrDefault("625:m_categoryId") is not (> 0 and int category)) continue; + + var curve = curves[0]; + if (TfBlockDeserializer.ReadFamilyAnnotationCurve(curve.Data, curve.Start, curve.Size) + is not { Arc: { } arc, TypeDependent: false, SketchId: > 0 } outline + || fields.GetValueOrDefault("1861:m_sketchId") != outline.SketchId + || Math.Abs(Math.Abs(arc.End - arc.Start) - 360) > 1e-6 + || info.GraphicsStylePens?.GetValueOrDefault(arc.StyleId) is not { PenNumber: > 0, LinePatternId: -3000010 } border + || border.Color is < 0 or > 0xFFFFFF + || RtfText.Parse(text.Rtf, 0, text.Rtf.Length) is not { Text.Length: > 0, FontSizePoints: > 0 and <= 200 } caption + || !TryCircularAnnotationTextStyle(text.Rtf, out int ink, out bool bold)) continue; + + var fills = new List(); + foreach (var style in group.Values.Where(m => m.ClassId == 2050)) + if (TfBlockDeserializer.TryExtractGraphicsStyleFull(style.Data, style.Start, style.Size, style.ClassId, + out int styleCategory, out _, out int type, out _, out int color, out _, out _) + && styleCategory == category && type == 1 && color is >= 0 and <= 0xFFFFFF) + fills.Add(color); + if (fills is [int fill]) + styles.Add(symbol, new(arc, fill, border.Color, border.PenNumber, + text, caption.Text, caption.FontSizePoints.Value, ink, bold)); + } + + var annotations = new Dictionary>(); + foreach (var element in placed) + { + int view = element.OwnerViewId!.Value; + if (!styles.TryGetValue(element.TypeId, out var style) + || info.ViewHiddenElements?.GetValueOrDefault(view)?.Contains(element.Id) == true + || !state.ComputedFamilySymbols.TryGetValue((uint)element.Id, out var instance) + || instance is not { BlockCount: 1, Symbol: { Transform: { Length: 12 } transform } computed } + || computed.SymbolId != element.TypeId) continue; + if (!annotations.TryGetValue(view, out var list)) annotations.Add(view, list = []); + list.Add(new(transform, style)); + } + info.CircularAnnotations = annotations; + } + + private static bool TryCircularAnnotationTextStyle(byte[] rtf, out int color, out bool bold) + { + color = 0; + bold = false; + // shortcut: a single horizontal run, extend when filled-region families need richer text. + string text = Encoding.ASCII.GetString(rtf); + var run = Regex.Match(text, + @"\\pard(?