Compare commits

...

21 Commits

Author SHA1 Message Date
Petru Conduraru c424d1b480 ifcgeom: resolve default materials through the schema supertype chain (#473)
get_default_style did an exact-name map lookup, so subtypes like
IfcWallStandardCase or IfcSlabStandardCase never inherited the default
material of their parent type, falling through to the generic grey
DefaultMaterial instead. This was reported in 2018 (#473) and the fix
direction (walk up the supertype chain once the schema runtime made
supertypes available) was agreed there, but never implemented.

On an exact-match miss the lookup now walks decl->supertype() until a
mapped ancestor is found, caching the result under the leaf name for
O(1) subsequent lookups. The product's user-facing type string is
deliberately untouched; only the style lookup gained inheritance.
Applies equally to the built-in defaults and --default-material-file.

This change was written with AI assistance.
2026-07-21 17:43:06 +03:00
Ryan Schultz e52e5e2e58 Bonsai: add category-level select-all to the Drawings list (#8826)
Add an "Is Selected" checkbox to each target-view category header in
BIM_UL_drawinglist that toggles selection for all drawings in the
category. The toggle only affects drawings currently visible in the
list (honoring the show_drawings_on_sheets_only filter), and the header
checkbox reflects the aggregate selection state of its drawings.

Also make category headers more obvious: wrap them in a box() for a
distinct inset background and make the header name clickable to
expand/contract the category (same as the disclosure triangle).

Ref: #8825

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 20:39:22 -05:00
Ryan Schultz 2d59ea1988 Bonsai: add toggle to show only drawings placed on sheets (#8824)
Adds a "Show Only Drawings on Sheets" toggle below the drawing list. When
enabled, the list is filtered to drawings referenced by at least one sheet
(target-view headers with no sheeted drawings are hidden too), and
bim.select_all_drawings only acts on the visible/filtered drawings.

A drawing is considered sheeted when its drawing document Location matches a
document reference Location on any SHEET-scoped IfcDocumentInformation.
Filtering is computed live so it reflects sheet edits without reloading.

Closes #8823

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 19:03:56 -05:00
Petru Conduraru 55a2430d71 docs: cover the Blender 5.1 / Python 3.13 transition in installation guides (#8781)
* docs: cover the Blender 5.1 / Python 3.13 transition in installation guides

The system requirements still listed Blender 4.3-4.5 with Python 3.11
only, and nothing documented the pitfall from issue 7623: importing
preferences into a Blender whose Python version changed carries over an
incompatible Bonsai build that silently fails to load. Document the two
Python generations, that Get Extensions picks the matching build
automatically while manual zip installs do not, and the
uninstall-reinstall step that resolves the upgrade case.

Generated with the assistance of an AI coding tool.

* docs: keep it simple, only Blender 5.1 and 5.2 with Python 3.13

Per review, drop the descriptive text and the Python 3.11 line.

Generated with the assistance of an AI coding tool.
2026-07-20 16:27:51 +10:00
Petru Conduraru 04a2535a98 Preserve the real cause when the ifcopenshell wrapper fails to load (#8785)
* Keep real cause in wrapper ImportError

When the compiled wrapper exists for the current interpreter but fails
to load (for example a glibc version mismatch, as on AWS Lambda in
issue 5927), the bare except rewrote the error into the misleading
"IfcOpenShell not built for '<platform>'" message. Environments such
as AWS Lambda or the Blender add-on dialog only surface the final
exception message, so the actual cause was invisible and undiagnosable.

Keep the "not built for" message only when no matching binary is
present, and otherwise include the original loader error, chaining the
cause in both branches.

This change was AI-generated.

Fixes #5927

* Simplify wrapper import failure to a single message

Per review feedback, drop the filesystem scan and the two message
variants. Always raise the classic "IfcOpenShell not built for
'<platform>'" message with the original exception appended in
parentheses, still chained as the cause. Environments that only show
the final exception message (AWS Lambda, the Blender add-on dialog)
now surface the real loader error, such as the glibc version mismatch
in issue 5927, without any extra logic.

This change was AI-generated.
2026-07-20 16:27:22 +10:00
Petru Conduraru 727b5f3475 Bonsai: add Hour zoom level to the interactive Gantt chart
The jsGantt-improved library that renders Bonsai's Gantt chart already
ships full support for an "Hour" granularity (column width, header
labels in every bundled language, hour-aware rendering math). Bonsai's
config only exposed Day/Week/Month/Quarter, with a comment claiming
Hour caused browser issues even with vUseSingleCell enabled.

Headless Chrome testing against the same library version shows that
claim no longer holds once vUseSingleCell is active (as Bonsai already
configures it at 10000): Hour-format charts render without errors from
typical schedules up through fairly extreme ones (5000 tasks across a
3 year span rendered in about 2.4s). The failure mode the old comment
described only reproduces with vUseSingleCell disabled, which is not
how Bonsai runs it.

Task start/finish times already flow through to the chart unmodified
as raw ISO datetimes (tool/sequence.py create_new_task_json), so any
schedule authored with real hour-level timestamps, for example an
imported MS Project/P6/Excel schedule or one written directly through
ifcopenshell-python, can now be viewed at hour granularity. Verified
live with a night shift schedule crossing midnight, rendered correctly
with no console errors.

Note: Bonsai's own "Edit Task Time" UI currently always snaps
ScheduleStart/ScheduleFinish to 09:00/17:00 regardless of the hour
entered (ifcopenshell/api/sequence/edit_task_time.py), and work
calendars only encode working days, not working hours. So authoring a
genuine hour-precision schedule through that UI is still not possible;
this change only unlocks viewing hour-level data that already exists
in the model. Fixing the editor and calendar model is a separate,
larger design decision for a maintainer.

Addresses #2772.

Generated with the assistance of an AI coding tool.
2026-07-20 10:19:42 +10:00
Bartok a45f2fae61 docs(ifc2ca): fix script paths in README
Point scriptSalome.py at templates/salome/ and the bonded scripts at
_deprecated/, matching the current tree so README links resolve.

Generated with the assistance of an AI coding tool.
2026-07-20 09:53:35 +10:00
dependabot[bot] 1ae50b8cce build(deps): bump ruff from 0.15.12 to 0.15.22 (#8212)
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.20
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-20 09:52:46 +10:00
dependabot[bot] 9fda996ebe build(deps): bump ruff from 0.15.12 to 0.15.22 (#8497)
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.21
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-20 09:52:38 +10:00
dependabot[bot] 7a7a250942 build(deps): bump ruff from 0.15.12 to 0.15.22
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.22
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-20 09:52:07 +10:00
Petru Conduraru bc1fb2a88d Bonsai: add one click copy of annotations to another drawing (#8719)
* Bonsai: move annotations between drawings when reassigning their group

Assigning an IfcAnnotation to a group that represents another drawing
previously left the annotation in both drawings at once: it stayed in
its old drawing group, its Blender object stayed in the old drawing
collection, and it kept the old camera depth, so the reassignment
appeared to do nothing useful. Issue #2966 documents the seven step
manual workaround users needed instead.

The assign group operator now detects when the target group represents
a drawing (via the new tool.Drawing.get_group_drawing, the inverse of
get_drawing_group), unassigns the annotation from its previous drawing
group, moves its object into the new drawing collection, and places it
on the new drawing camera plane. The target camera is imported on
demand when it has not been loaded yet, matching the pattern used by
the activate drawing operator.

Generated with the assistance of an AI coding tool.

* Bonsai: add one click copy of annotations to another drawing (#2966)

Duplicating an annotation into a different drawing used to require a
seven step manual process: loading groups in scene properties, copying
the object, fixing its group assignment by hand, and repositioning it
onto the target camera plane. A plain Blender duplicate is not enough
because the copy keeps pointing at the same IFC entity, and the Shift D
override, while it does create a genuine new entity through
root.copy_class, leaves the duplicate in the source drawing group,
collection, and camera depth.

The new copy annotation to drawing operator packages the proven recipe
already used by duplicate drawing into one action: duplicate through
tool.Geometry.duplicate_ifc_objects, unassign the copy from the source
drawing group, assign it to the chosen target group, place it on the
target camera plane at the same world XY, and file it into the target
drawing collection. The originals are left untouched and the user's
selection is restored. The target camera is imported on demand when it
has not been loaded yet.

The operator shows a target drawing dropdown and is reachable from the
annotation tool sidebar when an annotation is selected, and from the
drawings panel. Annotations already in the target drawing are skipped
and reported.

The orchestration lives in core.drawing.copy_annotations_to_drawing
with prophecy tests covering the copy, the skip, and the camera import
branches. Verified live in headless Blender 5.1: the copy is a new
IfcAnnotation with its own GlobalId and IfcTextLiteral, both texts are
editable independently, and everything survives save and reload with
each annotation loading in its own drawing.

Generated with the assistance of an AI coding tool.
2026-07-20 09:50:14 +10:00
Petru Conduraru c55a79b8b5 bonsai: allow overriding which classes join in section linework (#4395) (#8617)
Fixes #4395.

Root cause: the SVG cut-linework merge step that fuses adjacent
elements' cut polygons together (per the pset-driven JoinCriteria
setting) was hardcoded to only IfcWall and IfcSlab. IfcCovering cut
shapes were skipped unconditionally, so adjacent coverings never
joined, leaving a visible seam/broken corner in section drawings
regardless of JoinCriteria.

Fix: added an EPset_Drawing.JoinClasses property, following the
exact same user-overridable pattern already used by
EPset_Drawing.BringToFront - a comma-separated list of IFC classes
to join, defaulting to "IfcWall,IfcSlab" (unchanged behavior) when
unset. Users can override per-drawing to add IfcCovering (or any
other class) when they want it joined too. Kept this opt-in rather
than hardcoding IfcCovering into the default list, since joining a
thin finish layer the same way as a thick wall/slab could produce
unwanted mitring in some cases - the user decides per drawing.

Verified live against the reporter's own attached file
(ifcovering joining.ifc) and its cached section linework: with
JoinClasses unset, two separate closed paths reproduce the reported
seam exactly. With JoinClasses = "IfcWall,IfcSlab,IfcCovering", the
two coverings merge into a single closed polygon with the internal
seam removed. Confirmed IfcSlab join behavior is unchanged in both
runs.

Generated with the assistance of an AI coding tool.

Co-authored-by: Dion Moult <dionmoult@gmail.com>
2026-07-20 09:41:09 +10:00
sboddy b669baf793 Propagate deflection settings on reload (#8484)
reimport_element_representations() built a fresh
ifcopenshell.geom.settings() without copying deflection_tolerance /
angular_tolerance from the IfcImportSettings it had just
constructed, and never passed geometry_library to either the
iterator() or create_shape() calls it makes. As a result, exiting
Item/edit mode (which reaches this function via
switch_representation) silently fell back to IfcOpenShell's
hard-coded mesher defaults (0.001 linear deflection, ~50x finer than
the project's default of 0.05) and the default geometry kernel,
instead of the project's configured tolerance and Geometry Library.

This made geometry visibly change quality after a no-op Tab into and
back out of edit mode, since the reload path was unintentionally far
more precise (and used a different kernel) than the initial import.
Both settings, and geometry_library, are now taken from the
IfcImportSettings instance already built at the top of the function,
so a reload matches the original import.

Refs #5685.

Generated with the assistance of an AI coding tool.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-20 09:37:04 +10:00
Petru Conduraru 32ac20e8e3 Bonsai: refresh the arc/circle decorator immediately after duplicating a loop
theoryshaw's follow-up on #6944: after the profile/curve reconstruction fix
(previous commit), the arc/circle marker for a freshly Shift+D-duplicated
loop wouldn't appear until leaving and re-entering Edit Mode.

Root cause: ProfileDecorator groups arc/circle vertices purely by
IFCARCINDEX/IFCCIRCLE vertex-group index every draw call (it has no cache
to go stale, it fully recomputes from the live edit-mesh bmesh each frame).
Duplicating a loop copies its vertex-group weights onto the new geometry,
since Blender allocates no new group for a duplicate, so the source loop
and its live duplicate land in the same dict entry. That entry then fails
the "exactly 2 verts per circle / 3 per arc" check and is skipped entirely,
so BOTH the original and the duplicate stop being drawn until the mesh is
reimported and gets fresh, distinct groups.

Verified live in headless Blender: built a bmesh with an IFCCIRCLE loop and
an IFCARCINDEX loop, then ran bmesh.ops.duplicate on each (the same
bmesh-level operation underlying Shift+D) and called ProfileDecorator's
draw method directly. Before this change, duplicating either loop dropped
both the original and the duplicate from the decorator (0 circle/arc
batches drawn instead of 2). After, both draw immediately, with no change
to the non-duplicated case (still 1) or to genuinely distinct loops (5
independent circles still resolve to 5, not merged). 500-circle timing is
unchanged (~14.3ms/draw before and after), so the added connectivity split
is not a hot-path regression.

Added test/bim/module/model/test_profile_decorator_duplicate_loop.py
pinning the new _connected_components helper's behavior for single and
duplicated circle/arc loops.

This contribution was produced with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 0d5ea02169 Bonsai: fix the same duplicate-loop vertex-group bug in auto_detect_curves
auto_detect_profiles had the identical defect fixed in the previous
commit: duplicating a circle/arc loop in Edit Mode reuses the same
IFCCIRCLE/IFCARCINDEX vertex group index for the new geometry, and this
sibling function (used for curve/annotation editing rather than profile
voids) tallied group membership across the whole mesh instead of per
loop, so it also rejected a legitimately duplicated loop as malformed.

Applied the identical fix: scope the group-count sanity check to each
connected edge loop, computed after the loops are built rather than in
the initial whole-mesh vertex pass. Kept the existing forked-loop check
(more than 2 edges per vertex) in the first pass since it is unrelated
to group counting.

Verified live in headless Blender: constructed two 2-vertex IFCCIRCLE
loops sharing one vertex group index (the exact state Blender's Edit
Mode duplicate produces) and called auto_detect_curves directly.
Before this change it returned (False, "CIRCLE"); after, it returns two
valid IfcCircle curves.

Generated with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 0a027d47a3 Bonsai: fix profile reconstruction after duplicating a circle/arc in Edit Mode
Duplicating a circular or filleted-arc void in the profile CAD editor
(Shift+D on the loop's vertices) reused the same IFCCIRCLE/IFCARCINDEX
vertex group index for the new geometry, since Blender's mesh duplicate
copies vertex group weights but does not allocate a new group. On exit
from Edit Mode, auto_detect_profiles tallied group membership across the
whole mesh rather than per loop, so a group meant to hold exactly 2 (circle)
or 3 (arc) vertices ended up with double that, failing its sanity check
and blocking the edit with an "INVALID PROFILE" popup. Fixes #6944.

Scope the sanity check to each connected edge loop instead, matching how
the loops are actually converted into IfcCircle/arc segments below. Also
explicitly reject an arc/circle vertex tagged onto an isolated vertex with
no edges at all, which the old whole-mesh count also caught.

Verified live in headless Blender against the issue's repro file
(IfcFurniture "Slab.004", IfcArbitraryProfileDefWithVoids with three
IfcCircle voids): entering the profile editor, duplicating one void's
2-vertex loop and moving it produced an "INVALID PROFILE" popup before
this change, and now produces a valid profile (the original 3 voids
intact, plus the duplicate as a 4th void or a separate solid profile
depending on whether it still falls inside the outer boundary).
test/tool/test_model.py passes unchanged (32 passed, 1 pre-existing
unrelated failure present on both before and after).

Generated with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 6014bbd877 ci-lint: black-format two files that drifted on v0.8.0
Both files were merged unformatted and fail the Black formatter step
on every branch, keeping ci-lint red repo-wide.

Generated with the assistance of an AI coding tool.
2026-07-20 09:24:34 +10:00
Petru Conduraru 6d6d92b849 Fix all remaining ty type-check failures on ci-lint
The ci-lint workflow's ty steps fail on every branch because base
v0.8.0 has four diagnostics.

ty check (bonsai):

- root/operator.py: bpy.data.objects.get() can return None, so
  UnlinkObject._execute could put None in its objects list and crash
  on the first attribute access when an unknown object name is passed.
  Handle the miss explicitly, which also satisfies the declared
  list[bpy.types.Object] type.
- tool/sequence.py: ty does not narrow Literal types through
  membership tests on list literals, so the assert_never() exhaustive
  check was flagged. Use tuple literals, which ty narrows, keeping the
  exhaustiveness check intact.

ty check (ios):

- draw.py: arrange_polygons was called through conditional argument
  splats that let the same call site work against pre-April-2026
  wrappers lacking arrange_polygon_settings and the logger parameter.
  No runtime bug for current builds, but the dynamic splats cannot be
  typed against the fixed 3-parameter signature. Drop the old-build
  workaround and call the current signature directly, following the
  precedent of 3d8115ebc5 which dropped similar old-build workarounds
  in ifcopenshell.file. Verified against a current wrapper build that
  the direct call arranges polygons and serializes to SVG, with and
  without a logger.
- Optimise.py: igraph is an optional dependency with a guarded import
  and a toposort fallback, but it was missing from the ios type-check
  venv so ty could not resolve it. Add it to type-check-requirements
  next to the toposort fallback that is already listed.

After this, poe ty-bonsai and poe ty-ios both pass cleanly.

Generated with the assistance of an AI coding tool.
2026-07-20 09:23:48 +10:00
Petru Conduraru bb49822f2e Bonsai: make dxf2ifc.py example script skip unsupported DXF entities
The script called Polyline.get_mode() on every modelspace entity, but
that method only exists on POLYLINE entities, so any typical DXF
containing lines, circles or text crashed with AttributeError before
converting anything. Test for POLYLINE polyface meshes with
dxftype()/is_poly_face_mesh instead and skip other entities with a
message, only create the spatial containment relation when products
exist, and take the input/output paths from the command line (matching
obj2ifc.py) instead of a hardcoded input.dxf/test.ifc.

Fixes #2151

This change was written with the assistance of an AI coding tool.
2026-07-20 09:22:44 +10:00
Bruno Postle 21ea58b0e6 Fix Bonsai polyline not enough values to unpack error
Typo was introduced in b35f99e
2026-07-19 23:50:19 +01:00
Ryan Schultz b66d8b2c4d Fix #6652: Extend grab selection to include BBIM_Array members (#7968)
When grabbing an array child, the selection now expands to include
the array parent and all sibling children before the move operator
runs. Mirrors existing behavior for aggregates and nests.

Generated with the assistance of an AI coding tool.
2026-07-19 14:00:44 -05:00
36 changed files with 742 additions and 88 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
black==26.3.1
ruff==0.15.12
ruff==0.15.22
poethepoet
ty==0.0.61
gersemi==0.26.1
@@ -5,7 +5,7 @@ FILE_NAME('EPset_Drawing.ifc','2020-01-01T00:00:00',$,$,'EPset_Drawing','EPset_D
FILE_SCHEMA(('IFC4'));
ENDSEC;
DATA;
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2,#31,#32,#33,#34,#35,#36));
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2,#31,#32,#33,#34,#35,#36,#37));
#2=IFCSIMPLEPROPERTYTEMPLATE('23JavTMk98ZxXhrUEnjAcf',$,'TargetView','',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
#3=IFCSIMPLEPROPERTYTEMPLATE('1yVWUt5H9DAOuu0OaMMLpe',$,'Scale','The scale of this drawing represented as a numerator and denominator, such as 1/100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
#4=IFCSIMPLEPROPERTYTEMPLATE('3gsuPBtU93b8f0gg1pjkq6',$,'HumanScale','The scale of this drawing in human readable format, such as 1:100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
@@ -41,5 +41,6 @@ DATA;
#34=IFCSIMPLEPROPERTYTEMPLATE('2epSGfC4bFM9gb1X7zBIp4',$,'RenderSharp','Whether to render ''sharp'' (convex) edges. Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#35=IFCSIMPLEPROPERTYTEMPLATE('3TZwsEjkr5WRDKcgrYzSIA',$,'RidgeAngleMinDegrees','Minimum convex dihedral deviation from flat, in degrees, for a projection edge to be classified as ''sharp'' rather than ''flush''.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
#36=IFCSIMPLEPROPERTYTEMPLATE('2Jua$lO754vgZOkBoHM2gA',$,'RenderFlush','Whether to render ''flush'' edges (dihedral deviation below both ridge/valley thresholds). Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#37=IFCSIMPLEPROPERTYTEMPLATE('1zM9sia2L8RQDnWZxgUwlZ',$,'JoinClasses','Comma separated list of IFC classes whose cut linework will be joined together when they meet (e.g. mitred at a corner).\X2\000A\X0\Defaults to ''IfcWall,IfcSlab'' if not set. Override to also join other classes, such as ''IfcWall,IfcSlab,IfcCovering''.',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
ENDSEC;
END-ISO-10303-21;
@@ -244,7 +244,7 @@ function addGanttElement(blenderId, tasks, workSched, filename) {
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
vFormatArr: ["Day", "Week", "Month", "Quarter"], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
vFormatArr: ["Hour", "Day", "Week", "Month", "Quarter"], // vUseSingleCell keeps Hour usable on large charts.
vShowRes: true, // Disable the resource column.
vShowComp: false, // Disable the completion column.
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
@@ -47,6 +47,7 @@ classes = (
operator.CleanWireframes,
operator.ContractSheet,
operator.ConvertSVGToDXF,
operator.CopyAnnotationToDrawing,
operator.CopyTextToSelection,
operator.CreateDrawing,
operator.CreateSheets,
@@ -107,6 +108,7 @@ classes = (
operator.SelectAssignedProduct,
operator.SelectSimilarTextLiteralValue,
operator.ToggleTargetView,
operator.ToggleDrawingCategorySelection,
operator.OpenDocumentationWebUi,
operator.FilterSelectedObjectsIfIntersectedByCamera,
prop.Variable,
@@ -228,6 +228,90 @@ class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
)
def get_copy_annotation_target_drawings(self, context):
global COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
drawings = [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]
drawings.sort(key=lambda d: d.Name or "")
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = [(str(d.id()), d.Name or "Unnamed", "") for d in drawings]
return COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = []
class CopyAnnotationToDrawing(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.copy_annotation_to_drawing"
bl_label = "Copy Annotation To Drawing"
bl_description = (
"Copy the selected annotations to another drawing.\n\n"
"The copies become independent annotations assigned to the chosen drawing, "
"placed in its view plane. The originals stay in their current drawing"
)
bl_options = {"REGISTER", "UNDO"}
target_drawing: bpy.props.EnumProperty(name="Target Drawing", items=get_copy_annotation_target_drawings)
if TYPE_CHECKING:
target_drawing: str
@classmethod
def poll(cls, context):
if not tool.Ifc.get():
cls.poll_message_set("No IFC project loaded.")
return False
if not cls.get_selected_annotations(context):
cls.poll_message_set("No annotation selected.")
return False
return True
@classmethod
def get_selected_annotations(cls, context) -> list[ifcopenshell.entity_instance]:
return [
element
for obj in context.selected_objects
if (element := tool.Ifc.get_entity(obj))
and element.is_a("IfcAnnotation")
and element.ObjectType != "DRAWING"
]
def invoke(self, context, event):
assert context.window_manager
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
assert self.layout
row = self.layout.row()
row.prop(self, "target_drawing")
def _execute(self, context):
if not self.target_drawing:
self.report({"ERROR"}, "No target drawing selected.")
return {"CANCELLED"}
target_drawing = tool.Ifc.get().by_id(int(self.target_drawing))
annotations = self.get_selected_annotations(context)
previous_selection = [obj for a in annotations if (obj := tool.Ifc.get_object(a))]
previous_active = context.view_layer.objects.active
copied = core.copy_annotations_to_drawing(
tool.Ifc,
tool.Collector,
tool.Drawing,
tool.Geometry,
annotations=annotations,
target_drawing=target_drawing,
)
for obj in context.selected_objects:
obj.select_set(False)
for obj in previous_selection:
if obj.name in context.view_layer.objects:
obj.select_set(True)
if previous_active and previous_active.name in context.view_layer.objects:
context.view_layer.objects.active = previous_active
skipped = len(annotations) - len(copied)
message = f"Copied {len(copied)} annotations to {target_drawing.Name or 'Unnamed'}."
if skipped:
message += f" Skipped {skipped} already in that drawing."
self.report({"INFO"}, message)
class CreateDrawing(bpy.types.Operator):
"""Creates/refreshes a .svg drawing
@@ -1471,6 +1555,15 @@ class CreateDrawing(bpy.types.Operator):
"Material.Name",
]
join_classes = ifcopenshell.util.element.get_pset(self.camera_element, "EPset_Drawing", "JoinClasses")
if join_classes:
join_classes = tuple(c.strip() for c in join_classes.split(",") if c.strip())
else:
# Architectural convention only merges these objects by default. E.g. pipe
# segments and fittings shouldn't merge. Users may override this per-drawing
# via the EPset_Drawing.JoinClasses property (e.g. to also join IfcCovering).
join_classes = ("IfcWall", "IfcSlab")
group = root.find("{http://www.w3.org/2000/svg}g")
joined_paths = {}
self.is_manifold_cache = {}
@@ -1572,8 +1665,7 @@ class CreateDrawing(bpy.types.Operator):
)
path.attrib["d"] = d
# Architectural convention only merges these objects. E.g. pipe segments and fittings shouldn't merge.
if not element.is_a("IfcWall") and not element.is_a("IfcSlab"):
if not any(element.is_a(c) for c in join_classes):
continue
keys = []
@@ -2218,7 +2310,11 @@ class SelectAllDrawings(bpy.types.Operator):
def execute(self, context):
props = tool.Drawing.get_document_props()
# When filtering to sheeted drawings only, act on the visible drawings only.
sheeted_ids = tool.Drawing.get_sheeted_drawing_ids() if props.show_drawings_on_sheets_only else None
for drawing in props.drawings:
if sheeted_ids is not None and drawing.is_drawing and drawing.ifc_definition_id not in sheeted_ids:
continue
if drawing.is_selected != self.select_all:
drawing.is_selected = self.select_all
return {"FINISHED"}
@@ -3778,6 +3874,26 @@ class ToggleTargetView(bpy.types.Operator):
return {"FINISHED"}
class ToggleDrawingCategorySelection(bpy.types.Operator):
bl_idname = "bim.toggle_drawing_category_selection"
bl_label = "Toggle Category Selection"
bl_description = "Select or deselect all drawings in this view category"
bl_options = {"REGISTER", "UNDO"}
target_view: bpy.props.StringProperty()
if TYPE_CHECKING:
target_view: str
def execute(self, context):
drawings = tool.Drawing.get_visible_drawings_in_category(self.target_view)
# If everything visible in the category is already selected, deselect all; otherwise select all.
new_state = not all(d.is_selected for d in drawings)
for drawing in drawings:
drawing.is_selected = new_state
return {"FINISHED"}
class ExpandSheet(bpy.types.Operator):
bl_idname = "bim.expand_sheet"
bl_label = "Expand Sheet"
@@ -409,6 +409,12 @@ class DocProperties(PropertyGroup):
options=set(),
)
is_editing_drawings: BoolProperty(name="Is Editing Drawings", default=False)
show_drawings_on_sheets_only: BoolProperty(
name="Show Only Drawings on Sheets",
description="Only show drawings that are placed on a sheet",
default=False,
options=set(),
)
is_editing_schedules: BoolProperty(name="Is Editing Schedules", default=False)
is_editing_references: BoolProperty(name="Is Editing References", default=False)
target_view: EnumProperty(
@@ -439,6 +445,7 @@ class DocProperties(PropertyGroup):
should_use_annotation_cache: bool
should_draw_linked_projects: bool
is_editing_drawings: bool
show_drawings_on_sheets_only: bool
is_editing_schedules: bool
is_editing_references: bool
target_view: Literal["PLAN_VIEW", "ELEVATION_VIEW", "SECTION_VIEW", "REFLECTED_PLAN_VIEW", "MODEL_VIEW"]
+56 -2
View File
@@ -332,6 +332,8 @@ class BIM_PT_drawings(Panel):
row3.separator(factor=0.5, type="SPACE")
row3.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="")
row3.operator("bim.select_all_drawings", icon="CHECKBOX_HLT", text="")
row3.operator("bim.create_drawing", text="", icon="OUTPUT")
row3.operator("bim.convert_svg_to_dxf", text="", icon="SEQ_PREVIEW").view = active_drawing.name
@@ -339,6 +341,7 @@ class BIM_PT_drawings(Panel):
self.layout.template_list(
"BIM_UL_drawinglist", "", self.props, "drawings", self.props, "active_drawing_index"
)
self.layout.prop(self.props, "show_drawings_on_sheets_only")
class BIM_PT_schedules(Panel):
@@ -871,8 +874,8 @@ class BIM_UL_drawinglist(bpy.types.UIList):
layout.label(text="", translate=False)
return
row = layout.row(align=True)
if item.is_drawing:
row = layout.row(align=True)
row.label(text="", icon="BLANK1")
selected_icon = "CHECKBOX_HLT" if item.is_selected else "CHECKBOX_DEHLT"
row.prop(item, "is_selected", text="", icon=selected_icon, emboss=False)
@@ -893,6 +896,9 @@ class BIM_UL_drawinglist(bpy.types.UIList):
item.ifc_definition_id
)
else:
# Give category headers a distinct inset background so they stand out from drawing rows.
box = layout.box()
row = box.row(align=True)
if item.target_view == "PLAN_VIEW":
icon = "UV_FACESEL"
elif item.target_view == "ELEVATION_VIEW":
@@ -913,7 +919,55 @@ class BIM_UL_drawinglist(bpy.types.UIList):
op = row.operator("bim.toggle_target_view", text="", emboss=False, icon="DISCLOSURE_TRI_RIGHT")
op.target_view = item.target_view
op.option = "EXPAND"
row.prop(item, "name", text="", icon=icon, emboss=False)
group = tool.Drawing.get_visible_drawings_in_category(item.target_view)
all_selected = bool(group) and all(d.is_selected for d in group)
row.operator(
"bim.toggle_drawing_category_selection",
text="",
icon="CHECKBOX_HLT" if all_selected else "CHECKBOX_DEHLT",
emboss=False,
).target_view = item.target_view
row.separator(factor=0.5, type="SPACE")
# Clicking the header name toggles expand/contract, same as the disclosure triangle.
op = row.operator("bim.toggle_target_view", text=item.name, icon=icon, emboss=False)
op.target_view = item.target_view
op.option = "CONTRACT" if item.is_expanded else "EXPAND"
def filter_items(self, context, data: DocProperties, propname: str):
drawings = getattr(data, propname)
helper_funcs = bpy.types.UI_UL_list
flt_flags = []
flt_neworder = []
if self.filter_name:
flt_flags = helper_funcs.filter_items_by_name(
self.filter_name,
self.bitflag_filter_item,
drawings,
"name",
reverse=self.use_filter_sort_reverse,
)
if not flt_flags:
flt_flags = [self.bitflag_filter_item] * len(drawings)
props = tool.Drawing.get_document_props()
if props.show_drawings_on_sheets_only:
ifc_file = tool.Ifc.get()
sheeted_ids = tool.Drawing.get_sheeted_drawing_ids()
# Target view headers are only shown if they contain a sheeted drawing.
sheeted_target_views = {
tool.Drawing.get_drawing_target_view(ifc_file.by_id(drawing_id)) for drawing_id in sheeted_ids
}
for i, item in enumerate(drawings):
if item.is_drawing:
is_visible = item.ifc_definition_id in sheeted_ids
else:
is_visible = item.target_view in sheeted_target_views
if not is_visible:
flt_flags[i] &= ~self.bitflag_filter_item
return flt_flags, flt_neworder
class BIM_UL_sheets(bpy.types.UIList):
@@ -225,6 +225,9 @@ class AnnotationToolUI:
def draw_edit_object_interface(cls, context):
if DecoratorData.get_text_data(bpy.context.active_object):
add_layout_hotkey_operator(cls.layout, "Edit Text", "S_E", "")
if bpy.ops.bim.copy_annotation_to_drawing.poll():
row = cls.layout.row(align=True)
row.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="Copy To Drawing")
@classmethod
def draw_type_selection_interface(cls):
@@ -4124,6 +4124,31 @@ class OverrideMoveSelect(bpy.types.Operator):
self.new_active_obj = obj
return {"FINISHED"}
# Get arrays
ifc_file = tool.Ifc.get()
array_parents_to_move: list[bpy.types.Object] = []
for obj in list(context.selected_objects):
element = tool.Ifc.get_entity(obj)
if not element:
continue
pset = ifcopenshell.util.element.get_pset(element, "BBIM_Array")
if not pset:
continue
parent_element = ifc_file.by_guid(pset["Parent"])
parent_obj = tool.Ifc.get_object(parent_element)
if parent_obj not in array_parents_to_move:
array_parents_to_move.append(parent_obj)
if element.GlobalId != pset["Parent"]:
obj.select_set(False)
if array_parents_to_move:
for parent_obj in array_parents_to_move:
parent_element = tool.Ifc.get_entity(parent_obj)
for array_obj in tool.Array.get_all_objects(parent_element):
array_obj.select_set(True)
self.new_active_obj = parent_obj
return {"FINISHED"}
# Get nests
props = tool.Nest.get_nest_props()
not_editing_objs = [o.obj for o in props.not_editing_objects]
+39 -1
View File
@@ -163,14 +163,52 @@ class AssignGroup(bpy.types.Operator, tool.Ifc.Operator):
def _execute(self, context):
if not self.is_assigning:
return bpy.ops.bim.unassign_group(group=self.group)
ifc_file = tool.Ifc.get()
group = ifc_file.by_id(self.group)
products = [
element
for o in tool.Blender.get_selected_objects(include_active=False)
if (element := tool.Ifc.get_entity(o))
]
ifcopenshell.api.group.assign_group(tool.Ifc.get(), products=products, group=tool.Ifc.get().by_id(self.group))
relocated_annotations = self.unassign_from_previous_drawing(ifc_file, group, products)
ifcopenshell.api.group.assign_group(ifc_file, products=products, group=group)
self.relocate_annotations_to_drawing(relocated_annotations, group)
self.report({"INFO"}, f"Assigned {len(products)} objects to group.")
def unassign_from_previous_drawing(self, ifc_file, group, products) -> list[ifcopenshell.entity_instance]:
"""Assigning an annotation to a group that represents a drawing means the
annotation should belong to that drawing only, so it needs to leave
whichever drawing it was previously part of, instead of ending up
visible in both at once.
"""
new_drawing = tool.Drawing.get_group_drawing(group)
if not new_drawing:
return []
relocated = []
for product in products:
if not product.is_a("IfcAnnotation") or product.ObjectType == "DRAWING":
continue
old_drawing = tool.Drawing.get_annotation_drawing(product)
if not old_drawing or old_drawing.id() == new_drawing.id():
continue
if old_group := tool.Drawing.get_drawing_group(old_drawing):
ifcopenshell.api.group.unassign_group(ifc_file, products=[product], group=old_group)
relocated.append(product)
return relocated
def relocate_annotations_to_drawing(self, products, group) -> None:
"""Move the relocated annotations into the new drawing's collection and
depth, now that they have actually been assigned to its group.
"""
if not products:
return
new_drawing = tool.Drawing.get_group_drawing(group)
new_camera = tool.Ifc.get_object(new_drawing) or tool.Drawing.import_drawing(new_drawing)
for product in products:
if obj := tool.Ifc.get_object(product):
tool.Drawing.ensure_annotation_in_drawing_plane(obj, camera=new_camera)
tool.Collector.assign(obj)
class UnassignGroup(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.unassign_group"
@@ -93,6 +93,30 @@ def _stroke_lines_alpha(
gpu.state.blend_set("NONE")
def _connected_components(
vertex_groups: dict[int, list[bmesh.types.BMVert]],
) -> list[list[bmesh.types.BMVert]]:
"""Split each vertex group's members into their connected components,
since a duplicated arc/circle loop shares its source loop's group index."""
components = []
for verts in vertex_groups.values():
remaining = set(verts)
while remaining:
seed = remaining.pop()
stack = [seed]
component = [seed]
while stack:
v = stack.pop()
for edge in v.link_edges:
other = edge.other_vert(v)
if other in remaining:
remaining.discard(other)
stack.append(other)
component.append(other)
components.append(component)
return components
class ProfileDecorator:
installed = None
@@ -265,7 +289,7 @@ class ProfileDecorator:
# Draw arcs
arc_centroids = []
arc_segments = []
for arc in arcs.values():
for arc in _connected_components(arcs):
if len(arc) != 3:
continue
sorted_arc = [None, None, None]
@@ -292,7 +316,7 @@ class ProfileDecorator:
# Draw circles
circle_centroids = []
circle_segments = []
for circle in circles.values():
for circle in _connected_components(circles):
if len(circle) != 2:
continue
p1 = obj.matrix_world @ circle[0].co
@@ -413,12 +413,13 @@ class UnlinkObject(bpy.types.Operator, tool.Ifc.Operator):
skip_invoke: bpy.props.BoolProperty(default=False, options={"SKIP_SAVE"})
def _execute(self, context):
objects: list[bpy.types.Object]
if self.obj:
objects = [bpy.data.objects.get(self.obj)]
requested_obj = bpy.data.objects.get(self.obj)
objects = [requested_obj] if requested_obj is not None else []
else:
objects = context.selected_objects
objects: list[bpy.types.Object]
for obj in objects:
was_active_object = obj == context.active_object
@@ -12,7 +12,7 @@ function create_gantt_chart(json_data) {
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
vFormatArr: ['Day', 'Week', 'Month', 'Quarter'], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
vFormatArr: ['Hour', 'Day', 'Week', 'Month', 'Quarter'], // vUseSingleCell keeps Hour usable on large charts.
vShowRes: true, // Disable the resource column.
vShowComp: false, // Disable the completion column.
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
@@ -117,9 +117,7 @@ class UnassignType(bpy.types.Operator, tool.Ifc.Operator):
related_object: str
@staticmethod
def _reattach_styles(
file: ifcopenshell.file, copied_entities: dict[int, ifcopenshell.entity_instance]
) -> None:
def _reattach_styles(file: ifcopenshell.file, copied_entities: dict[int, ifcopenshell.entity_instance]) -> None:
"""copy_deep only follows forward references, so IfcStyledItem (an inverse,
``StyledByItem``) is not carried onto the copied geometry. Re-create a
styled item on each copy that points at the same presentation styles as
+31
View File
@@ -411,6 +411,37 @@ def duplicate_drawing(
return new_drawing
def copy_annotations_to_drawing(
ifc: type[tool.Ifc],
collector: type[tool.Collector],
drawing_tool: type[tool.Drawing],
geometry: type[tool.Geometry],
annotations: list[ifcopenshell.entity_instance],
target_drawing: ifcopenshell.entity_instance,
) -> list[ifcopenshell.entity_instance]:
"""Duplicate annotations into another drawing, leaving the originals untouched."""
target_group = drawing_tool.get_drawing_group(target_drawing)
if not target_group:
return []
annotations = [a for a in annotations if drawing_tool.get_annotation_drawing(a) != target_drawing]
annotation_objs = [obj for a in annotations if (obj := ifc.get_object(a))]
if not annotation_objs:
return []
camera = ifc.get_object(target_drawing) or drawing_tool.import_drawing(target_drawing)
old_to_new, _ = geometry.duplicate_ifc_objects(annotation_objs)
copied: list[ifcopenshell.entity_instance] = []
for new_elements in old_to_new.values():
for new_element in new_elements:
if old_group := drawing_tool.get_drawing_group(new_element):
ifc.run("group.unassign_group", group=old_group, products=[new_element])
ifc.run("group.assign_group", group=target_group, products=[new_element])
new_obj = ifc.get_object(new_element)
drawing_tool.ensure_annotation_in_drawing_plane(new_obj, camera)
collector.assign(new_obj, should_clean_users_collection=True)
copied.append(new_element)
return copied
def remove_drawing(
ifc: type[tool.Ifc], drawing_tool: type[tool.Drawing], drawing: ifcopenshell.entity_instance
) -> None:
+4
View File
@@ -354,6 +354,7 @@ class Drawing:
def enable_editing_schedules(cls): pass
def enable_editing_sheets(cls): pass
def enable_editing_text(cls, obj): pass
def ensure_annotation_in_drawing_plane(cls, obj, camera=None): pass
def ensure_drawings_parent_document(cls): pass
def ensure_drawings_parent_group(cls): pass
def ensure_unique_drawing_name(cls, name): pass
@@ -367,6 +368,7 @@ class Drawing:
def generate_reference_attributes(cls, reference, **attributes): pass
def generate_sheet_identification(cls): pass
def get_annotation_context(cls, target_view, object_type=None): pass
def get_annotation_drawing(cls, element): pass
def get_annotation_representation(cls, element_type): pass
def get_assigned_product(cls, element): pass
def get_assigned_product_workaround(cls, element): pass
@@ -384,6 +386,7 @@ class Drawing:
def get_drawing_group(cls, drawing): pass
def get_drawing_references(cls, drawing): pass
def get_drawing_target_view(cls, drawing): pass
def get_group_drawing(cls, group): pass
def get_group_elements(cls, group): pass
def get_ifc_representation_class(cls, object_type): pass
def get_name(cls, element): pass
@@ -397,6 +400,7 @@ class Drawing:
def get_unit_system(cls): pass
def import_assigned_product(cls, obj): pass
def import_documents(cls, document_type): pass
def import_drawing(cls, drawing): pass
def import_drawings(cls): pass
def import_sheets(cls): pass
def import_text_attributes(cls, obj): pass
+55
View File
@@ -756,6 +756,17 @@ class Drawing(bonsai.core.tool.Drawing):
if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup.ObjectType == "DRAWING":
return rel.RelatingGroup
@classmethod
def get_group_drawing(cls, group: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
"""Get the drawing that owns this group, if the group represents a drawing."""
if group.ObjectType != "DRAWING":
return None
for rel in group.IsGroupedBy or []:
for related_object in rel.RelatedObjects:
if related_object.is_a("IfcAnnotation") and related_object.ObjectType == "DRAWING":
return related_object
return None
@classmethod
def get_drawing_document(cls, drawing: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
for rel in drawing.HasAssociations:
@@ -2876,6 +2887,50 @@ class Drawing(bonsai.core.tool.Drawing):
break
return sheet_references
@classmethod
def get_sheeted_drawing_ids(cls) -> set[int]:
"""Get the IFC ids of all drawings that are placed on at least one sheet."""
ifc_file = tool.Ifc.get()
sheet_locations: set[Union[str, None]] = set()
for sheet in ifc_file.by_type("IfcDocumentInformation"):
if sheet.Scope != "SHEET":
continue
for reference in cls.get_document_references(sheet):
sheet_locations.add(reference.Location)
if not sheet_locations:
return set()
result: set[int] = set()
for drawing in ifc_file.by_type("IfcAnnotation"):
if drawing.ObjectType != "DRAWING":
continue
drawing_document = cls.get_drawing_document(drawing)
if drawing_document and drawing_document.Location in sheet_locations:
result.add(drawing.id())
return result
@classmethod
def get_visible_drawings_in_category(cls, target_view: str) -> list[DrawingProperties]:
"""Get the drawing items in a target view category that are currently visible in the drawing list.
Grouping is positional: individual drawing items don't carry their own ``target_view``, they belong to
the most recent header item above them. Only expanded categories contribute drawing items to the
collection, so a collapsed category yields an empty list. Respects the ``show_drawings_on_sheets_only``
filter so that select-all only affects visible drawings.
"""
props = cls.get_document_props()
drawings: list[DrawingProperties] = []
in_category = False
for item in props.drawings:
if not item.is_drawing:
# Header row: we're inside the requested category until the next header.
in_category = item.target_view == target_view
elif in_category:
drawings.append(item)
if props.show_drawings_on_sheets_only:
sheeted_ids = cls.get_sheeted_drawing_ids()
drawings = [d for d in drawings if d.ifc_definition_id in sheeted_ids]
return drawings
@classmethod
def get_camera_matrix(cls, camera: bpy.types.Object) -> Matrix:
matrix_world = camera.matrix_world.copy().normalized()
+11 -2
View File
@@ -1151,6 +1151,9 @@ class Geometry(bonsai.core.tool.Geometry):
settings.set("layerset-first", True)
settings.set("keep-bounding-boxes", True)
settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS)
settings.set("mesher-linear-deflection", ifc_import_settings.deflection_tolerance)
settings.set("mesher-angular-deflection", ifc_import_settings.angular_tolerance)
geometry_library = ifc_import_settings.geometry_library
ifc_importer = bonsai.bim.import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = tool.Ifc.get()
@@ -1162,7 +1165,11 @@ class Geometry(bonsai.core.tool.Geometry):
shape = None
if elements:
iterator = ifcopenshell.geom.iterator(
settings, tool.Ifc.get(), multiprocessing.cpu_count(), include=elements
settings,
tool.Ifc.get(),
multiprocessing.cpu_count(),
include=elements,
geometry_library=geometry_library,
)
else:
iterator = None # For example, when switching representation of a type with no occurrences
@@ -1217,7 +1224,9 @@ class Geometry(bonsai.core.tool.Geometry):
for element in element_types:
if obj := tool.Ifc.get_object(element):
if representation := ifcopenshell.util.representation.get_representation(element, context):
geometry = ifcopenshell.geom.create_shape(settings, representation)
geometry = ifcopenshell.geom.create_shape(
settings, representation, geometry_library=geometry_library
)
mesh_name = tool.Loader.get_mesh_name_from_shape(geometry)
mesh = meshes.get(mesh_name)
if mesh is None:
+48 -34
View File
@@ -2292,32 +2292,18 @@ class Model(bonsai.core.tool.Model):
deform_layer = bm.verts.layers.deform.active
# Sanity check
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
if deform_layer:
for vert in bm.verts:
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
is_circle = False
for group_index in vert_group_indices:
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
group_verts[group_type].setdefault(group_index, 0)
group_verts[group_type][group_index] += 1
if group_type == "IFCCIRCLE":
is_circle = True
is_circle = any(gi in groups["IFCCIRCLE"] for gi in vert_group_indices)
is_arc = any(gi in groups["IFCARCINDEX"] for gi in vert_group_indices)
if (is_circle or is_arc) and not vert.link_edges:
return (False, "CIRCLE" if is_circle else "3POINT_ARC")
if is_circle:
pass # Circles are allowed to be unclosed
elif len(vert.link_edges) != 2: # Unclosed loop or forked loop
return (False, "UNCLOSED_LOOP")
for group_type, group_counts in group_verts.items():
if group_type == "IFCARCINDEX":
for group_count in group_counts.values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
elif group_type == "IFCCIRCLE":
for group_count in group_counts.values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
loop_edges = list(bm.edges)
# Create loops from edges
@@ -2340,6 +2326,28 @@ class Model(bonsai.core.tool.Model):
has_found_connected_edge = True
loops.append(loop)
# Sanity check, per loop rather than across the whole mesh
if deform_layer:
for loop in loops:
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
loop_verts = {v for edge in loop for v in edge.verts}
for vert in loop_verts:
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
if group_index in groups["IFCARCINDEX"]:
group_type = "IFCARCINDEX"
elif group_index in groups["IFCCIRCLE"]:
group_type = "IFCCIRCLE"
else:
continue
loop_group_counts[group_type].setdefault(group_index, 0)
loop_group_counts[group_type][group_index] += 1
for group_count in loop_group_counts["IFCARCINDEX"].values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
for group_count in loop_group_counts["IFCCIRCLE"].values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
@@ -2520,27 +2528,11 @@ class Model(bonsai.core.tool.Model):
deform_layer = bm.verts.layers.deform.active
# Sanity check
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
if deform_layer:
for vert in bm.verts:
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
for group_index in vert_group_indices:
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
group_verts[group_type].setdefault(group_index, 0)
group_verts[group_type][group_index] += 1
if len(vert.link_edges) > 2: # Forked loop
return (False, "FORKED_LOOP")
for group_type, group_counts in group_verts.items():
if group_type == "IFCARCINDEX":
for group_count in group_counts.values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
elif group_type == "IFCCIRCLE":
for group_count in group_counts.values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
loop_edges = list(bm.edges)
# Create loops from edges
@@ -2563,6 +2555,28 @@ class Model(bonsai.core.tool.Model):
has_found_connected_edge = True
loops.append(loop)
# Sanity check, per loop rather than across the whole mesh
if deform_layer:
for loop in loops:
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
loop_verts = {v for edge in loop for v in edge.verts}
for vert in loop_verts:
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
if group_index in groups["IFCARCINDEX"]:
group_type = "IFCARCINDEX"
elif group_index in groups["IFCCIRCLE"]:
group_type = "IFCCIRCLE"
else:
continue
loop_group_counts[group_type].setdefault(group_index, 0)
loop_group_counts[group_type][group_index] += 1
for group_count in loop_group_counts["IFCARCINDEX"].values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
for group_count in loop_group_counts["IFCCIRCLE"].values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
+1 -1
View File
@@ -168,7 +168,7 @@ class Polyline(bonsai.core.tool.Polyline):
distance = (mouse_vector - last_point).length
if distance < 0:
return
angle, orientation_angle, angle_round_threshold = None, None
angle, orientation_angle, angle_round_threshold = None, None, None
if distance > 0:
angle = tool.Cad.angle_3_vectors(
second_to_last_point, last_point, mouse_vector, new_angle=None, degrees=True
+3 -3
View File
@@ -1159,11 +1159,11 @@ class Sequence(bonsai.core.tool.Sequence):
props.task_input_colors.clear()
for group, data in groups.items():
for predefined_type in data["PredefinedType"]:
if group in ["CREATION", "OPERATION", "MOVEMENT_TO"]:
if group in ("CREATION", "OPERATION", "MOVEMENT_TO"):
predefined_type_item = props.task_output_colors.add()
elif group in ["MOVEMENT_FROM"]:
elif group in ("MOVEMENT_FROM",):
predefined_type_item = props.task_input_colors.add()
elif group in ["USERDEFINED", "DESTRUCTION"]:
elif group in ("USERDEFINED", "DESTRUCTION"):
predefined_type_item = props.task_input_colors.add()
predefined_type_item2 = props.task_output_colors.add()
predefined_type_item2.name = predefined_type
@@ -24,7 +24,7 @@ Blender versions:
- 64-bit MacOS Intel (``macos-x64``)
- 64-bit MacOS Silicon (``macos-arm64``)
- 64-bit Windows (``windows-x64``)
- Blender 4.3, 4.4, or 4.5 with Python 3.11
- Blender 5.1 or 5.2 with Python 3.13
Developer builds may exist for different versions of Python but there will be
no guarantee of the uptime or stability of these builds.
+27 -12
View File
@@ -16,20 +16,26 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import argparse
import ezdxf
import ifcopenshell
import ifcopenshell.guid
class Dxf2Ifc:
def __init__(self, dxf_path, outfile):
self.dxf_path = dxf_path
self.outfile = outfile
def execute(self):
self.create_ifc_file()
doc = ezdxf.readfile("input.dxf")
doc = ezdxf.readfile(self.dxf_path)
model = doc.modelspace()
products = []
for entity in model:
print(entity)
if entity.get_mode() == "AcDbPolyFaceMesh":
if entity.dxftype() == "POLYLINE" and entity.is_poly_face_mesh:
ifc_faces = []
for face in entity.faces():
ifc_faces.append(
@@ -67,15 +73,18 @@ class Dxf2Ifc:
"Name": entity.dxf.layer,
"ObjectPlacement": self.placement,
"Representation": representation,
}
},
)
)
else:
print("Not yet implemented")
self.file.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(), None, None, None, products, self.site
)
self.file.write("test.ifc")
print(f"Skipping unsupported entity: {entity.dxftype()}")
if products:
self.file.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(), None, None, None, products, self.site
)
else:
print("No AcDbPolyFaceMesh entities found, writing an empty IFC")
self.file.write(self.outfile)
def create_ifc_file(self):
self.file = ifcopenshell.file()
@@ -97,14 +106,20 @@ class Dxf2Ifc:
"Name": "DXF Conversion",
"RepresentationContexts": [self.context],
"UnitsInContext": units,
}
},
)
self.site = self.file.create_entity(
"IfcSite",
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement}
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement},
)
self.file.createIfcRelAggregates(ifcopenshell.guid.new(), None, None, None, self.project, [self.site])
dxf2ifc = Dxf2Ifc()
dxf2ifc.execute()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Converts DXF polyface meshes (AcDbPolyFaceMesh) to an IFC")
parser.add_argument("dxf", type=str, help="The input DXF file")
parser.add_argument("-o", "--output", type=str, help="The output IFC file", default="out.ifc")
args = parser.parse_args()
dxf2ifc = Dxf2Ifc(args.dxf, args.output)
dxf2ifc.execute()
@@ -0,0 +1,141 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
#
# This file was generated with the assistance of an AI coding tool.
"""Regression tests for ``ProfileDecorator``'s ``_connected_components`` helper.
Duplicating a circle/arc void's loop in Edit Mode (Tab, Tab, select the
loop, Shift+D) copies the ``IFCARCINDEX``/``IFCCIRCLE`` vertex-group
weights onto the new geometry, since Blender's mesh duplicate never
allocates a new vertex group. Before this fix, ``ProfileDecorator``
grouped arc/circle vertices by group index alone, so the duplicate's
vertices piled into the same entry as the source loop's, failing the
"exactly 2/3 verts" check and silently dropping *both* loops from the
decorator until the mesh was re-imported (e.g. by leaving and re-entering
Edit Mode). ``_connected_components`` splits each group's vertices back
into their connected loops so a duplicate is drawn immediately, see #6944."""
import bmesh
import bpy
import pytest
from bonsai.bim.module.model.decorator import _connected_components
pytestmark = pytest.mark.model
def _bm_with_groups(verts, edges, groups):
"""Build a standalone bmesh with a deform layer, and populate ``groups``:
a list of (group_index, [vert_indices]) pairs, mirroring how
``tool.Model.import_profile``/``convert_curve_to_mesh`` assign one
vertex group per circle/arc loop."""
bm = bmesh.new()
deform_layer = bm.verts.layers.deform.new()
bm_verts = [bm.verts.new(v) for v in verts]
bm.verts.ensure_lookup_table()
for a, b in edges:
bm.edges.new((bm_verts[a], bm_verts[b]))
bm.verts.ensure_lookup_table()
bm_verts = list(bm.verts)
for group_index, vert_indices in groups:
for vi in vert_indices:
bm_verts[vi][deform_layer][group_index] = 1.0
return bm, bm_verts, deform_layer
def _group_dict(bm_verts, deform_layer, group_index, vert_indices):
return {group_index: [bm_verts[i] for i in vert_indices]}
def test_single_circle_loop_is_one_component():
# A circle is exactly 2 verts joined by 1 edge (tool.Model.convert_curve_to_mesh).
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 1, 0)],
edges=[(0, 1)],
groups=[(0, [0, 1])],
)
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1])
components = _connected_components(circles)
assert len(components) == 1
assert len(components[0]) == 2
bm.free()
def test_single_arc_loop_is_one_component():
# An arc is exactly 3 verts: endpoint-midpoint-endpoint (2 edges).
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0)],
edges=[(0, 1), (1, 2)],
groups=[(0, [0, 1, 2])],
)
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2])
components = _connected_components(arcs)
assert len(components) == 1
assert len(components[0]) == 3
bm.free()
def test_duplicated_circle_loop_splits_into_two_components():
# Duplicating verts 0-1 (Shift+D) yields verts 2-3, connected to each
# other but NOT to the source loop, while keeping the same group index
# (0) -- exactly what bmesh.ops.duplicate produces mid Edit-Mode.
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 1, 0), (5, -1, 0), (5, 1, 0)],
edges=[(0, 1), (2, 3)],
groups=[(0, [0, 1, 2, 3])],
)
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3])
components = _connected_components(circles)
assert len(components) == 2
assert sorted(len(c) for c in components) == [2, 2]
bm.free()
def test_duplicated_arc_loop_splits_into_two_components():
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0), (5, -1, 0), (5, 0, 0.3), (5, 1, 0)],
edges=[(0, 1), (1, 2), (3, 4), (4, 5)],
groups=[(0, [0, 1, 2, 3, 4, 5])],
)
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3, 4, 5])
components = _connected_components(arcs)
assert len(components) == 2
assert sorted(len(c) for c in components) == [3, 3]
bm.free()
def test_distinct_circle_groups_stay_separate_and_correctly_sized():
# Multiple genuinely different circles (distinct group indices) must
# each still resolve to their own single 2-vert component.
verts = []
edges = []
groups = []
for i in range(5):
base = len(verts)
verts += [(i * 3, -1, 0), (i * 3, 1, 0)]
edges.append((base, base + 1))
groups.append((i, [base, base + 1]))
bm, bm_verts, deform_layer = _bm_with_groups(verts, edges, groups)
circles = {}
for group_index, vert_indices in groups:
circles[group_index] = [bm_verts[i] for i in vert_indices]
components = _connected_components(circles)
assert len(components) == 5
assert all(len(c) == 2 for c in components)
bm.free()
+53
View File
@@ -453,6 +453,59 @@ class TestDuplicateDrawing:
subject.duplicate_drawing(ifc, blender, drawing, geometry, drawing="drawing", should_duplicate_annotations=True)
class TestCopyAnnotationsToDrawing:
def test_run(self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
ifc.get_object("target_drawing").should_be_called().will_return("camera")
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
({"annotation": ["new_annotation"]}, None)
)
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
assert subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
) == ["new_annotation"]
def test_skipping_annotations_already_in_the_target_drawing(
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("target_drawing")
assert (
subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
)
== []
)
def test_importing_the_target_camera_when_it_is_not_loaded(
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
ifc.get_object("target_drawing").should_be_called().will_return(None)
drawing.import_drawing("target_drawing").should_be_called().will_return("camera")
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
({"annotation": ["new_annotation"]}, None)
)
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
assert subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
) == ["new_annotation"]
class TestRemoveDrawing:
def test_run(self, ifc, drawing):
drawing.is_active_drawing("drawing").should_be_called().will_return(True)
+19
View File
@@ -506,6 +506,25 @@ class TestGetDrawingGroup(NewFile):
assert subject.get_drawing_group(element) == group
class TestGetGroupDrawing(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
group = ifcopenshell.api.group.add_group(ifc)
group.ObjectType = "DRAWING"
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
assert subject.get_group_drawing(group) == drawing
def test_ignores_groups_that_are_not_drawings(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
group = ifcopenshell.api.group.add_group(ifc)
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
assert subject.get_group_drawing(group) is None
class TestGetDrawingTargetView(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
+3 -3
View File
@@ -6,10 +6,10 @@ Files and scripts for the use of [`Code_Aster`](https://code-aster.org) in IFC-d
## Scripts:
- [`ifc2ca.py`](ifc2ca.py): a python script to extract and create a `json` file from an `ifc` file
- [`scriptSalome.py`](scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
- [`scriptSalome.py`](templates/salome/scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
- [`scriptCodeAster.py`](scriptCodeAster.py): a python script to create the input file (`.comm`) for Code_Aster
- [`scriptSalomeBonded.py`](scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered)
- [`scriptCodeAsterBonded.py`](scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case
- [`scriptSalomeBonded.py`](_deprecated/scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered). Located under `_deprecated/`.
- [`scriptCodeAsterBonded.py`](_deprecated/scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case. Located under `_deprecated/`.
## Analysis Models
+1 -1
View File
@@ -244,7 +244,7 @@ IfcGeom::BRepElement* ifcopenshell::geometry::Converter::create_brep_for_represe
}
}
shape = new IfcGeom::Representation::BRep(settings_, product_type, representation_id_builder.str(), shapes);
shape = new IfcGeom::Representation::BRep(settings_, product_type, representation_id_builder.str(), shapes, &product->declaration());
std::string context_string = "";
+11 -1
View File
@@ -30,8 +30,18 @@
#include <sstream>
#include <memory>
namespace IfcParse {
class declaration;
}
namespace IfcGeom {
IFC_GEOM_API const ifcopenshell::geometry::taxonomy::style::ptr& get_default_style(const std::string& ifc_type);
// Looks up the default (fallback) style registered for `ifc_type`. When no style is
// registered for that exact type and `decl` is provided, the type's supertype chain
// (as defined by the IFC schema) is walked until a registered ancestor is found, so
// e.g. IfcSlabStandardCase inherits the style registered for IfcSlab. Falls back to
// the generic default style ("*" in a --default-material-file, or a fixed grey) when
// neither the type nor any of its supertypes have a registered style.
IFC_GEOM_API const ifcopenshell::geometry::taxonomy::style::ptr& get_default_style(const std::string& ifc_type, const IfcParse::declaration* decl = nullptr);
IFC_GEOM_API ifcopenshell::geometry::taxonomy::style::ptr& update_default_style(const std::string& ifc_type);
+1 -1
View File
@@ -137,7 +137,7 @@ IfcGeom::Representation::Triangulation::Triangulation(const BRep& shape_model)
}
if (settings().get<ifcopenshell::geometry::settings::ApplyDefaultMaterials>().get() && surface_style_id == -1) {
const auto& material = IfcGeom::get_default_style(shape_model.entity());
const auto& material = IfcGeom::get_default_style(shape_model.entity(), shape_model.declaration());
auto mit = std::find(materials_.begin(), materials_.end(), material);
if (mit == materials_.end()) {
surface_style_id = (int)materials_.size();
+17 -3
View File
@@ -25,6 +25,10 @@
#include <map>
namespace IfcParse {
class declaration;
}
namespace IfcGeom {
namespace Representation {
@@ -36,16 +40,26 @@ namespace IfcGeom {
const ifcopenshell::geometry::Settings settings_;
const std::string entity_;
std::string id_;
// Most-derived IFC type declaration of the product this representation was
// built for, used to walk the supertype chain when resolving a default
// (fallback) style so subtypes such as IfcSlabStandardCase inherit the
// style registered for IfcSlab. May be null (e.g. for reconstructed /
// deserialized representations), in which case no inheritance is applied.
const IfcParse::declaration* declaration_ = nullptr;
public:
explicit Representation(const ifcopenshell::geometry::Settings& settings, const std::string& entity, const std::string& id)
explicit Representation(const ifcopenshell::geometry::Settings& settings, const std::string& entity, const std::string& id, const IfcParse::declaration* decl = nullptr)
: settings_(settings)
, entity_(entity)
, id_(id)
, declaration_(decl)
{}
const ifcopenshell::geometry::Settings& settings() const { return settings_; }
const std::string& entity() const {
return entity_;
}
const IfcParse::declaration* declaration() const {
return declaration_;
}
// id starts with representation id and then it may have the following dash separated elements:
// - layerset-layerset_id
// - material-material_id
@@ -60,8 +74,8 @@ namespace IfcGeom {
BRep(const BRep& other);
BRep& operator=(const BRep& other);
public:
BRep(const ifcopenshell::geometry::Settings& settings, const std::string& entity, const std::string& id, const IfcGeom::ConversionResults& shapes)
: Representation(settings, entity, id)
BRep(const ifcopenshell::geometry::Settings& settings, const std::string& entity, const std::string& id, const IfcGeom::ConversionResults& shapes, const IfcParse::declaration* decl = nullptr)
: Representation(settings, entity, id, decl)
, shapes_(shapes)
{}
virtual ~BRep() {}
+22 -1
View File
@@ -1,4 +1,5 @@
#include "../ifcgeom/IfcGeomRenderStyles.h"
#include "../ifcparse/IfcSchema.h"
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
@@ -112,15 +113,35 @@ void IfcGeom::set_default_style_file(const std::string& json_file) {
}
}
const ifcopenshell::geometry::taxonomy::style::ptr& IfcGeom::get_default_style(const std::string& s) {
const ifcopenshell::geometry::taxonomy::style::ptr& IfcGeom::get_default_style(const std::string& s, const IfcParse::declaration* decl) {
static std::mutex m;
std::lock_guard<std::mutex> lk(m);
if (!default_materials_initialized) InitDefaultMaterials();
auto it = default_materials.find(s);
if (it == default_materials.end() && decl != nullptr) {
// No style registered for this exact type. Walk up the schema's supertype
// chain (e.g. IfcSlabStandardCase -> IfcSlab) so a style registered for a
// supertype is inherited by its subtypes, rather than always falling back
// to the generic default style.
const IfcParse::entity* entity = decl->as_entity();
const IfcParse::entity* super = entity ? entity->supertype() : nullptr;
while (super != nullptr) {
auto super_it = default_materials.find(super->name());
if (super_it != default_materials.end()) {
it = super_it;
break;
}
super = super->supertype();
}
}
if (it == default_materials.end()) {
default_materials.insert(std::make_pair(s, default_material));
it = default_materials.find(s);
} else if (it->first != s) {
// Cache the resolved (inherited) style under the leaf type name too, so
// repeated lookups for this exact type are O(1) afterwards.
default_materials.insert(std::make_pair(s, it->second));
}
return it->second;
}
@@ -85,8 +85,8 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "lib", p
try:
from . import ifcopenshell_wrapper
except Exception:
raise ImportError("IfcOpenShell not built for '%s'" % python_distribution)
except Exception as e:
raise ImportError("IfcOpenShell not built for '%s' (%s)" % (python_distribution, e)) from e
# `_file`, `_stream` is used only for annotations inside this file,
# see https://github.com/microsoft/pyright/discussions/9065.
+2 -6
View File
@@ -42,7 +42,7 @@ WHITE = numpy.array((1.0, 1.0, 1.0))
DO_NOTHING = lambda *args: None
ARRANGE_POLYGON_SETTINGS = W.arrange_polygon_settings() if hasattr(W, "arrange_polygon_settings") else None
ARRANGE_POLYGON_SETTINGS = W.arrange_polygon_settings()
@dataclass
@@ -546,11 +546,7 @@ def main(
*(tup for i, tup in enumerate(zip(path_objects, section_polies, polies)) if has_relevant_zone(i))
)
arranged = W.arrange_polygons(
*filter(None, (ARRANGE_POLYGON_SETTINGS,)),
polies,
*((logger,) if logger is not None else ()),
)
arranged = W.arrange_polygons(ARRANGE_POLYGON_SETTINGS, polies, logger)
svg_data_3 = W.polygons_to_svg(arranged, False)
dom3 = parseString(svg_data_3)
svg3 = dom3.childNodes[0]
+3 -1
View File
@@ -21,7 +21,9 @@ END-ISO-10303-21;
def test_reference_to_undefined_owning_instance():
data = "ISO-10303-21;HEADER;FILE_DESCRIPTION();FILE_NAME();FILE_SCHEMA(('IFC4'));#=IFCRELAGGREGATES((#))#5=IFCPOINT)"
data = (
"ISO-10303-21;HEADER;FILE_DESCRIPTION();FILE_NAME();FILE_SCHEMA(('IFC4'));#=IFCRELAGGREGATES((#))#5=IFCPOINT)"
)
ifcopenshell.file.from_string(data)
print(ifcopenshell.get_log())
@@ -3,6 +3,7 @@ cjio >=0.8, <0.10
deepdiff
docutils
flask
igraph
isodate
jinja2
lark