Compare commits

...

75 Commits

Author SHA1 Message Date
Richard Brice edfcdbb865 Playing with input panels for alignment 2025-05-15 10:19:19 -07:00
Andrej730 a77125ff12 bim.add_drawing - document camera placement behaviour in description
See https://i.imgur.com/VfOjGHk.png
2025-05-15 20:01:02 +05:00
Andrej730 c8841bcb6a Add a test for be65774 2025-05-15 20:01:01 +05:00
Andrej730 b20997dea8 Fix tests missing assert statement - add assert and fix them 2025-05-15 19:45:11 +05:00
Andrej730 292aca6685 Remove unnecessary IFC operators 2025-05-15 19:45:11 +05:00
Andrej730 3a824ec969 Allow adding arrays to openings and spatial elements 0b8fb41 0e37528 2025-05-15 19:45:11 +05:00
Andrej730 bea9f42f87 Annotator.add_text - remove ancient dead code
It was deprecated a while ago in 43869c3, when we stopped using curves for text annotations. bim.resize_text was also using curve annotations and now also was unused
2025-05-15 19:45:11 +05:00
Andrej730 e4a50b32ce typing 2025-05-15 19:40:44 +05:00
Andrej730 76611024b6 Remove drawing styles attributes prop (a50c633cf) 2025-05-15 10:30:35 +05:00
Andrej730 92ee82374c EPset_Drawing.Metadata - add description
See https://i.imgur.com/0fR9fRj.png
2025-05-14 19:40:46 +05:00
Andrej730 af81aa1fae Reapply 06f1477 to fix not appearing IFC Description button
Not that skipping non-string properties was a bad idea, but inserting it right at the beginning was - non-string IFC properties were missing IFC descriptions because of it. Moved it past `Attribute` check to avoid this issue.

For anyone hearing about this feature for the first time - https://imgur.com/a/dNRao3R

I assume this was also the issue that was encountered in #5892
2025-05-14 19:40:45 +05:00
Andrej730 16f9f91561 util.doc - statically type json structures 2025-05-14 19:40:45 +05:00
Andrej730 3a52a848ae draw_custom_context_menu - small refactor to improve readibility 2025-05-14 19:40:45 +05:00
Andrej730 a50c633cf4 Remove drawing styles attributes
It's been awhile since they were unused (2c301d7) and now they're replaced with EPset_Drawing.Metadata
2025-05-14 19:40:45 +05:00
Andrej730 6251750133 common method for getting active drawing style 2025-05-14 19:40:45 +05:00
Andrej730 acef6379e8 drawing styles - add descriptions to render types, remove NONE type
NONE type removed as it was unused and basically meant the same as 'VIEWPORT'.

Example - https://i.imgur.com/7r6CJdg.png
2025-05-14 19:40:45 +05:00
Andrej730 c2860e6e25 drawing.operator not to use DrawingsData 2025-05-14 19:40:44 +05:00
Andrej730 b8e5cd740a Use common method for getting active drawing entity 2025-05-14 19:40:44 +05:00
Andrej730 9188dc60ab typing 2025-05-14 19:40:44 +05:00
Thomas Krijnen 8ce56db0c3 Align preprocessor flags #6706 2025-05-14 13:09:17 +02:00
Andrej730 b91b1401f4 util.get_aggregate - make it more readable (5597095) 2025-05-13 17:44:42 +05:00
Andrej730 0e37528915 Skip IfcOpeningElements arrays during base import, setup constraint on opening load #6688 2025-05-13 17:23:46 +05:00
Andrej730 9991c4aa56 IfcImporter.create_generic_elements - prevent argument mutation
as it may have unexpected consequences
2025-05-13 17:23:46 +05:00
Andrej730 0ef3983035 bim.show_opening - simplify code 2025-05-13 17:23:46 +05:00
Andrej730 0f6e6a48f4 bim.show_openings - expand description 2025-05-13 17:23:45 +05:00
Andrej730 3d225beafd Add notes on Tekla accommodations (7c3870595) 2025-05-13 16:59:12 +05:00
Andrej730 6a91bbb720 typing 2025-05-13 16:59:12 +05:00
Hannes 1f23e4ba18 Fixed typo in __init__.py
See https://github.com/IfcOpenShell/IfcOpenShell/issues/6625
2025-05-13 13:18:24 +02:00
Andrej730 2ebcffc7d4 Geometry changes will be lost - show warning only for IFC objects
Previously it would also occur for vanilla Blender objects not connected to IFC.
2025-05-13 13:26:54 +05:00
Andrej730 3d4321f713 Prevent class assignment in non-object mode #6697
Example - https://i.imgur.com/KQYQLQZ.png
2025-05-13 13:26:54 +05:00
Andrej730 f8799305e1 black . 2025-05-13 13:26:54 +05:00
Dion Moult 7c38705958 Accommodate invalid missing mapped representations and items coming from Tekla (2023) 2025-05-13 13:09:37 +10:00
Bruno Perdigão f6fc0cfa0f See #6537. Fix object display type when exiting aggregate mode. 2025-05-12 22:01:40 -03:00
Richard Brice 686e9c946b Adds object placement to stationing referent. 2025-05-12 16:14:53 -07:00
sboddy 3085072751 Improve drawing activation as per #6653 (#6659)
Drawings are now activated in a bit different way - not by the camera button located above the drawings list, but by using the camera indicator next to each drawing. Which allows do change active drawing very quickly. All activation options (shift+, alt+) are also available from this indicator.

Now - https://imgur.com/a/DmnWkul

Before - https://imgur.com/a/zjPDkPa
2025-05-12 19:46:34 +05:00
Andrej730 0328be4093 Drawing styles - remove deprecated properties / property values
Deprecated properties:
- scene.render.engine + BLENDER_EEVEE
- scene.render.simplify_shadows
- scene.render.simplify_shadows_render
- space.overlay.backwire_opacity
- space.overlay.show_edges
- space.overlay.show_occlude_wire
- scene.display.shading.wireframe_color_type + MATERIAL
2025-05-12 19:10:04 +05:00
Andrej730 6218d3902e bim.activate_drawing_style - show warnings if some property failed to be set
Otherwise errors were passing silently (just console errors) and remained unfixed. 'PYTEST_VERSION' is needed to be even more strict when we're running pytests, which allows us to catch outdated Blender properties in time.

Example - https://i.imgur.com/K7Trkxf.png
2025-05-12 19:10:04 +05:00
Andrej730 be1836fa48 Mark thumbnails as outdated instead of updating them right away
As user may never open them in type manager
2025-05-12 19:08:46 +05:00
Andrej730 22b5db8a1e ci-black-formatting - print diff 2025-05-12 19:08:46 +05:00
Andrej730 4268e1376c Address PR review changes #6660 2025-05-12 19:08:46 +05:00
Andrej730 e2c1a54e0a typing 2025-05-12 19:08:46 +05:00
falken10vdl d1be660469 Update type manager preview on updating paramteric door/window type (#6656) 2025-05-12 12:41:02 +05:00
Kristoffer Andersen 3ae5227b57 Update ci-ifcopenshell-conda-daily.yml
remove env var
2025-05-11 19:59:05 +02:00
Kristoffer Andersen cdc994ca76 Update ci-ifcopenshell-conda-daily.yml
move rattler build output dir outside of build dir
2025-05-11 19:58:27 +02:00
Kristoffer Andersen 0ad4087f0a Update ci-ifcopenshell-conda-daily.yml
remove dotnet to save space on ubuntu runner
2025-05-11 19:28:12 +02:00
Kristoffer Andersen 4b7ca648c6 Update ci-ifcopenshell-conda-daily.yml
try to get even more space on ubuntu ci runner
2025-05-11 19:23:28 +02:00
Kristoffer Andersen 17bd6e6b0c Update ci-ifcopenshell-conda-daily.yml
fix missing comma
2025-05-11 19:12:34 +02:00
Kristoffer Andersen 7b80803cbe separate osx-x86 and osx-arm64 for the conda daily builds (#6694)
* separate osx-x86 and osx-arm64 for the conda daily builds

* remove running this in PR. No need.
2025-05-11 18:59:52 +02:00
Kristoffer Andersen eaf67d83f9 Update ci-ifcopenshell-conda-daily.yml
strip daily conda build version date string
2025-05-11 16:04:21 +02:00
Kristoffer Andersen 41f754e15b Update ci-ifcopenshell-conda-daily.yml
Update conda ci
2025-05-11 15:53:29 +02:00
Kristoffer Andersen b7cdb86327 use rattler-build to speed up daily conda builds and fix deps (#6692)
* use rattler-build to speed up daily conda builds and add typing_extensions

* minor update
2025-05-11 09:37:02 +02:00
falken10vdl 809a20dc99 system info copied when clicking in Bonsai Version (#6660) 2025-05-09 16:09:37 -05:00
Andrej730 f5e41d18c6 drawing.operator - reuse blender.get_view3d_space 2025-05-09 19:26:28 +05:00
Andrej730 60a8c45ad7 Fix IFC operators issues for drawing styles operations (38cf88d) 2025-05-09 19:26:28 +05:00
Andrej730 73f98bfe4b Remove 2 years old fallback for missing ShadingStyles prop in drawing's pset (38cf88d) 2025-05-09 19:26:28 +05:00
Andrej730 958686958b drawing.prop - reuse generic pset update callback 2025-05-09 19:26:28 +05:00
Andrej730 e0b61c5794 Fix drawing styles update on underlay toggle after 9329390 2025-05-09 19:26:28 +05:00
Andrej730 5aa5552759 Fix drawing test after be657748f 2025-05-09 19:26:27 +05:00
Andrej730 82a19cee7b generate_drawing_matrix - simplify logic 2025-05-09 19:26:27 +05:00
Andrej730 43d4adbd9d Fix tests after specifying types more precisely in def9352ad 2025-05-09 19:26:27 +05:00
Andrej730 1d3c71985f typing 2025-05-09 19:26:27 +05:00
Andrej730 381fca0812 black . 2025-05-09 19:26:27 +05:00
Dion Moult 0f37eca333 Fix bug in IFC4X3 when convering properties to quantities 2025-05-09 15:24:30 +10:00
Dion Moult 6bf9b8b0c9 Fix bug where appending assets could accidentally create duplicate contexts 2025-05-09 15:24:17 +10:00
Bruno Perdigão 9361cfee28 See #6536. Update cardinal point when editing IfcMaterialProfileSetUsage. 2025-05-08 22:06:48 -03:00
Bruno Perdigão 1c205d494a See #6332. Fix issue where imperial precision were being used by metric formatting. 2025-05-08 19:15:51 -03:00
Ryan Schultz 4d1d224a34 fix #6683 - When placing Level (Plan) annotation, have it take on the 'z' dimension of the 3d cursor, verses the front plane of the drawing camera 2025-05-08 17:04:34 -05:00
Andrej730 4976af5e66 drawing.create_camera - remove setting location line that had no effect
Apparently it had no effect from the beginning in 074fe0d and lost any use in 6a8292d, when we started to base position on current cursor's location.
2025-05-08 19:23:24 +05:00
Andrej730 be657748f3 Align new Model drawings to viewport by default
Previously it was creating not very useful top-down camera at `(0,0,0)`, now it should be more intuitive.

Example - https://imgur.com/a/GHrvCSJ
2025-05-08 19:23:24 +05:00
Andrej730 def9352ade typing 2025-05-08 19:23:23 +05:00
Josef Wienerroither a20002ecca Update links and version info ifcmax.rst 2025-05-08 14:42:50 +02:00
Andrej730 b7a0f230ad Fix confused target_view callbacks (1619ae854)
Fix using the same function name twice leading to DocProperties using camera callback too.
2025-05-08 15:50:00 +05:00
Andrej730 76529a06bb Fix resetting perspective camera on drawing activation (1619ae854) 2025-05-08 15:41:34 +05:00
Andrej730 dcdae67a2d Fix typo in 1619ae854 2025-05-08 15:41:34 +05:00
Andrej730 5a7a368169 ifcopenshell.file.Transaction - add static typing 2025-05-08 15:41:34 +05:00
96 changed files with 2637 additions and 1096 deletions
+1 -1
View File
@@ -37,7 +37,7 @@ jobs:
- name: Black formatter
id: linting
run: |
python3 -m black --check .
python3 -m black --diff --check .
continue-on-error: true
- name: Final check
@@ -35,11 +35,11 @@ jobs:
- name: Version + date str
id: verdate
run: echo "verdate='${{ steps.version.outputs.version }}alpha${{ steps.date.outputs.date }}'" >> $GITHUB_OUTPUT
run: echo "verdate=${{ steps.version.outputs.version }}alpha${{ steps.date.outputs.date }}" >> $GITHUB_OUTPUT
test:
name: ${{ matrix.platform.distver }}-${{ matrix.pyver.name }}-${{ matrix.variant }}
name: ${{ matrix.platform.distver }}-${{ matrix.pyver.name }}
needs: activate
runs-on: ${{ matrix.platform.distver }}
defaults:
@@ -48,57 +48,67 @@ jobs:
strategy:
fail-fast: false
matrix:
variant: [novtk, all]
pyver: [
# { name: py311, distver: '3.11'},
{ name: py312, distver: '3.12'}
]
platform: [
{ name: win, distver: windows-latest, pkg_dir: 'win-64' },
{ name: linux, distver: ubuntu-latest, pkg_dir: 'linux-64' },
{ name: macOS, distver: macos-latest, pkg_dir: 'osx-64' }
{ name: macOS-arm, distver: macos-latest, pkg_dir: 'osx-arm64' },
{ name: macOS-x86, distver: macos-13, pkg_dir: 'osx-64' }
]
steps:
- name: Set up swap space
- name: Set Swap Space
if: runner.os == 'Linux'
uses: pierotofy/set-swap-space@v1.0
uses: pierotofy/set-swap-space@master
with:
swap-size-gb: 10
- name: set ARTIFACTS ENV vars
shell: bash
run: |
pwd
if [[ "$RUNNER_OS" == "Windows" ]]; then
echo "ARTIFACTS_DIR=D:/a/artifacts" >> $GITHUB_ENV
elif [[ "$RUNNER_OS" == "macOS" ]]; then
echo "ARTIFACTS_DIR=/Users/runner/work/artifacts" >> $GITHUB_ENV
elif [[ "$RUNNER_OS" == "Linux" ]]; then
echo "ARTIFACTS_DIR=/home/runner/work/artifacts" >> $GITHUB_ENV
fi
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Download and extract MacOSX SDK
if: ${{ runner.os == 'macOS' }}
if: ${{ matrix.platform.name == 'macOS-x86' }}
run: |
curl -L https://github.com/phracker/MacOSX-SDKs/releases/download/11.3/MacOSX10.13.sdk.tar.xz | tar -xvJf - -C /Users/runner/work/
- uses: mamba-org/setup-micromamba@v1 # https://github.com/mamba-org/setup-micromamba
- uses: mamba-org/setup-micromamba@v2 # https://github.com/mamba-org/setup-micromamba
with:
environment-name: test-env
create-args: >-
python=3.11
python=3.12
anaconda-client
boa
rattler-build
- name: create conda package dist dir
run: |
mkdir -p ${{ github.workspace }}/dist
mkdir -p ${{ env.ARTIFACTS_DIR }}
- name: build & test ifcopenshell
run: |
conda mambabuild . --python ${{ matrix.pyver.distver }} --no-remove-work-dir --output-folder '${{ github.workspace }}/dist' --variants='{variant: ${{ matrix.variant }}}'
working-directory: ./conda
rattler-build build -r conda/recipe.yaml --output-dir '${{ env.ARTIFACTS_DIR }}'
env:
VERSION_OVERRIDE: ${{ needs.activate.outputs.verdate }}
- name: upload to anaconda
if: ${{ matrix.platform.name == 'win' }}
run: |
anaconda -t ${{ secrets.ANACONDA_TOKEN }} upload --force --user ifcopenshell '${{ github.workspace }}/dist/${{ matrix.platform.pkg_dir }}/*.tar.bz2'
anaconda -t ${{ secrets.ANACONDA_TOKEN }} upload --force --user ifcopenshell '${{ env.ARTIFACTS_DIR }}/${{ matrix.platform.pkg_dir }}/*.conda'
- name: upload to anaconda
if: ${{ matrix.platform.name != 'win' }}
run: |
anaconda -t ${{ secrets.ANACONDA_TOKEN }} upload --force --user ifcopenshell ${{ github.workspace }}/dist/${{ matrix.platform.pkg_dir }}/*.tar.bz2
anaconda -t ${{ secrets.ANACONDA_TOKEN }} upload --force --user ifcopenshell ${{ env.ARTIFACTS_DIR }}/${{ matrix.platform.pkg_dir }}/*.conda
+4
View File
@@ -49,3 +49,7 @@ if errorlevel 1 exit 1
ninja install -j 1
if errorlevel 1 exit 1
python %RECIPE_DIR%/update_version_init.py %PKG_VERSION% %SP_DIR%/ifcopenshell/__init__.py
if errorlevel 1 exit 1
+3 -1
View File
@@ -46,4 +46,6 @@ cmake ${CMAKE_ARGS} -G Ninja \
ninja
ninja install -j 1
ninja install -j 1
python "${RECIPE_DIR}/update_version_init.py" "${PKG_VERSION}" "${SP_DIR}/ifcopenshell/__init__.py"
+13 -16
View File
@@ -1,7 +1,3 @@
variant:
- novtk
- all
occt:
- 7.8.1
@@ -24,12 +20,13 @@ cxx_compiler_version:
- '12' # [linux]
- '16' # [osx]
c_stdlib_version:
- '2.12' # [linux]
- '10.13' # [osx]
- 2.17 # [linux]
- 10.13 # [osx and x86_64]
- 11.0 # [osx and arm64]
hdf5:
- 1.14.3
- 1.14.6
libboost_devel:
- '1.84'
- '1.86'
libxml2:
- '2'
mpfr:
@@ -47,12 +44,12 @@ target_platform:
- win-64 # [win]
- linux-64 # [linux]
- osx-64 # [osx]
macos_machine:
- x86_64-apple-darwin13.4.0
MACOSX_DEPLOYMENT_TARGET:
- '10.13'
MACOSX_SDK_VERSION:
- '10.13'
macos_machine: # [osx]
- x86_64-apple-darwin13.4.0 # [osx and x86_64]
- arm64-apple-darwin20.0.0 # [osx and arm64]
MACOSX_DEPLOYMENT_TARGET: # [osx]
- 11.0 # [osx and arm64]
- 10.13 # [osx and x86_64]
CONDA_BUILD_SYSROOT:
- "/Users/runner/work/MacOSX10.13.sdk" # [osx]
CONDA_BUILD_SYSROOT: # [osx]
- "/Users/runner/work/MacOSX10.13.sdk" # [osx and x86_64]
+48 -33
View File
@@ -1,64 +1,78 @@
{% set version = environ.get('VERSION_OVERRIDE', '0.8.0') %}
{% set build = 0 %}
# Higher number -> Always prioritize "novtk" variant over "all" variant
{% set build = build + 200 %} # [variant == "novtk"]
{% set build = build + 100 %} # [variant == "all"]
context:
version: ${{ env.get("VERSION_OVERRIDE", default="0.8.2.1") }}
build: 1
package:
name: ifcopenshell
version: {{ version }}
version: ${{ version }}
source:
path: ../
- path: ..
build:
number: {{ build }}
skip: true # [py<39]
binary_relocation: false # [osx]
string: py{{ CONDA_PY }}_{{ variant }}_h{{ PKG_HASH }}_{{ build }}
run_exports:
- {{ pin_subpackage('ifcopenshell', max_pin='x.x.x') }} *{{ variant }}*
number: ${{ build }}
dynamic_linking:
binary_relocation: ${{ true if osx }}
requirements:
build:
- cmake
- if: build_platform != target_platform
then:
- python
- cross-python_${{ target_platform }}
- cmake <4
- ninja
- swig >=4.1.1
- {{ stdlib("c") }}
- {{ compiler('c') }}
- {{ compiler('cxx') }}
- ${{ stdlib("c") }}
- ${{ compiler('c') }}
- ${{ compiler('cxx') }}
host:
- python
- libboost-devel
- occt *=*{{ variant }}*
- occt
- libxml2
- cgal-cpp
- hdf5
- eigen
- mpfr
- nlohmann_json
- gmp # [unix]
- mpir # [win]
- gmp
- zlib
run:
- python
- {{ pin_compatible('occt', max_pin='x.x.x') }} *{{ variant }}*
- {{ pin_compatible('cgal-cpp', max_pin='x.x') }}
test:
imports:
- ifcopenshell
- shapely
- typing_extensions
- ${{ pin_compatible('occt', upper_bound='x.x.x') }}
- ${{ pin_compatible('cgal-cpp', upper_bound='x.x') }}
run_exports:
- ${{ pin_subpackage('ifcopenshell', upper_bound='x.x.x') }}
tests:
- python:
imports:
- ifcopenshell
pip_check: false
- script:
- python -c "import ifcopenshell; assert ifcopenshell.version == '${{ version }}', 'print(ifcopenshell.version)'"
requirements:
run:
- occt * *novtk* # Ensure that even though compiled against OCCT with VTK, it can still run with OCCT without VTK
- pytest
- python-dateutil
- xmlschema
- xsdata
- lxml
- isodate
- lark
- networkx
- tabulate
- shapely
about:
home: https://ifcopenshell.org
license: LGPL-3.0-or-later
license_file: COPYING
summary: 'IfcOpenShell is a library to support the IFC file format'
summary: IfcOpenShell is a library to support the IFC file format
description: |
IfcOpenShell
============
@@ -293,8 +307,9 @@ about:
[MSYS2]: https://msys2.github.io/ "MSYS2"
[win/readme.md]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/win/readme.md "win/readme.md"
[nix/build-all.py]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/nix/build-all.py "nix/build-all.py"
doc_url: https://ifcopenshell.org/
dev_url: https://github.com/IfcOpenShell/IfcOpenShell
homepage: https://ifcopenshell.org
repository: https://github.com/IfcOpenShell/IfcOpenShell
documentation: https://ifcopenshell.org/
extra:
recipe-maintainers:
+32
View File
@@ -0,0 +1,32 @@
import re
import argparse
from pathlib import Path
def update_version(file_path: str, version: str) -> None:
"""Update the version string in the given __init__.py file."""
file_path = Path(file_path)
# Read the file and replace the version
file_contents = file_path.read_text(encoding="utf-8")
new_contents = re.sub(r'version = "0\.0\.0"', f'version = "{version}"', file_contents)
# Write the updated contents back to the file
file_path.write_text(new_contents, encoding="utf-8")
print(f"Updated version in {file_path} to {version}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Update the version string in a Python file.")
parser.add_argument(
"version",
type=str,
help="The version string to replace '0.0.0' with (e.g., '1.2.3')."
)
parser.add_argument(
"file",
type=str,
help="The path to the __init__.py file where the version will be updated."
)
args = parser.parse_args()
update_version(args.file, args.version)
+1
View File
@@ -123,6 +123,7 @@ classes = [
operator.SelectURIAttribute,
operator.SetTab,
operator.SwitchTab,
operator.ShowSystemInfo,
prop.StrProperty,
operator.BIM_OT_enum_property_search, # /!\ Register AFTER prop.StrProperty
prop.ObjProperty,
@@ -47,8 +47,6 @@
"scene.render.simplify_gpencil_shader_fx": true,
"scene.render.simplify_gpencil_tint": true,
"scene.render.simplify_gpencil_view_fill": true,
"scene.render.simplify_shadows": 1.0,
"scene.render.simplify_shadows_render": 1.0,
"scene.render.simplify_subdivision": 6,
"scene.render.simplify_subdivision_render": 6,
"scene.render.simplify_volumes": 1.0,
@@ -147,7 +145,7 @@
"scene.display.shading.use_scene_world_render": false,
"scene.display.shading.use_studiolight_view_rotation": true,
"scene.display.shading.use_world_space_lighting": false,
"scene.display.shading.wireframe_color_type": "MATERIAL",
"scene.display.shading.wireframe_color_type": "THEME",
"scene.display.shading.xray_alpha": 0.5,
"scene.display.shading.xray_alpha_wireframe": 0.0,
"scene.display.light_direction": [
@@ -162,7 +160,6 @@
"scene.display.shadow_focus": 0.0,
"scene.display.shadow_shift": 0.10000000149011612,
"scene.display.viewport_aa": "FXAA",
"space.overlay.backwire_opacity": 0.5,
"space.overlay.bone_wire_alpha": 1.0,
"space.overlay.display_handle": "SELECTED",
"space.overlay.fade_inactive_alpha": 0.4000000059604645,
@@ -189,7 +186,6 @@
"space.overlay.show_edge_crease": true,
"space.overlay.show_edge_seams": true,
"space.overlay.show_edge_sharp": true,
"space.overlay.show_edges": false,
"space.overlay.show_extra_edge_angle": false,
"space.overlay.show_extra_edge_length": false,
"space.overlay.show_extra_face_angle": false,
@@ -208,7 +204,6 @@
"space.overlay.show_motion_paths": true,
"space.overlay.show_object_origins": false,
"space.overlay.show_object_origins_all": false,
"space.overlay.show_occlude_wire": false,
"space.overlay.show_onion_skins": false,
"space.overlay.show_ortho_grid": true,
"space.overlay.show_outline_selected": true,
@@ -298,8 +293,6 @@
"scene.render.simplify_gpencil_shader_fx": true,
"scene.render.simplify_gpencil_tint": true,
"scene.render.simplify_gpencil_view_fill": true,
"scene.render.simplify_shadows": 1.0,
"scene.render.simplify_shadows_render": 1.0,
"scene.render.simplify_subdivision": 6,
"scene.render.simplify_subdivision_render": 6,
"scene.render.simplify_volumes": 1.0,
@@ -398,7 +391,7 @@
"scene.display.shading.use_scene_world_render": false,
"scene.display.shading.use_studiolight_view_rotation": true,
"scene.display.shading.use_world_space_lighting": false,
"scene.display.shading.wireframe_color_type": "MATERIAL",
"scene.display.shading.wireframe_color_type": "THEME",
"scene.display.shading.xray_alpha": 0.5,
"scene.display.shading.xray_alpha_wireframe": 0.0,
"scene.display.light_direction": [
@@ -413,7 +406,6 @@
"scene.display.shadow_focus": 0.0,
"scene.display.shadow_shift": 0.10000000149011612,
"scene.display.viewport_aa": "FXAA",
"space.overlay.backwire_opacity": 0.5,
"space.overlay.bone_wire_alpha": 1.0,
"space.overlay.display_handle": "SELECTED",
"space.overlay.fade_inactive_alpha": 0.4000000059604645,
@@ -440,7 +432,6 @@
"space.overlay.show_edge_crease": true,
"space.overlay.show_edge_seams": true,
"space.overlay.show_edge_sharp": true,
"space.overlay.show_edges": false,
"space.overlay.show_extra_edge_angle": false,
"space.overlay.show_extra_edge_length": false,
"space.overlay.show_extra_face_angle": false,
@@ -459,7 +450,6 @@
"space.overlay.show_motion_paths": true,
"space.overlay.show_object_origins": false,
"space.overlay.show_object_origins_all": false,
"space.overlay.show_occlude_wire": false,
"space.overlay.show_onion_skins": false,
"space.overlay.show_ortho_grid": true,
"space.overlay.show_outline_selected": true,
@@ -520,7 +510,7 @@
"scene.render.border_min_x": 0.0,
"scene.render.border_min_y": 0.0,
"scene.render.dither_intensity": 1.0,
"scene.render.engine": "BLENDER_EEVEE",
"scene.render.engine": "BLENDER_EEVEE_NEXT",
"scene.render.film_transparent": false,
"scene.render.filter_size": 1.5,
"scene.render.fps": 24,
@@ -549,8 +539,6 @@
"scene.render.simplify_gpencil_shader_fx": true,
"scene.render.simplify_gpencil_tint": true,
"scene.render.simplify_gpencil_view_fill": true,
"scene.render.simplify_shadows": 1.0,
"scene.render.simplify_shadows_render": 1.0,
"scene.render.simplify_subdivision": 6,
"scene.render.simplify_subdivision_render": 6,
"scene.render.simplify_volumes": 1.0,
@@ -649,7 +637,7 @@
"scene.display.shading.use_scene_world_render": false,
"scene.display.shading.use_studiolight_view_rotation": true,
"scene.display.shading.use_world_space_lighting": false,
"scene.display.shading.wireframe_color_type": "MATERIAL",
"scene.display.shading.wireframe_color_type": "THEME",
"scene.display.shading.xray_alpha": 0.5,
"scene.display.shading.xray_alpha_wireframe": 0.0,
"scene.display.light_direction": [
@@ -664,7 +652,6 @@
"scene.display.shadow_focus": 0.0,
"scene.display.shadow_shift": 0.10000000149011612,
"scene.display.viewport_aa": "FXAA",
"space.overlay.backwire_opacity": 0.5,
"space.overlay.bone_wire_alpha": 1.0,
"space.overlay.display_handle": "SELECTED",
"space.overlay.fade_inactive_alpha": 0.4000000059604645,
@@ -691,7 +678,6 @@
"space.overlay.show_edge_crease": true,
"space.overlay.show_edge_seams": true,
"space.overlay.show_edge_sharp": true,
"space.overlay.show_edges": false,
"space.overlay.show_extra_edge_angle": false,
"space.overlay.show_extra_edge_length": false,
"space.overlay.show_extra_face_angle": false,
@@ -710,7 +696,6 @@
"space.overlay.show_motion_paths": true,
"space.overlay.show_object_origins": true,
"space.overlay.show_object_origins_all": false,
"space.overlay.show_occlude_wire": false,
"space.overlay.show_onion_skins": false,
"space.overlay.show_ortho_grid": true,
"space.overlay.show_outline_selected": true,
@@ -14,7 +14,7 @@ DATA;
#7=IFCSIMPLEPROPERTYTEMPLATE('2j2ZEZR8X5tONm7kli5hM6',$,'HasLinework','',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#8=IFCSIMPLEPROPERTYTEMPLATE('1ttChRysH9UuEX2FeMj5Hu',$,'HasAnnotation','',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#9=IFCSIMPLEPROPERTYTEMPLATE('2NPPxuABv1huDTVh32TFgw',$,'GlobalReferencing','',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#10=IFCSIMPLEPROPERTYTEMPLATE('10hT_1zrzEbRRKMXYAWvtD',$,'Metadata','',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
#10=IFCSIMPLEPROPERTYTEMPLATE('10hT_1zrzEbRRKMXYAWvtD',$,'Metadata','Comma separated list of selector expressions to evaluate for each drawing elementand add results to their ''class'' attribute.\X2\000A\X0\E.g. ''Name, id'' would add to ''class'' value similar to ''Name-Wall id-1220''.\X2\000A\X0\Then it can be used to applied css styles based on the resulting class.\X2\000A\X0\If attribute is not present on the element, then it won''t be added to it''s ''class''.',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
#11=IFCSIMPLEPROPERTYTEMPLATE('3Z0BXPSG5CWgtI33ioV7aj',$,'Include','Selector expression to include ifc elements in the drawing',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
#12=IFCSIMPLEPROPERTYTEMPLATE('1RVts_g3PAw98PJA2yL3bO',$,'Exclude','Selector expression to exclude ifc elements in the drawing',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
#13=IFCSIMPLEPROPERTYTEMPLATE('0c1$8NpYDEaBiJrj16jHIo',$,'Stylesheet','',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
+22 -6
View File
@@ -428,7 +428,8 @@ class IfcImporter:
rep = representation
while True:
if len(rep.Items) == 1 and rep.Items[0].is_a("IfcMappedItem"):
# Tekla 2023 has missing items, though it's invalid IFC.
if rep.Items and len(rep.Items) == 1 and rep.Items[0].is_a("IfcMappedItem"):
rep_matrix = ifcopenshell.util.placement.get_mappeditem_transformation(rep.Items[0])
if not np.allclose(rep_matrix, np.eye(4)):
matrix = rep_matrix @ matrix
@@ -595,6 +596,7 @@ class IfcImporter:
return self.create_generic_sqlite_elements(elements)
if self.ifc_import_settings.should_load_geometry:
elements = elements.copy() # Prevent argument mutation.
context_settings = (
tool.Loader.settings.gross_context_settings if is_gross else tool.Loader.settings.context_settings
)
@@ -1136,7 +1138,22 @@ class IfcImporter:
bpy.ops.view3d.view_selected()
bpy.ops.object.select_all(action="DESELECT")
def setup_arrays(self, annotations_to_import: Optional[set[ifcopenshell.entity_instance]] = None) -> None:
def setup_arrays(
self,
*,
annotations_to_import: Optional[set[ifcopenshell.entity_instance]] = None,
openings_to_import: Optional[set[ifcopenshell.entity_instance]] = None,
) -> None:
# During base import some elements are skipped.
is_base_import = True
elements_to_import: set[ifcopenshell.entity_instance] = set()
if annotations_to_import is not None:
is_base_import = False
elements_to_import = annotations_to_import
elif openings_to_import is not None:
is_base_import = False
elements_to_import = openings_to_import
for pset in self.file.by_type("IfcPropertySet"):
if pset.Name != "BBIM_Array":
continue
@@ -1146,12 +1163,11 @@ class IfcImporter:
for rel in pset.DefinesOccurrence:
element: ifcopenshell.entity_instance
for element in rel.RelatedObjects:
if annotations_to_import is None:
# IfcAnnotations are not loaded during base import.
if element.is_a("IfcAnnotation"):
if is_base_import:
if element.is_a("IfcAnnotation") or element.is_a("IfcOpeningElement"):
continue
else:
if element not in annotations_to_import:
if element not in elements_to_import:
continue
for i in range(len(data)):
tool.Blender.Modifier.Array.set_children_lock_state(element, i, True)
@@ -16,21 +16,51 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a __init__.py file to load all of its classes. Every
# operation, property, and interface needs to be registered with the Blender
# system when the add-on loads. This is where it happens.
import bpy
from . import ui, prop, operator
# from . import ui, prop, operator
from . import operator
classes = (operator.ImportAlignmentCSV,)
# You'll need to provide a list of every one of your classes here. If you forget
# to specify your class, it won't load and you won't be able to use that
# operator, property, or interface.
classes = (
operator.ImportAlignmentCSV,
operator.BuildAlignment,
operator.SurveyPoint,
prop.BIMAlignmentBuilderProperties,
ui.BIM_PT_alignment,
)
def menu_func_import(self, context):
self.layout.operator(operator.ImportAlignmentCSV.bl_idname, text="Alignment (.csv)")
# When the add-on loads, this register function is called. This allows you to
# perform additional tasks during startup. If you need to store custom
# properties, this is where you tell Blender where they are going to be stored.
# You might see more advanced registrations happening in other modules.
def register():
# Properties are usually stored on bpy.types.Scene when they are something
# that affects everything in the project, or bpy.types.Object when they
# affect a single BIM element.
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
bpy.types.Scene.BIMAlignmentBuilderProperties = bpy.props.PointerProperty(type=prop.BIMAlignmentBuilderProperties)
# When someone disables the add-on, we need to unload everything we loaded. This
# does the reverse of the register function.
def unregister():
del bpy.types.Scene.BIMAlignmentBuilderProperties
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
@@ -0,0 +1,80 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2022 Dion Moult <dion@thinkmoult.com>
#
# 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/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a data.py file to load data for its interface panels to
# display. When a panel needs to show information that doesn't come from a
# Blender property, it gets that data from one of these classes. This separation
# of "fetching data" and "displaying data" is a common concept that makes UI
# code much simpler, more efficient, and less error-prone to refresh data.
import bonsai.tool as tool
# All data must have a refresh function. The refresh function simply sets all
# data class to be not yet loaded. So the next time the interface is drawn to
# the user, it will force the data to be reloaded.
def refresh():
# When you define your own data classes, just add to this list!
AlignmentBuilderData.is_loaded = False
# This is a sample data class. It correlates to a single interface panel. Panels
# should not share data classes. This makes it easy to write your interface
# without having your code mixed in with other parts of the interface. As a
# convention, the class is named the same name as the panel.
class AlignmentBuilderData:
# All data classes must have two variables. One to store all the data it has
# loaded and another to store the load state.
data = {}
is_loaded = False
x = 0.0
y = 0.0
# Every data class must have a load function. This lets us load data in a
# predictable manner.
@classmethod
def load(cls):
# The load function always has two responsibilities: populate the data,
# and set is_loaded to true.
cls.data = {
"has_project": cls.has_project(),
"x" : cls.x(),
"y" : cls.y()
}
cls.is_loaded = True
@classmethod
def has_project(cls):
# Here, we check whether or not there is an active IFC project in our
# Blender session.
return bool(tool.Ifc.get())
@classmethod
def x(cls):
return cls.x
@classmethod
def y(cls):
return cls.y
@@ -18,6 +18,17 @@
# pyright: reportUnnecessaryTypeIgnoreComment=error
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has an operator.py file to define all of the buttons that a user
# can click on from the Blender interface. Blender calls these buttons
# "Operators", since they correlate to a single user operation.
import os
import ifcopenshell.api.alignment
@@ -28,7 +39,7 @@ import json
import time
import calendar
import isodate
import bonsai.core.sequence as core
import bonsai.core.alignment as core
import bonsai.tool as tool
import bonsai.bim.module.sequence.helper as helper
import ifcopenshell.api.spatial
@@ -112,3 +123,41 @@ class ImportAlignmentCSV(bpy.types.Operator, tool.Ifc.Operator, ImportHelper):
tool.Collector.assign(alignment_obj, should_clean_users_collection=False)
self.report({"INFO"}, "Imported in %s seconds" % (time.time() - start))
# Each button correlates to a class like the one below. In this case, we're
# creating a new button that will execute a hello world feature.
class BuildAlignment(bpy.types.Operator, tool.Ifc.Operator):
# Every operator has a unique ID. If you enable Python tooltips and hover
# over any button in the interface, you will see each button will run a
# function that uses this ID. For example, hovering over this button will
# show that the code it executes is "bpy.ops.bim.demonstrate_hello_world()"
bl_idname = "bim.build_alignment"
# In the interface, this button will have the text "Build Alignment".
bl_label = "Build Alignment"
# This code means that the user can undo or redo after pressing the button.
bl_options = {"REGISTER", "UNDO"}
# When hovering over the button, this helpful description will be shown.
bl_description = "Builds a dummy alignment"
# When the button is pressed, this _execute() function will run.
def _execute(self, context):
# Every operator should do one thing only: execute a core function. In
# order to execute a core function, the operator's responsibility is to
# pass in all of the inputs the core needs to do its job.
# A core function simply tells tools what to do, so a core function will
# always need at least one tool as an input.
core.build_alignment(tool.Alignment)
class SurveyPoint(bpy.types.Operator,tool.Ifc.Operator):
bl_idname = "bim.add_survey_point"
bl_label = "Add Survey Point"
bl_options = {"REGISTER","UNDO"}
bl_description = "Adds a survey point"
def _execute(self,context):
core.add_survey_point(tool.Alignment,x=bpy.context.scene.BIMAlignmentBuilderProperties.x,y=bpy.context.scene.BIMAlignmentBuilderProperties.y)
@@ -0,0 +1,64 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2022 Dion Moult <dion@thinkmoult.com>
#
# 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/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a prop.py file to define Blender properties. Any time you
# want an interface widget like an input field, dropdown, checkbox, or number
# slider, you need a Blender property to store that widget's data. If you want
# to store data that will affect the Blender interface, you also need a
# property. Properties are stored in the .blend file, so when your user closes
# their Blender session, and reopens it, things are how they left it.
import bpy
from bpy.types import PropertyGroup
# Properties have many different data types. We won't use all of them in this
# demo module, but this is a list for your reference.
from bpy.props import (
PointerProperty,
StringProperty,
EnumProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
CollectionProperty,
)
# All properties must belong in a property group. Usually, you'd have a group
# named after your module.
class BIMAlignmentBuilderProperties(PropertyGroup):
# This first property is a string. This means that in the interface, it will
# represent a text input field. We can give it a name and a default value.
# The name will be the label shown next to the input field in the interface.
name: StringProperty(name="Name", default="New Project Name")
# Not all properties need to be shown using their equivalent input widget.
# In this case, we can store a message string, but we will never show it as
# an input text field in the ui.py.
message: StringProperty(name="Message")
show_hints: BoolProperty(name="Show Hints", default=False)
#webui_message: StringProperty(name="Web UI Message", default="Hello, Web UI!")
x: FloatProperty(name="x")
y: FloatProperty(name="y")
@@ -0,0 +1,140 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2022 Dion Moult <dion@thinkmoult.com>
#
# 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/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a ui.py file to define its interface. Interfaces describe how
# panels, buttons, labels, and input fields are laid out.
import bpy
from bonsai.bim.module.alignment.data import AlignmentBuilderData
# Every panel in the interface correlates to one of these classes. If you enable
# the "Developer Extras" option in Blender, then you can actually right click on
# any panel in Blender, and click "Edit Source". This will bring you to a ui.py
# file like this one where you can see this code. Pretty neat!
class BIM_PT_alignment(bpy.types.Panel):
# Every panel has a title.
bl_label = "Alignment Demo"
# Every panel must have an ID. It must be unique. For example, you may want
# to later reference the panel (such as if you want to create a nested
# subpanel).
bl_idname = "BIM_PT_alignment"
# This tells the panel to appear in the properties section (in the bottom
# right by default) of the Blender interface.
bl_space_type = "VIEW_3D" #"PROPERTIES"
bl_region_type = "UI" #"WINDOW"
bl_category = "Survey"
# This tells the panel to appear in the "scene" tab of the properties panel.
#bl_context = "scene"
# Every panel has a draw function. This draws all the layout of the panel,
# including all of its labels, buttons, and so on. Note that if the panel is
# hidden, this draw function will not be called.
def draw(self, context):
# Before drawing any content, the panel must load any dynamic variables
# that it will show. Most panels have dynamic content, which display
# changing data from your BIM model. You must load that data first. The
# two lines are always the same, "if not loaded, then load".
if not AlignmentBuilderData.is_loaded:
# Each panel should have its own data class that it loads data from.
# Note that we only load data if it hasn't already been loaded.
# This is because interface panels are drawn continuously. This
# draw() function will be called every time you scroll or move your
# mouse over it. Loading data is slow, so we only refresh data when
# we have to.
AlignmentBuilderData.load()
# Interface panels often show properties. For convenience, define where
# the properties are stored for the module.
self.props = context.scene.BIMAlignmentBuilderProperties
# This defines a new "row" in our layout. When a new row is defined, the
# things on that row, like buttons, labels, and input fields, show on a
# new line.
row = self.layout.row()
# This is the simplest interface element - a label placed in our row.
# If you enable the "Icon Viewer" add-on, you can view a list of
# Blender's built-in icons to choose from in the Blender text editor's
# side panel.
row.label(text="This is a demo panel", icon="INFO")
# Our interface can contain simple logic. For example, if we don't have
# an IFC project, show an error message and don't draw anything else.
# The ui.py should always have very simple logic. Details like how to
# determine whether we have a project is delegated to the data loader.
if not AlignmentBuilderData.data["has_project"]:
row = self.layout.row()
row.label(text="Load or create an IFC project first", icon="ERROR")
return
row = self.layout.row()
# When you want to show a button in the interface, you have to specify
# an operator. Operators are defined in operator.py. You reference an
# operator using its unique ID.
row.operator("bim.build_alignment")
# Blender properties can be used to affect what your panel shows. Notice
# how the logic is very simple. Only use simple boolean predicates and
# loops in your layout. No complex logic should ever been seen in the
# interface code.
#if self.props.message:
# row = self.layout.row()
# row.label(text=self.props.message)
#row = self.layout.row(align=True)
#row.label(text="Build Dummy Alignment")
# Sometimes you need data that doesn't come from Blender properties,
# like from your IFC model. In this case, just get some data from your
# data loader. For those familiar with how templating languages work,
# this is exactly the same.
#row.label(text=AlignmentData.data["project_name"])
#row = self.layout.row()
# We've seen how to show text labels and buttons using operators. What
# about text input fields, number sliders, dropdowns, checkboxes, and
# scrollable lists? The way Blender works is that you simply show a
# Blender property in your interface. The data type of that property
# determines which UI widget is shown. A text property will show a text
# field. A number property will show a number slider. An enum property
# will show a drop down. And so on. In this case, our name property is a
# text data type, so expect to see a text input field show up here.
#row.prop(self.props, "name")
#row = self.layout.row()
# Here's another button, referencing another operator.
#row.operator("bim.demonstrate_rename_project")
row = self.layout.row()
row.label(text="Survey Point")
row.prop(self.props,"x")
row.prop(self.props,"y")
row = self.layout.row()
row.operator("bim.add_survey_point")
#if self.props.show_hints:
# row = self.layout.row()
# row.label(text="Name cannot be blank!")
@@ -1401,6 +1401,7 @@ class ActivateBcfViewpoint(bpy.types.Operator):
self.hide_spaces(context)
def hide_spaces(self, context: bpy.types.Context) -> None:
assert context.area
old = context.area.type
context.area.type = "VIEW_3D"
bpy.ops.object.select_all(action="DESELECT")
@@ -30,6 +30,7 @@ from bpy.props import (
FloatVectorProperty,
CollectionProperty,
)
from typing import TYPE_CHECKING
class BIMContextProperties(PropertyGroup):
@@ -66,3 +67,10 @@ class BIMContextProperties(PropertyGroup):
)
active_context_id: IntProperty(name="Active Context Id")
context_attributes: CollectionProperty(name="Context Attributes", type=Attribute)
if TYPE_CHECKING:
contexts: str
subcontexts: str
target_views: str
active_context_id: int
context_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
+3 -2
View File
@@ -33,13 +33,14 @@ class BIM_PT_context(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not ContextData.is_loaded:
ContextData.load()
props = context.scene.BIMContextProperties
assert self.layout
props = tool.Context.get_context_props()
row = self.layout.row(align=True)
row.prop(props, "contexts", text="")
+2 -2
View File
@@ -90,7 +90,7 @@ def update_cost_item_identification(self: "CostItem", context: bpy.types.Context
**{"cost_item": self.file.by_id(self.ifc_definition_id), "attributes": {"Identification": self.identification}},
)
if props.active_cost_item_id == self.ifc_definition_id:
attribute = props.cost_item_attributes.get("Identification")
attribute = props.cost_item_attributes["Identification"]
attribute.string_value = self.identification
@@ -105,7 +105,7 @@ def update_cost_item_name(self: "CostItem", context: bpy.types.Context) -> None:
**{"cost_item": self.file.by_id(self.ifc_definition_id), "attributes": {"Name": self.name}},
)
if props.active_cost_item_id == self.ifc_definition_id:
attribute = props.cost_item_attributes.get("Name")
attribute = props.cost_item_attributes["Name"]
attribute.string_value = self.name
@@ -28,7 +28,6 @@ classes = (
operator.AddAnnotationType,
operator.AddDrawing,
operator.AddDrawingStyle,
operator.AddDrawingStyleAttribute,
operator.AddDrawingToSheet,
operator.AddReference,
operator.AddReferenceImage,
@@ -80,12 +79,10 @@ classes = (
operator.RemoveDrawing,
operator.RemoveDrawingFromSheet,
operator.RemoveDrawingStyle,
operator.RemoveDrawingStyleAttribute,
operator.RemoveReference,
operator.RemoveSchedule,
operator.RemoveSheet,
operator.RemoveTextLiteral,
operator.ResizeText,
operator.SaveDrawingStyle,
operator.SaveDrawingStylesData,
operator.SelectAllDrawings,
@@ -29,52 +29,6 @@ from typing import Optional
class Annotator:
@staticmethod
def add_text(related_element: Optional[ifcopenshell.entity_instance] = None) -> bpy.types.Object:
curve = bpy.data.curves.new(type="FONT", name="Text")
curve.body = "TEXT"
obj = bpy.data.objects.new("Text", curve)
obj.matrix_world = bpy.context.scene.camera.matrix_world
if related_element is None:
location, _, _, _ = Annotator.get_placeholder_coords(bpy.context)
else:
curve.BIMAssignedProductProperties.related_element = related_element
location = related_element.location
obj.location = location
obj.hide_render = True
font = bpy.data.fonts.get("OpenGost TypeB TT")
if not font:
font = bpy.data.fonts.load(
tool.Blender.get_data_dir_path(Path("fonts") / "OpenGost Type B TT.ttf").__str__()
)
font.name = "OpenGost Type B TT"
curve.font = font
props = tool.Drawing.get_text_props(obj)
props.font_size = "2.5"
collection = tool.Blender.get_object_bim_props(bpy.context.scene.camera).collection
collection.objects.link(obj)
Annotator.resize_text(obj)
return obj
@staticmethod
def resize_text(text_obj: bpy.types.Object) -> None:
camera = None
group = tool.Drawing.get_drawing_group(tool.Ifc.get_entity(text_obj))
for element in tool.Drawing.get_drawing_elements(group):
if element.is_a("IfcAnnotation") and element.ObjectType == "DRAWING":
camera = tool.Ifc.get_object(element)
break
if not camera:
return
# This is a magic number for OpenGost
font_size = 1.6 / 1000
props = tool.Drawing.get_text_props(text_obj)
font_size *= float(props.font_size)
font_size /= tool.Drawing.get_scale_ratio(tool.Drawing.get_diagram_scale(camera)["Scale"])
text_obj.data.size = font_size
@staticmethod
def add_line_to_annotation(
obj: bpy.types.Object, co1: Optional[Vector] = None, co2: Optional[Vector] = None
@@ -129,8 +83,14 @@ class Annotator:
def get_annotation_obj(
drawing: ifcopenshell.entity_instance, object_type: str, data_type: tool.Drawing.ANNOTATION_DATA_TYPE
) -> bpy.types.Object:
assert bpy.context.scene
camera = tool.Ifc.get_object(drawing)
co1, _, _, _ = Annotator.get_placeholder_coords(camera)
assert isinstance(camera, bpy.types.Object)
# those annotations you want to obey the depth of the 3d cursor
if object_type == "PLAN_LEVEL":
co1 = bpy.context.scene.cursor.location.copy()
else:
co1, _, _, _ = Annotator.get_placeholder_coords(camera)
matrix_world = tool.Drawing.get_camera_matrix(camera)
matrix_world.translation = co1
collection = tool.Blender.get_object_bim_props(camera).collection
+3 -5
View File
@@ -118,7 +118,7 @@ class DrawingsData:
return len([e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"])
@classmethod
def location_hint(cls):
def location_hint(cls) -> list[tuple[tool.Drawing.LocationHintType, str, str]]:
props = tool.Drawing.get_document_props()
if props.target_view in ["PLAN_VIEW", "REFLECTED_PLAN_VIEW"]:
results = [("0", "Origin", "")]
@@ -132,12 +132,10 @@ class DrawingsData:
@classmethod
def active_drawing_pset_data(cls):
ifc_file = tool.Ifc.get()
props = tool.Drawing.get_document_props()
drawing_id = props.active_drawing_id
if drawing_id == 0:
drawing = props.get_active_drawing()
if drawing is None:
return {}
drawing = ifc_file.by_id(drawing_id)
return ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing")
@@ -1982,10 +1982,16 @@ class DecorationsHandler:
return results
def __call__(self, context):
collection, _ = helper.get_active_drawing(context.scene)
if collection is None:
props = tool.Drawing.get_document_props()
drawing = props.get_active_drawing()
if drawing is None:
return
camera = tool.Ifc.get_object(drawing)
assert isinstance(camera, bpy.types.Object)
collection = tool.Blender.get_object_bim_props(camera).collection
assert collection
if not DrawingsData.is_loaded:
DrawingsData.load()
+1 -13
View File
@@ -305,7 +305,7 @@ def format_distance(
if unit_length == "MILLIMETERS":
value = value / 1000
if precision:
if precision and isinstance(precision, float):
value = precision * round(float(value) / precision)
if decimal_places is not None:
@@ -392,18 +392,6 @@ def format_distance(
return tx_dist
def get_active_drawing(
scene: bpy.types.Scene,
) -> Union[tuple[bpy.types.Collection, bpy.types.Camera], tuple[None, None]]:
"""Get active drawing collection and camera"""
props = tool.Drawing.get_document_props()
try:
camera = tool.Ifc.get_object(tool.Ifc.get().by_id(props.active_drawing_id))
return tool.Blender.get_object_bim_props(camera).collection, camera
except:
return None, None
def get_project_collection(scene):
"""Get main project collection"""
+190 -171
View File
@@ -29,6 +29,8 @@ import numpy as np
import multiprocessing
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.api.pset
import ifcopenshell.api.style
import ifcopenshell.ifcopenshell_wrapper
import ifcopenshell.geom
import ifcopenshell.util.selector
@@ -45,8 +47,8 @@ import bonsai.bim.module.drawing.sheeter as sheeter
import bonsai.bim.export_ifc
from bpy_extras.io_utils import ImportHelper
from bonsai.bim.module.drawing.decoration import CutDecorator
from bonsai.bim.module.drawing.data import DecoratorData, DrawingsData
from typing import NamedTuple, List, Union, Optional, Literal, TYPE_CHECKING, Any
from bonsai.bim.module.drawing.data import DecoratorData
from typing import NamedTuple, List, Union, Optional, Literal, TYPE_CHECKING, Any, TypedDict
from lxml import etree
from math import radians
from mathutils import Vector, Color, Matrix
@@ -57,6 +59,7 @@ from pathlib import Path
from bpy_extras.image_utils import load_image
if TYPE_CHECKING:
from bonsai.bim.module.drawing.prop import RenderType
from bonsai.bim.module.project.prop import Link
from bpy._typing import rna_enums
@@ -136,13 +139,19 @@ class AddDrawing(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_drawing"
bl_label = "Add Drawing"
bl_options = {"REGISTER", "UNDO"}
bl_description = "Add a drawing view to the IFC project"
bl_description = (
"Add a drawing view to the IFC project.\n\n"
"For all views besides MODEL_VIEW camera will be placed at the current cursor position,\n"
"for MODEL_VIEW camera will be aligned to the current viewport position and orientation."
)
def _execute(self, context):
props = tool.Drawing.get_document_props()
hint = props.location_hint
if props.target_view in ["PLAN_VIEW", "REFLECTED_PLAN_VIEW"]:
hint = int(hint)
else:
assert hint in tool.Drawing.LOCATION_HINT_LITERALS
core.add_drawing(
tool.Ifc,
tool.Collector,
@@ -150,11 +159,12 @@ class AddDrawing(bpy.types.Operator, tool.Ifc.Operator):
target_view=props.target_view,
location_hint=hint,
)
try:
drawing = tool.Ifc.get().by_id(props.active_drawing_id)
core.sync_references(tool.Ifc, tool.Collector, tool.Drawing, drawing=drawing)
except:
pass
# TODO: Why need to resync active drawing, if it wasn't changed.
drawing = props.get_active_drawing()
if drawing is None:
return
core.sync_references(tool.Ifc, tool.Collector, tool.Drawing, drawing=drawing)
class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
@@ -167,7 +177,6 @@ class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
@classmethod
def poll(cls, context):
props = tool.Drawing.get_document_props()
if not tool.Drawing.get_active_drawing_item():
cls.poll_message_set("No drawing selected.")
return False
@@ -190,11 +199,12 @@ class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
drawing=tool.Ifc.get().by_id(self.drawing),
should_duplicate_annotations=self.should_duplicate_annotations,
)
try:
drawing = tool.Ifc.get().by_id(props.active_drawing_id)
core.sync_references(tool.Ifc, tool.Collector, tool.Drawing, drawing=drawing)
except:
pass
# TODO: Why need to resync active drawing, if it wasn't changed.
drawing = props.get_active_drawing()
if drawing is None:
return
core.sync_references(tool.Ifc, tool.Collector, tool.Drawing, drawing=drawing)
class CreateDrawing(bpy.types.Operator):
@@ -398,17 +408,23 @@ class CreateDrawing(bpy.types.Operator):
for obj in bpy.context.view_layer.objects:
obj.hide_render = obj.name not in visible_object_names
assert context.scene and context.view_layer and context.screen
context.scene.render.filepath = str(Path(svg_path).with_suffix(".png"))
drawing_style = self.props.drawing_styles[self.cprops.active_drawing_style_index]
assert (drawing_style := self.cprops.get_active_drawing_style())
if drawing_style.render_type == "DEFAULT":
bpy.ops.render.render(write_still=True)
else:
previous_visibility = {}
for obj in tool.Blender.get_object_bim_props(self.camera).collection.objects:
if bpy.context.view_layer.objects.get(obj.name):
previous_visibility: dict[str, bool] = {}
collection = tool.Blender.get_object_bim_props(self.camera).collection
assert collection
# Hie annotations.
for obj in collection.objects:
if context.view_layer.objects.get(obj.name):
previous_visibility[obj.name] = obj.hide_get()
obj.hide_set(True)
# Hide objects that shouldn't appear on render - empties, camera, grids, etc.
for obj in context.visible_objects:
if (
(not obj.data and not obj.instance_collection)
@@ -417,11 +433,11 @@ class CreateDrawing(bpy.types.Operator):
or "IfcGridAxis/" in obj.name
or "IfcOpeningElement/" in obj.name
):
if bpy.context.view_layer.objects.get(obj.name):
if context.view_layer.objects.get(obj.name):
previous_visibility[obj.name] = obj.hide_get()
obj.hide_set(True)
space = self.get_view_3d(context.screen.areas)
assert (space := tool.Blender.get_view3d_space())
previous_shading = space.shading.type
previous_format = context.scene.render.image_settings.file_format
space.shading.type = "RENDERED"
@@ -437,15 +453,15 @@ class CreateDrawing(bpy.types.Operator):
return svg_path
def get_linework_contexts(self, ifc: ifcopenshell.file, target_view: str) -> LineworkContexts:
plan_body_target_contexts = []
plan_body_model_contexts = []
model_body_target_contexts = []
model_body_model_contexts = []
plan_body_target_contexts: list[int] = []
plan_body_model_contexts: list[int] = []
model_body_target_contexts: list[int] = []
model_body_model_contexts: list[int] = []
plan_annotation_target_contexts = []
plan_annotation_model_contexts = []
model_annotation_target_contexts = []
model_annotation_model_contexts = []
plan_annotation_target_contexts: list[int] = []
plan_annotation_model_contexts: list[int] = []
model_annotation_target_contexts: list[int] = []
model_annotation_model_contexts: list[int] = []
for rep_context in ifc.by_type("IfcGeometricRepresentationContext"):
if rep_context.is_a("IfcGeometricRepresentationSubContext"):
@@ -517,8 +533,8 @@ class CreateDrawing(bpy.types.Operator):
target_view: str,
) -> None:
drawing_elements = drawing_elements.copy()
contexts: list[list[int]] = getattr(contexts, context_type)
for context in contexts:
contexts_: list[list[int]] = getattr(contexts, context_type)
for context in contexts_:
with profile(f"Processing {context_type} context"):
if not context or not drawing_elements:
continue
@@ -541,7 +557,7 @@ class CreateDrawing(bpy.types.Operator):
tree.add_element(elem)
drawing_elements -= processed
def generate_bisect_linework(self, context: bpy.types.Context, root):
def generate_bisect_linework(self, context: bpy.types.Context, root) -> None:
camera_matrix_i = context.scene.camera.matrix_world.inverted()
group = root.find("{http://www.w3.org/2000/svg}g")
@@ -576,7 +592,7 @@ class CreateDrawing(bpy.types.Operator):
path.attrib["d"] = d
group.append(g)
def generate_wall_layers(self, context: bpy.types.Context, root):
def generate_wall_layers(self, context: bpy.types.Context, root) -> None:
for el in root.findall(".//{http://www.w3.org/2000/svg}g[@{http://www.ifcopenshell.org/ns}guid]"):
if "projection" in el.get("class", "").split():
continue
@@ -1570,12 +1586,6 @@ class CreateDrawing(bpy.types.Operator):
def is_landscape(self, render):
return render.resolution_x > render.resolution_y
def get_view_3d(self, areas):
for area in areas:
if area.type != "VIEW_3D":
continue
return area.spaces.active
def get_material_name(self, element: ifcopenshell.entity_instance) -> str:
if hasattr(element, "Name") and element.Name:
return element.Name
@@ -1613,8 +1623,9 @@ class AddAnnotation(bpy.types.Operator, tool.Ifc.Operator):
def _execute(self, context):
props = tool.Drawing.get_annotation_props()
if not (drawing := tool.Ifc.get_entity(context.scene.camera)):
self.report({"WARNING"}, "Not a BIM camera")
dprops = tool.Drawing.get_document_props()
if not (drawing := dprops.get_active_drawing()):
self.report({"WARNING"}, "No active drawing.")
return
obj = core.add_annotation(
@@ -1717,7 +1728,7 @@ class SelectAllSheets(bpy.types.Operator):
return {"FINISHED"}
class OpenSheet(bpy.types.Operator, tool.Ifc.Operator):
class OpenSheet(bpy.types.Operator):
bl_idname = "bim.open_sheet"
bl_label = "Open Sheet"
bl_description = (
@@ -2159,8 +2170,6 @@ class ActivateDrawingBase(tool.Ifc.Operator):
tool.Blender.set_viewport_position(viewport_position)
dprops.active_drawing_id = self.drawing
# reset DrawingsData to reload_drawing_styles work correctly
DrawingsData.is_loaded = False
dprops.drawing_styles.clear()
if ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing", "HasUnderlay"):
bpy.ops.bim.reload_drawing_styles()
@@ -2196,13 +2205,6 @@ class ActivateDrawing(bpy.types.Operator, ActivateDrawingBase):
should_view_from_camera: bpy.props.BoolProperty(name="Should View From Camera", default=True, options={"SKIP_SAVE"})
use_quick_preview: bpy.props.BoolProperty(name="Use Quick Preview", default=False, options={"SKIP_SAVE"})
@classmethod
def poll(cls, context):
if not tool.Drawing.get_active_drawing_item():
cls.poll_message_set("No drawing selected.")
return False
return True
class ActivateDrawingFromSheet(bpy.types.Operator, ActivateDrawingBase):
bl_idname = "bim.activate_drawing_from_sheet"
@@ -2243,19 +2245,6 @@ class SelectDocIfcFile(bpy.types.Operator, ImportHelper):
return {"FINISHED"}
class ResizeText(bpy.types.Operator):
bl_idname = "bim.resize_text"
bl_label = "Resize Text"
bl_options = {"REGISTER", "UNDO"}
# TODO: check undo redo
def execute(self, context):
for obj in tool.Blender.get_object_bim_props(context.scene.camera).collection.objects:
if isinstance(obj.data, bpy.types.TextCurve):
annotation.Annotator.resize_text(obj)
return {"FINISHED"}
class RemoveDrawing(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_drawing"
bl_label = "Remove Drawing"
@@ -2303,37 +2292,25 @@ class RemoveDrawing(bpy.types.Operator, tool.Ifc.Operator):
props.should_draw_decorations = False
class DrawingStyleJson(TypedDict):
render_type: "RenderType"
raster_style: dict[str, Any]
class ReloadDrawingStyles(bpy.types.Operator):
bl_idname = "bim.reload_drawing_styles"
bl_label = "Reload Drawing Styles"
bl_options = {"REGISTER", "UNDO"}
bl_description = "Reload drawing styles for the active camera"
bl_description = "Reload drawing styles for the active camera from the related JSON file."
def execute(self, context):
if not DrawingsData.is_loaded:
DrawingsData.load()
drawing_pset_data = DrawingsData.data["active_drawing_pset_data"]
props = tool.Drawing.get_document_props()
assert (drawing := props.get_active_drawing())
drawing_pset_data = ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing")
assert context.scene and (camera := context.scene.camera)
camera_props = tool.Drawing.get_camera_props(camera)
# added this part as a temporary fallback
# TODO: should remove it a bit later when projects get more accommodated
# with saving shadingstyles to ifc and separate json file
if "ShadingStyles" not in drawing_pset_data:
ifc_file = tool.Ifc.get()
pset = ifc_file.by_id(drawing_pset_data["id"])
edit_properties = {
"ShadingStyles": (
shading_styles_path := tool.Drawing.get_default_drawing_resource_path("ShadingStyles")
),
"CurrentShadingStyle": tool.Drawing.get_default_shading_style(),
}
ifcopenshell.api.run("pset.edit_pset", ifc_file, pset=pset, properties=edit_properties)
tool.Drawing.setup_shading_styles_path(shading_styles_path)
DrawingsData.load()
drawing_pset_data = DrawingsData.data["active_drawing_pset_data"]
if "ShadingStyles" not in drawing_pset_data:
self.report({"ERROR"}, "Could not find shading styles path in EPset_Drawing.ShadingStyles.")
return {"CANCELLED"}
@@ -2353,9 +2330,8 @@ class ReloadDrawingStyles(bpy.types.Operator):
shutil.copy(ootb_resource, json_path)
with open(json_path, "r") as fi:
shading_styles_json = json.load(fi)
shading_styles_json: dict[str, DrawingStyleJson] = json.load(fi)
props = tool.Drawing.get_document_props()
drawing_styles = props.drawing_styles
drawing_styles.clear()
styles = [style for style in shading_styles_json]
@@ -2367,20 +2343,22 @@ class ReloadDrawingStyles(bpy.types.Operator):
drawing_style.raster_style = json.dumps(style_data["raster_style"])
if current_style is not None:
try:
if current_style not in styles:
self.report({"WARNING"}, f"Could not find style {current_style} in EPset_Drawing.ShadingStyles.")
else:
camera_props.active_drawing_style_index = styles.index(current_style)
except ValueError:
self.report({"INFO"}, f"Could not find style {current_style} in EPset_Drawing.ShadingStyles.")
return {"FINISHED"}
# NOTE: Ifc Operator is not necessary for add and remove,
# as underlying save operator creates ifc undo step for us,
# but we keep it to make it more safe in case operators composition will change.
class AddDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_drawing_style"
bl_label = "Add Drawing Style"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
def _execute(self, context):
assert context.scene and (camera_obj := context.scene.camera)
props = tool.Drawing.get_document_props()
drawing_styles = props.drawing_styles
@@ -2398,7 +2376,7 @@ class RemoveDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
index: bpy.props.IntProperty()
def execute(self, context):
def _execute(self, context):
assert context.scene and (camera_obj := context.scene.camera)
props = tool.Drawing.get_document_props()
props.drawing_styles.remove(self.index)
@@ -2412,13 +2390,13 @@ class SaveDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.save_drawing_style"
bl_label = "Save Drawing Style"
bl_options = {"REGISTER", "UNDO"}
bl_description = "Save current render setting to currently selected drawing style. Also resaves styles data to IFC"
bl_description = "Save current render settings to currently selected drawing style. Also resaves styles data to IFC"
index: bpy.props.StringProperty()
# TODO: check undo redo
def execute(self, context):
space = self.get_view_3d(context) # Do not remove. It is used later in eval
def _execute(self, context):
assert (space := tool.Blender.get_view3d_space()) # Do not remove. It is used later in eval
scene = context.scene
assert scene
style = {}
@@ -2467,16 +2445,11 @@ class SaveDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
bpy.ops.bim.save_drawing_styles_data()
return {"FINISHED"}
def get_view_3d(self, context):
for area in context.screen.areas:
if area.type != "VIEW_3D":
continue
return area.spaces.active
class SaveDrawingStylesData(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.save_drawing_styles_data"
bl_label = "Save Drawing Styles Data"
bl_description = "Save current drawing styles settings to IFC and JSON."
bl_options = {"REGISTER", "UNDO"}
skip_updating_current_style: bpy.props.BoolProperty(default=False)
@@ -2484,11 +2457,10 @@ class SaveDrawingStylesData(bpy.types.Operator, tool.Ifc.Operator):
rename_style_from: bpy.props.StringProperty(default="")
rename_style_to: bpy.props.StringProperty(default="")
def execute(self, context):
if not DrawingsData.is_loaded:
DrawingsData.load()
drawing_pset_data = DrawingsData.data["active_drawing_pset_data"]
def _execute(self, context):
props = tool.Drawing.get_document_props()
assert (drawing := props.get_active_drawing())
drawing_pset_data = ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing")
drawing_styles = props.drawing_styles
rel_path = drawing_pset_data["ShadingStyles"]
@@ -2498,10 +2470,9 @@ class SaveDrawingStylesData(bpy.types.Operator, tool.Ifc.Operator):
self.report({"ERROR"}, "Shading styles file not found: {}".format(json_path))
return {"CANCELLED"}
styles_data = {}
styles_data: dict[str, DrawingStyleJson] = {}
for style in drawing_styles:
style_data = {"render_type": style.render_type, "raster_style": json.loads(style.raster_style)}
styles_data[style.name] = style_data
styles_data[style.name] = {"render_type": style.render_type, "raster_style": json.loads(style.raster_style)}
with open(json_path, "w") as fo:
json.dump(styles_data, fo, indent=4)
@@ -2518,11 +2489,10 @@ class SaveDrawingStylesData(bpy.types.Operator, tool.Ifc.Operator):
new_style_name = None
ifc_file = tool.Ifc.get()
drawing = ifc_file.by_id(props.active_drawing_id)
assert (drawing := props.get_active_drawing())
pset = tool.Pset.get_element_pset(drawing, "EPset_Drawing")
ifcopenshell.api.run(
"pset.edit_pset", ifc_file, pset=pset, properties={"CurrentShadingStyle": new_style_name}
)
assert pset
ifcopenshell.api.pset.edit_pset(ifc_file, pset=pset, properties={"CurrentShadingStyle": new_style_name})
bonsai.bim.handler.refresh_ui_data()
return {"FINISHED"}
@@ -2533,44 +2503,115 @@ class ActivateDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_label = "Activate Drawing Style"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
has_errors_during_activation = False
has_warnings_during_activation = False
def _execute(self, context):
scene = context.scene
assert scene and (camera := scene.camera)
camera_props = tool.Drawing.get_camera_props(camera)
ifc_file = tool.Ifc.get()
active_drawing_style_index = camera_props.active_drawing_style_index
props = tool.Drawing.get_document_props()
if active_drawing_style_index >= len(props.drawing_styles):
drawing_style = camera_props.get_active_drawing_style()
if drawing_style is None:
self.report({"ERROR"}, "Could not find active drawing style")
return {"CANCELLED"}
self.drawing_style = props.drawing_styles[active_drawing_style_index]
self.drawing_style = drawing_style
self.set_raster_style(context)
self.set_query(context)
drawing = ifc_file.by_id(props.active_drawing_id)
props = tool.Drawing.get_document_props()
assert (drawing := props.get_active_drawing())
pset = tool.Pset.get_element_pset(drawing, "EPset_Drawing")
ifcopenshell.api.run(
"pset.edit_pset", ifc_file, pset=pset, properties={"CurrentShadingStyle": self.drawing_style.name}
assert pset
ifcopenshell.api.pset.edit_pset(
ifc_file, pset=pset, properties={"CurrentShadingStyle": self.drawing_style.name}
)
bonsai.bim.handler.refresh_ui_data()
if self.has_warnings_during_activation:
self.report(
{"WARNING"},
"There were warnings setting some drawing style properies, see system console for the details.",
)
if self.has_errors_during_activation:
self.report(
{"WARNING"},
"There were errors setting some drawing style properies, see system console for the details.",
)
return {"FINISHED"}
def set_raster_style(self, context: bpy.types.Context) -> None:
scene = context.scene # Do not remove. It is used in exec later
space = self.get_view_3d(context) # Do not remove. It is used in exec later
assert (space := tool.Blender.get_view3d_space()) # Do not remove. It is used in exec later
style = json.loads(self.drawing_style.raster_style)
def preprocess(path: str, value: Any) -> tuple[str, Any, bool, bool]:
warning = False
skip = False
# @25.05.12
if path == "scene.render.engine" and value == "BLENDER_EEVEE":
value = "BLENDER_EEVEE_NEXT"
print(
f"Warning: Value 'BLENDER_EEVEE' is outdated for property '{path}' "
"since Blender 4.2 and should be replaced with 'BLENDER_EEVEE_NEXT' in shading_styles.json."
)
warning = True
# @25.05.12
if path == "scene.display.shading.wireframe_color_type" and value == "MATERIAL":
value = "THEME"
print(
f"Warning: Value 'MATERIAL' is outdated for property '{path}' "
"since Blender 4.0 and should be replaced with 'THEME' in shading_styles.json."
)
warning = True
# @25.05.12
elif path in ("scene.render.simplify_shadows", "scene.render.simplify_shadows_render"):
print(
f"Warning: Property '{path}' is removed "
"since Blender 4.2 and should be also removed from shading_styles.json."
)
warning = True
skip = True
# @25.05.12
elif path in ("space.overlay.backwire_opacity", "space.overlay.show_edges"):
print(
f"Warning: Property '{path}' is removed "
"since Blender 4.1 and should be also removed from shading_styles.json."
)
warning = True
skip = True
# @25.05.12
elif path in ("space.overlay.show_occlude_wire",):
print(
f"Warning: Property '{path}' is removed "
"since Blender 3.6 and should be also removed from shading_styles.json."
)
warning = True
skip = True
return path, value, warning, skip
for path, value in style.items():
path, value, warning, skip = preprocess(path, value)
self.has_warnings_during_activation |= warning
if skip:
continue
try:
if isinstance(value, str):
exec(f"{path} = '{value}'")
else:
exec(f"{path} = {value}")
except:
except Exception as e:
# Differences in Blender versions mean result in failures here
print(f"Failed to set shading style {path} to {value}")
print(f"Failed to set drawing style property '{path}' to '{value}'. Error: '{str(e)}'")
self.has_errors_during_activation = True
if "PYTEST_VERSION" in os.environ:
raise
def set_query(self, context: bpy.types.Context) -> None:
self.include_global_ids = []
@@ -2594,6 +2635,7 @@ class ActivateDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
def parse_filter_query(self, mode: Literal["INCLUDE", "EXCLUDE"], context: bpy.types.Context) -> None:
if mode == "INCLUDE":
assert context.scene
objects = context.scene.objects
elif mode == "EXCLUDE":
objects = context.visible_objects
@@ -2611,13 +2653,6 @@ class ActivateDrawingStyle(bpy.types.Operator, tool.Ifc.Operator):
if global_id in self.exclude_global_ids:
obj.hide_viewport = True # Note: this breaks alt-H
def get_view_3d(self, context: bpy.types.Context) -> bpy.types.SpaceView3D:
for area in context.screen.areas:
if area.type != "VIEW_3D":
continue
return area.spaces.active
assert False, "Space is not found."
class RemoveSheet(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_sheet"
@@ -2851,35 +2886,6 @@ class OpenReference(bpy.types.Operator, tool.Ifc.Operator):
core.open_reference(tool.Drawing, reference=tool.Ifc.get().by_id(self.reference))
# TODO: dead code - drawing style attributes are never used?
class AddDrawingStyleAttribute(bpy.types.Operator):
bl_idname = "bim.add_drawing_style_attribute"
bl_label = "Add Drawing Style Attribute"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
assert context.scene and (camera := context.scene.camera)
props = tool.Drawing.get_camera_props(camera)
dprops = tool.Drawing.get_document_props()
dprops.drawing_styles[props.active_drawing_style_index].attributes.add()
return {"FINISHED"}
# TODO: dead code - drawing style attributes are never used?
class RemoveDrawingStyleAttribute(bpy.types.Operator):
bl_idname = "bim.remove_drawing_style_attribute"
bl_label = "Remove Drawing Style Attribute"
bl_options = {"REGISTER", "UNDO"}
index: bpy.props.IntProperty()
def execute(self, context):
assert context.scene and (camera := context.scene.camera)
props = tool.Drawing.get_camera_props(camera)
dprops = tool.Drawing.get_document_props()
dprops.drawing_styles[props.active_drawing_style_index].attributes.remove(self.index)
return {"FINISHED"}
class CleanWireframes(bpy.types.Operator):
bl_idname = "bim.clean_wireframes"
bl_label = "Clean Wireframes"
@@ -3090,6 +3096,7 @@ class OrderTextLiteralDown(bpy.types.Operator):
return {"FINISHED"}
# Ifc Operator is unnecessary, because suboperator is handling IFC changes.
class AssignSelectedObjectAsProduct(bpy.types.Operator):
bl_idname = "bim.assign_selected_as_product"
bl_label = "Assign Selected Object As Product"
@@ -3103,18 +3110,25 @@ class AssignSelectedObjectAsProduct(bpy.types.Operator):
return True
def execute(self, context):
assert bpy.context.view_layer
objs = context.selected_objects[:]
obj1 = objs[0]
obj1, obj2 = objs
element1 = tool.Ifc.get_entity(obj1)
obj2 = objs[1]
element2 = tool.Ifc.get_entity(obj2)
assert element1 and element2
if element1.is_a("IfcAnnotation"):
other_selected_object = obj2
bpy.context.view_layer.objects.active = obj1
elif element2.is_a("IfcAnnotation"):
other_selected_object = obj1
bpy.context.view_layer.objects.active = obj2
context.active_object.BIMAssignedProductProperties.relating_product = other_selected_object
else:
self.report({"ERROR"}, "One of the selected objects must be IfcAnnotation.")
return {"CANCELLED"}
assert (active_obj := context.active_object)
props = tool.Drawing.get_object_assigned_product_props(active_obj)
props.relating_product = other_selected_object
bpy.ops.bim.edit_assigned_product()
return {"FINISHED"}
@@ -3126,9 +3140,11 @@ class EditAssignedProduct(bpy.types.Operator, tool.Ifc.Operator):
def _execute(self, context):
product = None
if context.active_object.BIMAssignedProductProperties.relating_product:
product = tool.Ifc.get_entity(context.active_object.BIMAssignedProductProperties.relating_product)
core.edit_assigned_product(tool.Ifc, tool.Drawing, obj=context.active_object, product=product)
assert (obj := context.active_object)
props = tool.Drawing.get_object_assigned_product_props(obj)
if props.relating_product:
product = tool.Ifc.get_entity(props.relating_product)
core.edit_assigned_product(tool.Ifc, tool.Drawing, obj=obj, product=product)
tool.Blender.update_viewport()
@@ -3138,6 +3154,7 @@ class EnableEditingAssignedProduct(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
assert context.active_object
core.enable_editing_assigned_product(tool.Drawing, obj=context.active_object)
@@ -3147,6 +3164,7 @@ class DisableEditingAssignedProduct(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
assert context.active_object
core.disable_editing_assigned_product(tool.Drawing, obj=context.active_object)
@@ -3190,6 +3208,7 @@ class EditSheet(bpy.types.Operator, tool.Ifc.Operator):
document_type: Literal["SHEET", "TITLEBLOCK", "EMBEDDED"]
def invoke(self, context, event):
assert context.window_manager
self.props = tool.Drawing.get_document_props()
sheet = tool.Ifc.get().by_id(self.props.sheets[self.props.active_sheet_index].ifc_definition_id)
if sheet.is_a("IfcDocumentInformation"):
@@ -3452,12 +3471,13 @@ class EditElementFilter(bpy.types.Operator, tool.Ifc.Operator):
element = tool.Ifc.get_entity(obj)
assert element
pset = tool.Pset.get_element_pset(element, "EPset_Drawing")
assert pset
if self.filter_mode == "INCLUDE":
query = tool.Search.export_filter_query(props.include_filter_groups) or None
ifcopenshell.api.run("pset.edit_pset", tool.Ifc.get(), pset=pset, properties={"Include": query})
ifcopenshell.api.pset.edit_pset(tool.Ifc.get(), pset=pset, properties={"Include": query})
elif self.filter_mode == "EXCLUDE":
query = tool.Search.export_filter_query(props.exclude_filter_groups) or None
ifcopenshell.api.run("pset.edit_pset", tool.Ifc.get(), pset=pset, properties={"Exclude": query})
ifcopenshell.api.pset.edit_pset(tool.Ifc.get(), pset=pset, properties={"Exclude": query})
props.filter_mode = "NONE"
bpy.ops.bim.activate_drawing(drawing=element.id(), should_view_from_camera=False)
@@ -3555,8 +3575,7 @@ class AddReferenceImage(bpy.types.Operator, tool.Ifc.Operator, ImportHelper):
"Transparency": 0.0,
"ReflectanceMethod": "NOTDEFINED",
}
ifcopenshell.api.run(
"style.add_surface_style",
ifcopenshell.api.style.add_surface_style(
tool.Ifc.get(),
style=style,
ifc_class="IfcSurfaceStyleRendering",
+53 -40
View File
@@ -46,7 +46,7 @@ from bpy.props import (
CollectionProperty,
BoolVectorProperty,
)
from typing import TYPE_CHECKING, Literal, Any, Callable, get_args
from typing import TYPE_CHECKING, Literal, Any, Callable, get_args, Union
diagram_scales_enum = []
@@ -57,7 +57,7 @@ def purge():
diagram_scales_enum = []
def update_target_view(self: "DocProperties", context: bpy.types.Context) -> None:
def update_target_view_doc(self: "DocProperties", context: bpy.types.Context) -> None:
DrawingsData.data["location_hint"] = DrawingsData.location_hint()
@@ -228,32 +228,12 @@ def get_update_layer_callback(
return update_layer_callback
def update_has_linework(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
update_layer(self, context, "HasLinework", self.has_linework)
def update_target_view(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
if self.target_view != "MODEL_VIEW":
def update_target_view_camera(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
if self.update_props and self.target_view != "MODEL_VIEW":
self.camera_type = "ORTHO"
update_layer(self, context, "TargetView", self.target_view)
def update_dpi(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
update_layer(self, context, "DPI", self.dpi)
def update_linework_mode(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
update_layer(self, context, "LineworkMode", self.linework_mode)
def update_fill_mode(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
update_layer(self, context, "FillMode", self.fill_mode)
def update_cut_mode(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
update_layer(self, context, "CutMode", self.cut_mode)
def update_layer(self: "BIMCameraProperties", context: bpy.types.Context, name: str, value: Any) -> None:
assert context.scene
if not self.update_props:
@@ -366,21 +346,34 @@ class Sheet(PropertyGroup):
is_expanded: bool
RenderType = Literal["DEFAULT", "VIEWPORT"]
RENDER_TYPE_ENUM_ITEMS: dict[RenderType, tuple[str, str]] = {
"DEFAULT": ("Default", "Use default Blender render."),
"VIEWPORT": ("Viewport", "Render active viewport."),
}
class DrawingStyle(PropertyGroup):
name: StringProperty(name="Name", get=get_drawing_style_name, set=set_drawing_style_name)
raster_style: StringProperty(name="Raster Style", default="{}")
raster_style: StringProperty(
name="Raster Style",
description="JSON string for drawing style settings.",
default="{}",
)
render_type: EnumProperty(
items=[
("NONE", "None", ""),
("DEFAULT", "Default", ""),
("VIEWPORT", "Viewport", ""),
],
items=[(k, *v) for k, v in RENDER_TYPE_ENUM_ITEMS.items()],
name="Render Type",
default="VIEWPORT",
)
include_query: StringProperty(name="Include Query")
exclude_query: StringProperty(name="Exclude Query")
attributes: CollectionProperty(name="Attributes", type=StrProperty)
if TYPE_CHECKING:
name: str
raster_style: str
render_type: RenderType
include_query: str
exclude_query: str
class RasterStyleProperty(enum.Enum):
@@ -410,7 +403,7 @@ class DocProperties(PropertyGroup):
items=TARGET_VIEW_ITEMS,
name="Target View",
default="PLAN_VIEW",
update=update_target_view,
update=update_target_view_doc,
)
location_hint: EnumProperty(items=get_location_hint, name="Location Hint")
drawings: CollectionProperty(name="Drawings", type=Drawing)
@@ -465,7 +458,7 @@ class DocProperties(PropertyGroup):
is_editing_schedules: bool
is_editing_references: bool
target_view: Literal["PLAN_VIEW", "ELEVATION_VIEW", "SECTION_VIEW", "REFLECTED_PLAN_VIEW", "MODEL_VIEW"]
location_hint: str
location_hint: tool.Drawing.LocationHintType
drawings: bpy.types.bpy_prop_collection_idprop[Drawing]
active_drawing_id: int
active_drawing_index: int
@@ -498,6 +491,12 @@ class DocProperties(PropertyGroup):
tolerance: float
classes_to_wireframe: str
def get_active_drawing(self) -> Union[ifcopenshell.entity_instance, None]:
drawing_id = self.active_drawing_id
if drawing_id == 0:
return None
return tool.Ifc.get().by_id(drawing_id)
def update_width_height(self: "BIMCameraProperties", context: bpy.types.Context) -> None:
self.update_camera_resolution()
@@ -510,7 +509,7 @@ def update_camera_type(self: "BIMCameraProperties", context: bpy.types.Context)
CameraType = Literal["PERSP", "ORTHO"]
CAMERA_TYPE_ENUM_ITEMS: dict[CameraType, tuple[str, str]] = {
"ORTHO": ("Ortographic", "Most common camera for the drawings, supporting all of the features."),
"ORTHO": ("Orthographic", "Most common camera for the drawings, supporting all of the features."),
"PERSP": ("Perspective", "The only avilable features for perspective camera: freestyle linework, underlay."),
}
@@ -523,7 +522,7 @@ class BIMCameraProperties(PropertyGroup):
],
default="OPENCASCADE",
name="Linework Mode",
update=update_linework_mode,
update=get_update_layer_callback("LineworkMode", "linework_mode"),
)
fill_mode: EnumProperty(
items=[
@@ -533,7 +532,7 @@ class BIMCameraProperties(PropertyGroup):
],
default="NONE",
name="Fill Mode",
update=update_fill_mode,
update=get_update_layer_callback("FillMode", "fill_mode"),
)
cut_mode: EnumProperty(
items=[
@@ -542,14 +541,14 @@ class BIMCameraProperties(PropertyGroup):
],
default="BISECT",
name="Cut Mode",
update=update_cut_mode,
update=get_update_layer_callback("CutMode", "cut_mode"),
)
# EPset_Drawing.
has_underlay: BoolProperty(
name="Underlay",
default=False,
update=get_update_layer_callback("has_underlay", "HasUnderlay"),
update=update_has_underlay,
)
has_linework: BoolProperty(
name="Linework",
@@ -565,7 +564,7 @@ class BIMCameraProperties(PropertyGroup):
name="Target View",
default="PLAN_VIEW",
items=TARGET_VIEW_ITEMS,
update=update_target_view,
update=update_target_view_camera,
)
representation: StringProperty(name="Representation")
@@ -575,7 +574,7 @@ class BIMCameraProperties(PropertyGroup):
custom_scale_denominator: bpy.props.StringProperty(default="100", update=update_diagram_scale)
raster_x: IntProperty(name="Raster X", default=1000)
raster_y: IntProperty(name="Raster Y", default=1000)
dpi: IntProperty(name="DPI", default=75, update=update_dpi)
dpi: IntProperty(name="DPI", default=75, update=get_update_layer_callback("DPI", "dpi"))
width: FloatProperty(name="Width", default=50, subtype="DISTANCE", update=update_width_height)
height: FloatProperty(name="Height", default=50, subtype="DISTANCE", update=update_width_height)
# Bonsai property is needed to prevent user from using unsupported panoramic camera.
@@ -624,6 +623,10 @@ class BIMCameraProperties(PropertyGroup):
exclude_filter_groups: bpy.types.bpy_prop_collection_idprop[BIMFilterGroup]
update_props: bool
def get_active_drawing_style(self) -> Union[DrawingStyle, None]:
dprops = tool.Drawing.get_document_props()
return tool.Blender.get_active_uilist_element(dprops.drawing_styles, self.active_drawing_style_index)
# For now, this JSON dump are all the parameters that determine a camera's "Block representation"
# By checking this, you will know whether or not the camera IFC representation needs to be refreshed
def update_representation(self, matrix_world: Matrix) -> bool:
@@ -749,6 +752,12 @@ class LiteralProps(PropertyGroup):
}
return text_data
if TYPE_CHECKING:
attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
value: str
box_alignment: str
ifc_definition_id: int
class BIMTextProperties(PropertyGroup):
is_editing: BoolProperty(name="Is Editing", default=False)
@@ -799,6 +808,10 @@ class BIMAssignedProductProperties(PropertyGroup):
is_editing_product: BoolProperty(name="Is Editing Product", default=False)
relating_product: PointerProperty(name="Relating Product", type=bpy.types.Object, poll=relating_product_poll)
if TYPE_CHECKING:
is_editing_product: bool
relating_product: Union[bpy.types.Object, None]
annotation_classes = [
(x, *tool.Drawing.ANNOTATION_TYPES_DATA[x][:3], i) for i, x in enumerate(tool.Drawing.ANNOTATION_TYPES_DATA)
@@ -22,6 +22,7 @@ import bpy
import math
import bmesh
import shutil
from bpy.types import SplineBezierPoints, SplinePoints
import mathutils
import xml.etree.ElementTree as ET
import svgwrite
@@ -37,7 +38,7 @@ from bonsai.bim.module.drawing.data import DrawingsData
from bonsai.bim.module.drawing.data import DecoratorData
from math import pi, ceil, atan, degrees, acos
from mathutils import geometry, Vector
from typing import Optional, Self
from typing import Optional, Self, Union, Sequence, Callable
from pathlib import Path
@@ -59,6 +60,8 @@ class External(svgwrite.container.Group):
class SvgWriter:
metadata: list[str]
def __init__(self):
self.data_dir = None
self.human_scale = "NTS"
@@ -176,12 +179,20 @@ class SvgWriter:
for child in root:
self.svg.defs.add(External(child))
def draw_annotations(self, annotations, precision, decimal_places):
def draw_annotations(
self,
annotations: list[ifcopenshell.entity_instance],
precision: Union[float, None],
decimal_places: Union[int, None],
) -> Self:
self.precision = precision
self.decimal_places = decimal_places
for element in annotations:
obj = tool.Ifc.get_object(element)
if not obj or (object_type := ifcopenshell.util.element.get_predefined_type(element)) == "DRAWING":
if (
not isinstance(obj, bpy.types.Object)
or (object_type := ifcopenshell.util.element.get_predefined_type(element)) == "DRAWING"
):
continue
elif object_type == "GRID":
self.draw_grid_annotation(obj)
@@ -256,11 +267,12 @@ class SvgWriter:
get_text, tag, dimension_data, text_position=text_position, angle=angle, class_str="SECTIONLEVEL"
)
def draw_stair_annotation(self, obj):
def draw_stair_annotation(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
matrix_world = obj.matrix_world
classes = self.get_attribute_classes(obj)
assert isinstance(obj.data, bpy.types.Curve)
for spline in obj.data.splines:
points = self.get_spline_points(spline)
projected_points = [self.project_point_onto_camera(matrix_world @ p.co.xyz) for p in points]
@@ -284,7 +296,7 @@ class SvgWriter:
)
)
def draw_grid_annotation(self, obj):
def draw_grid_annotation(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
matrix_world = obj.matrix_world
@@ -358,6 +370,7 @@ class SvgWriter:
def get_attribute_classes(self, obj: bpy.types.Object) -> list[str]:
element = tool.Ifc.get_entity(obj)
assert element
global_id = "GlobalId-{}".format(element.GlobalId)
predefined_type = "PredefinedType-" + tool.Drawing.canonicalise_class_name(
str(ifcopenshell.util.element.get_predefined_type(element))
@@ -374,7 +387,7 @@ class SvgWriter:
)
return classes
def draw_line_annotation(self, obj):
def draw_line_annotation(self, obj: bpy.types.Object) -> None:
# TODO: properly scope these offsets
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
@@ -397,7 +410,7 @@ class SvgWriter:
elif isinstance(obj.data, bpy.types.Mesh):
self.draw_edge_annotation(obj, classes)
def draw_edge_annotation(self, obj, classes):
def draw_edge_annotation(self, obj: bpy.types.Object, classes: list[str]) -> None:
predefined_type = classes[2].split("-", 1)[1]
x_offset = self.raw_width / 2
@@ -415,7 +428,7 @@ class SvgWriter:
self.svg.line(start=start * self.svg_scale, end=end * self.svg_scale, class_=" ".join(classes))
)
def draw_batting_annotation():
def draw_batting_annotation() -> None:
v0_global = matrix_world @ obj.data.vertices[0].co.xyz
v1_global = matrix_world @ obj.data.vertices[1].co.xyz
v0 = self.project_point_onto_camera(v0_global)
@@ -481,41 +494,42 @@ class SvgWriter:
)
self.svg.add(self.svg.polyline(points=points, class_=" ".join(classes), style=polyline_style))
def draw_revision_cloud_annotation():
def draw_revision_cloud_annotation() -> None:
segment_width = 15.0
base_height = 1
width = 5
def get_svg_half_circle(height, width):
def get_svg_half_circle(height: float, width: float) -> str:
cp0 = f"0,-{height}"
cp1 = f"{width},-{height}"
end_point = f"{width},0"
circle = f"c{cp0} {cp1} {end_point}"
return circle
def get_revision_pattern(base_offset):
def get_revision_pattern(base_offset: Vector) -> str:
pattern = f"m{base_offset.x},{base_offset.y}"
pattern += " " + get_svg_half_circle(2 * base_height, width)
pattern += " " + get_svg_half_circle(2.5 * base_height, width)
pattern += " " + get_svg_half_circle(1.5 * base_height, width)
return pattern
def get_scale(size, direction):
def get_scale(size: float, direction: Vector) -> str:
original_edge = direction * size
current_svg_segments = ceil(size / segment_width) * segment_width * direction
scale = [1 if original_edge[i] == 0 else original_edge[i] / current_svg_segments[i] for i in range(2)]
return "scale(%f, %f)" % (scale[0], scale[1])
def poly_to_edges(poly):
edges = []
def poly_to_edges(poly: Sequence[int]) -> list[tuple[int, int]]:
edges: list[tuple[int, int]] = []
n_verts = len(poly)
lats_index = n_verts - 1
last_index = n_verts - 1
for i in range(len(poly)):
edge = [poly[i], (poly[i + 1]) if i != lats_index else poly[0]]
edge = (poly[i], (poly[i + 1]) if i != last_index else poly[0])
edges.append(edge)
return edges
element = tool.Ifc.get_entity(obj)
assert element
safe_offset_x = 2.0
marker_width = segment_width + safe_offset_x * 2
market_height = 15.0
@@ -573,7 +587,7 @@ class SvgWriter:
)
self.svg.add(polyline)
def draw_section_annotation():
def draw_section_annotation() -> None:
display_data = DecoratorData.get_section_markers_display_data(obj)
connect_markers = display_data["connect_markers"]
@@ -624,7 +638,7 @@ class SvgWriter:
for edge in obj.data.edges:
draw_simple_edge_annotation(*edge.vertices[:])
def draw_leader_annotation(self, obj):
def draw_leader_annotation(self, obj: bpy.types.Object) -> None:
self.draw_line_annotation(obj)
spline = obj.data.splines[0]
spline_points = spline.bezier_points if spline.bezier_points else spline.points
@@ -634,7 +648,7 @@ class SvgWriter:
position = Vector((0, 0, 0))
self.draw_text_annotation(obj, position)
def draw_section_annotation(self, obj):
def draw_section_annotation(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
@@ -688,7 +702,7 @@ class SvgWriter:
)
)
def draw_elevation_annotation(self, obj):
def draw_elevation_annotation(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
symbol_position = self.project_point_onto_camera(obj.location)
@@ -927,7 +941,7 @@ class SvgWriter:
symbol_transform = self.get_symbol_transform(svg_position_str)
self.draw_symbol(svg_id, symbol_transform)
def draw_break_annotations(self, obj):
def draw_break_annotations(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
@@ -950,18 +964,20 @@ class SvgWriter:
d = "M{}".format(d[1:])
path = self.svg.add(self.svg.path(d=d, class_=" ".join(classes)))
def draw_plan_level_annotation(self, obj):
def draw_plan_level_annotation(self, obj: bpy.types.Object) -> None:
offset = Vector([self.raw_width, self.raw_height]) / 2
matrix_world = obj.matrix_world
classes = self.get_attribute_classes(obj)
element = tool.Ifc.get_entity(obj)
assert element
description = element.Description
dimension_data = DecoratorData.get_dimension_data(obj)
suppress_zero_inches = dimension_data["suppress_zero_inches"]
base_offset_y = 1.0
assert isinstance(obj.data, bpy.types.Curve)
for spline in obj.data.splines:
points = self.get_spline_points(spline)
projected_points = [self.project_point_onto_camera(matrix_world @ p.co.xyz) for p in points]
@@ -1000,7 +1016,8 @@ class SvgWriter:
box_alignment=box_alignment,
)
def draw_angle_annotations(self, obj):
def draw_angle_annotations(self, obj: bpy.types.Object) -> None:
assert isinstance(obj.data, bpy.types.Curve)
points = obj.data.splines[0].points
# [1, 2, 3, 4, 5] -> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
points_chunked = [points[i : i + 3] for i in range(len(points) - 2)]
@@ -1009,18 +1026,18 @@ class SvgWriter:
points_chunk = [obj.matrix_world @ p.co.xyz for p in points_chunk]
self.draw_svg_3point_arc(obj, points_chunk)
def draw_svg_3point_arc(self, obj, angle_points):
def draw_svg_3point_arc(self, obj: bpy.types.Object, angle_points: list[Vector]) -> None:
"""`angle_points` are expected to be already in world space"""
# This implementation uses an SVG arc, which means that it can only draw
# arcs that are orthogonal to the view (e.g. not arcs in 3D).
# Gosh this is bad code :(
def position_on_svg(p):
def position_on_svg(p: Vector) -> Vector:
p = self.project_point_onto_camera(p)
offset = Vector([self.raw_width / 2, self.raw_height / 2])
return (offset + p.xy * Vector((1, -1))) * self.svg_scale
def get_angle_value():
def get_angle_value() -> float:
"""points should be in world space"""
# calculate arc angle, need to make sure we do it in world space
v0, v1, v2 = angle_points
@@ -1104,10 +1121,11 @@ class SvgWriter:
classes = self.get_attribute_classes(obj)
path = self.svg.add(self.svg.path(d=d, class_=" ".join(classes)))
def draw_radius_annotations(self, obj):
def draw_radius_annotations(self, obj: bpy.types.Object) -> None:
offset = Vector([self.raw_width, self.raw_height]) / 2
classes = self.get_attribute_classes(obj)
element = tool.Ifc.get_entity(obj)
assert element
tag = element.Description
matrix_world = obj.matrix_world
@@ -1141,7 +1159,7 @@ class SvgWriter:
get_text, tag, dimension_data, text_position=text_position, class_str="RADIUS", box_alignment="center"
)
def draw_dimension_text(self, get_text, tag, dimension_data, **create_text_kwargs):
def draw_dimension_text(self, get_text: Callable[[], str], tag, dimension_data, **create_text_kwargs) -> None:
prefix = dimension_data["text_prefix"]
suffix = dimension_data["text_suffix"]
show_description_only = dimension_data["show_description_only"]
@@ -1166,12 +1184,13 @@ class SvgWriter:
for text in text_tags:
self.svg.add(text)
def draw_fall_annotations(self, obj):
def draw_fall_annotations(self, obj: bpy.types.Object) -> None:
x_offset = self.raw_width / 2
y_offset = self.raw_height / 2
classes = self.get_attribute_classes(obj)
element = tool.Ifc.get_entity(obj)
matrix_world = obj.matrix_world
assert isinstance(obj.data, bpy.types.Curve)
for spline in obj.data.splines:
points = self.get_spline_points(spline)
projected_points = [self.project_point_onto_camera(matrix_world @ p.co.xyz) for p in points]
@@ -1236,13 +1255,14 @@ class SvgWriter:
text_style = SvgWriter.get_box_alignment_parameters("center")
self.svg.add(self.svg.text(tag, insert=tuple(text_position), class_="RADIUS", **text_style))
def draw_diameter_annotations(self, obj):
def draw_diameter_annotations(self, obj: bpy.types.Object) -> None:
classes = self.get_attribute_classes(obj)
matrix_world = obj.matrix_world
element = tool.Ifc.get_entity(obj)
dimension_text = element.Description
dimension_data = DecoratorData.get_dimension_data(obj)
assert isinstance(obj.data, bpy.types.Curve)
for spline in obj.data.splines:
points = self.get_spline_points(spline)
for i, p in enumerate(points):
@@ -1264,13 +1284,14 @@ class SvgWriter:
custom_unit=dimension_data["custom_unit"],
)
def draw_dimension_annotations(self, obj):
def draw_dimension_annotations(self, obj: bpy.types.Object) -> None:
classes = self.get_attribute_classes(obj)
matrix_world = obj.matrix_world
element = tool.Ifc.get_entity(obj)
dimension_text = element.Description
dimension_data = DecoratorData.get_dimension_data(obj)
assert isinstance(obj.data, bpy.types.Curve)
for spline in obj.data.splines:
points = self.get_spline_points(spline)
for i in range(len(points) - 1):
@@ -1289,7 +1310,7 @@ class SvgWriter:
custom_unit=dimension_data["custom_unit"],
)
def draw_measureit_arch_dimension_annotations(self):
def draw_measureit_arch_dimension_annotations(self) -> None:
try:
import MeasureIt_ARCH.measureit_arch_external_utils
@@ -1303,9 +1324,9 @@ class SvgWriter:
def draw_dimension_annotation(
self,
v0_global,
v1_global,
classes,
v0_global: Vector,
v1_global: Vector,
classes: list[str],
dimension_text=None,
text_format=lambda x: x,
show_description_only=False,
@@ -1314,7 +1335,7 @@ class SvgWriter:
text_suffix="",
fill_bg=False,
custom_unit=None,
):
) -> None:
offset = Vector([self.raw_width, self.raw_height]) / 2
v0 = self.project_point_onto_camera(v0_global)
v1 = self.project_point_onto_camera(v1_global)
@@ -1446,7 +1467,7 @@ class SvgWriter:
Vector(self.camera_projection),
)
def get_spline_points(self, spline):
def get_spline_points(self, spline: bpy.types.Spline) -> Union[SplineBezierPoints, SplinePoints]:
return spline.bezier_points if spline.bezier_points else spline.points
def draw_polygon(self, polygon, position):
+28 -20
View File
@@ -173,12 +173,13 @@ class BIM_PT_drawing_underlay(Panel):
return bool((camera := context.scene.camera) and tool.Ifc.get_entity(camera))
def draw(self, context):
assert self.layout
layout = self.layout
layout.use_property_split = True
assert context.scene and (camera := context.scene.camera)
dprops = tool.Drawing.get_document_props()
props = tool.Drawing.get_camera_props(camera)
drawing_index_is_valid = props.active_drawing_style_index < len(dprops.drawing_styles)
drawing_style = props.get_active_drawing_style()
if not DrawingsData.is_loaded:
DrawingsData.load()
@@ -192,7 +193,7 @@ class BIM_PT_drawing_underlay(Panel):
row.label(text="Current Shading Style:")
row.label(text=current_shading_style)
row.operator("bim.add_drawing_style", icon="ADD", text="")
if drawing_index_is_valid:
if drawing_style:
row.operator("bim.remove_drawing_style", icon="X", text="").index = props.active_drawing_style_index
row.operator("bim.reload_drawing_styles", icon="FILE_REFRESH", text="")
@@ -207,9 +208,8 @@ class BIM_PT_drawing_underlay(Panel):
"active_drawing_style_index",
)
if not drawing_index_is_valid:
if drawing_style is None:
return
drawing_style = dprops.drawing_styles[props.active_drawing_style_index]
row = layout.row(align=True)
row.prop(drawing_style, "name")
@@ -221,14 +221,6 @@ class BIM_PT_drawing_underlay(Panel):
row = layout.row(align=True)
row.prop(drawing_style, "exclude_query")
row = layout.row()
row.operator("bim.add_drawing_style_attribute")
for index, attribute in enumerate(drawing_style.attributes):
row = layout.row(align=True)
row.prop(attribute, "name", text="")
row.operator("bim.remove_drawing_style_attribute", icon="X", text="").index = index
row = layout.row(align=True)
row.operator("bim.save_drawing_style")
row.operator("bim.activate_drawing_style")
@@ -281,9 +273,6 @@ class BIM_PT_drawings(Panel):
row3 = row.row(align=True)
row3.alignment = "RIGHT"
row3.operator("bim.activate_drawing", icon="OUTLINER_OB_CAMERA", text="").drawing = (
active_drawing.ifc_definition_id
)
row3.operator("bim.activate_model", icon="VIEW3D", text="")
row3.separator(factor=0.5, type="SPACE")
@@ -505,17 +494,19 @@ class BIM_PT_product_assignments(Panel):
@classmethod
def poll(cls, context):
if not tool.Ifc.get() or not context.active_object:
return
return False
element = tool.Ifc.get_entity(context.active_object)
if not element:
return
return False
return element.is_a("IfcAnnotation")
def draw(self, context):
if not ProductAssignmentsData.is_loaded:
ProductAssignmentsData.load()
props = context.active_object.BIMAssignedProductProperties
assert self.layout
assert (obj := context.active_object)
props = tool.Drawing.get_object_assigned_product_props(obj)
if props.is_editing_product:
row = self.layout.row(align=True)
@@ -622,7 +613,16 @@ class BIM_PT_text(Panel):
class BIM_UL_drawinglist(bpy.types.UIList):
def draw_item(self, context, layout, data: DocProperties, item: Drawing, icon, active_data, active_propname):
def draw_item(
self,
context,
layout: bpy.types.UILayout,
data: DocProperties,
item: Drawing,
icon,
active_data,
active_propname,
):
if not item:
layout.label(text="", translate=False)
return
@@ -632,14 +632,22 @@ class BIM_UL_drawinglist(bpy.types.UIList):
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)
row.separator(factor=0.5, type="SPACE")
row.prop(item, "name", text="", emboss=False)
row.separator(factor=0.25, type="SPACE")
self.props = tool.Drawing.get_document_props()
if (
self.props.drawings
and self.props.active_drawing_id
and item.ifc_definition_id == self.props.active_drawing_id
):
row.label(text="", icon="OUTLINER_OB_CAMERA")
row.operator("bim.activate_drawing", text="", icon="VIEW_CAMERA", emboss=True, depress=True).drawing = (
item.ifc_definition_id
)
else:
row.operator("bim.activate_drawing", text="", icon="VIEW_CAMERA_UNSELECTED", emboss=False).drawing = (
item.ifc_definition_id
)
else:
if item.target_view == "PLAN_VIEW":
icon = "UV_FACESEL"
+35 -22
View File
@@ -23,6 +23,7 @@ import ifcopenshell.util.placement
import ifcopenshell.util.schema
import ifcopenshell.util.unit
import bonsai.tool as tool
from typing import Any, Union
from mathutils import Vector
@@ -45,13 +46,12 @@ class ViewportData:
cls.data = {"mode": cls.mode()}
@classmethod
def mode(cls):
def mode(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
obj_mode = ("OBJECT", "IFC Object Mode", "View and move the placements of objects", "OBJECT_DATAMODE", 0)
item_mode = ("ITEM", "IFC Item Mode", "View individual representation items", "MESH_DATA", 1)
edit_mode = ("EDIT", "IFC Edit Mode", "Edit representation items", "EDITMODE_HLT", 2)
obj = bpy.context.active_object
element = tool.Ifc.get_entity(obj)
modes: list[tuple[str, str, str, str, int]] = [obj_mode]
gprops = tool.Geometry.get_geometry_props()
@@ -61,13 +61,14 @@ class ViewportData:
if not obj:
return modes
element = tool.Ifc.get_entity(obj)
pprops = tool.Project.get_project_props()
if obj in pprops.clipping_planes_objs:
pass
elif element:
if tool.Geometry.is_locked(element):
pass
elif obj.data and tool.Geometry.is_profile_based(obj.data):
elif obj.data and tool.Geometry.has_mesh_properties(obj.data) and tool.Geometry.is_profile_based(obj.data):
modes.append(edit_mode)
elif element.is_a("IfcRelSpaceBoundary"):
modes.append(edit_mode)
@@ -88,7 +89,7 @@ class ViewportData:
class RepresentationsData:
data = {}
data: dict[str, Any] = {}
is_loaded = False
@classmethod
@@ -102,10 +103,12 @@ class RepresentationsData:
cls.is_loaded = True
@classmethod
def representations(cls):
results = []
def representations(cls) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
obj = tool.Geometry.get_active_or_representation_obj()
assert obj
element = tool.Ifc.get_entity(obj)
assert element
active_representation_id = None
active_representation = tool.Geometry.get_active_representation(obj)
@@ -132,8 +135,8 @@ class RepresentationsData:
return results
@classmethod
def contexts(cls):
results = []
def contexts(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
results: list[tuple[str, str, str]] = []
for element in tool.Ifc.get().by_type("IfcGeometricRepresentationContext", include_subtypes=False):
results.append((str(element.id()), element.ContextType or "Unnamed", ""))
for element in tool.Ifc.get().by_type("IfcGeometricRepresentationSubContext", include_subtypes=False):
@@ -219,9 +222,12 @@ class ConnectionsData:
cls.is_loaded = True
@classmethod
def connections(cls):
results = []
element = tool.Ifc.get_entity(bpy.context.active_object)
def connections(cls) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
obj = bpy.context.active_object
assert obj
element = tool.Ifc.get_entity(obj)
assert element
connected_to = getattr(element, "ConnectedTo", [])
connected_from = getattr(element, "ConnectedFrom", [])
@@ -285,13 +291,16 @@ class ConnectionsData:
return results
@classmethod
def is_connection_realization(cls):
element = tool.Ifc.get_entity(bpy.context.active_object)
def is_connection_realization(cls) -> Union[list[dict[str, Any]], None]:
obj = bpy.context.active_object
assert obj
element = tool.Ifc.get_entity(obj)
assert element
connections = getattr(element, "IsConnectionRealization", None)
if not connections:
return
results = []
results: list[dict[str, Any]] = []
for rel in connections:
data = {
"realizing_elements_connection_type": rel.ConnectionType,
@@ -322,16 +331,19 @@ class DerivedCoordinatesData:
cls.is_loaded = True
@classmethod
def load_z_values(cls):
def load_z_values(cls) -> None:
cls.z_values = [
(bpy.context.active_object.matrix_world @ Vector(co))[2] for co in bpy.context.active_object.bound_box
]
@classmethod
def load_collection(cls):
def load_collection(cls) -> None:
cls.collection = None
cls.collection_z = 0
element = tool.Ifc.get_entity(bpy.context.active_object)
obj = bpy.context.active_object
if not obj:
return
element = tool.Ifc.get_entity(obj)
if not element:
return
parent = ifcopenshell.util.element.get_aggregate(element)
@@ -392,7 +404,7 @@ class PlacementData:
@classmethod
def load(cls):
cls.data = {"has_placement": cls.has_placement()}
cls.data: dict[str, Any] = {"has_placement": cls.has_placement()}
props = tool.Georeference.get_georeference_props()
obj = bpy.context.active_object
@@ -415,13 +427,14 @@ class PlacementData:
return False
@classmethod
def original_xyz(cls, obj):
def original_xyz(cls, obj: bpy.types.Object) -> list[float]:
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
props = tool.Georeference.get_georeference_props()
translation = obj.matrix_world.translation
xyz = ifcopenshell.util.geolocation.xyz2enh(
obj.matrix_world[0][3],
obj.matrix_world[1][3],
obj.matrix_world[2][3],
translation[0],
translation[1],
translation[2],
float(props.blender_offset_x) * unit_scale,
float(props.blender_offset_y) * unit_scale,
float(props.blender_offset_z) * unit_scale,
@@ -35,13 +35,13 @@ from bpy.props import (
from typing import Optional, TYPE_CHECKING, Union, Literal
def get_contexts(self, context):
def get_contexts(self: "BIMObjectGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
if not RepresentationsData.is_loaded:
RepresentationsData.load()
return RepresentationsData.data["contexts"]
def update_mode(self, context):
def update_mode(self: "BIMGeometryProperties", context: bpy.types.Context) -> None:
if self.is_changing_mode:
return
if context.mode.startswith("EDIT"):
@@ -62,7 +62,7 @@ def update_mode(self, context):
bpy.ops.bim.override_mode_set_edit("INVOKE_DEFAULT")
def update_representation_obj(self, context):
def update_representation_obj(self: "BIMGeometryProperties", context: bpy.types.Context) -> None:
for item_obj in self.item_objs:
if item_obj.obj:
data = item_obj.obj.data
@@ -76,13 +76,13 @@ def update_representation_obj(self, context):
self.is_changing_mode = False
def get_mode(self, context):
def get_mode(self: "BIMGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str, str, int]]:
if not ViewportData.is_loaded:
ViewportData.load()
return ViewportData.data["mode"]
def get_styles(self, context):
def get_styles(self: "BIMObjectGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
# postponed import to avoid circular import
from bonsai.bim.module.material.data import MaterialsData
@@ -91,13 +91,13 @@ def get_styles(self, context):
return MaterialsData.data["styles"]
def get_shape_aspects(self, context):
def get_shape_aspects(self: "BIMObjectGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
if not RepresentationsData.is_loaded:
RepresentationsData.load()
return RepresentationsData.data["shape_aspects"]
def get_material_constituents(self, context, edit_text):
def get_material_constituents(self: "ShapeAspect", context: bpy.types.Context, edit_text: str) -> list[str]:
from bonsai.bim.module.material.data import ObjectMaterialData
if not ObjectMaterialData.is_loaded:
@@ -105,7 +105,7 @@ def get_material_constituents(self, context, edit_text):
return ObjectMaterialData.data["active_material_constituents"]
def get_layers(self, context):
def get_layers(self: "BIMObjectGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
from bonsai.bim.module.layer.data import LayersData
if not LayersData.is_loaded:
@@ -113,7 +113,7 @@ def get_layers(self, context):
return LayersData.data["layers_enum"]
def get_layers_no_active(self, context):
def get_layers_no_active(self: "BIMObjectGeometryProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
from bonsai.bim.module.layer.data import LayersData
if not LayersData.is_loaded:
@@ -112,7 +112,9 @@ def update_blender_coordinates(self: "BIMGeoreferenceProperties", context: bpy.t
props.is_updating_coordinates = True
blender_coordinates = tool.Georeference.get_coordinates("blender")
local_coordinates = ifcopenshell.util.geolocation.xyz2enh(
*blender_coordinates,
blender_coordinates[0],
blender_coordinates[1],
blender_coordinates[2],
float(props.blender_offset_x),
float(props.blender_offset_y),
float(props.blender_offset_z),
@@ -394,7 +394,7 @@ class ObjectMaterialData:
return [(m, m, ifcopenshell.util.doc.get_entity_doc(version, m).get("description", "")) for m in material_types]
@classmethod
def active_material_constituents(cls):
def active_material_constituents(cls) -> list[str]:
material = cls.material
if not cls.material or not material.is_a("IfcMaterialConstituentSet"):
return []
@@ -625,6 +625,26 @@ class EditAssignedMaterial(bpy.types.Operator, tool.Ifc.Operator):
wall.DumbWallPlaner().regenerate_from_layer_set(layer_set)
slab.DumbSlabPlaner().regenerate_from_layer_set(layer_set)
if material_set_usage.is_a("IfcMaterialProfileSetUsage"):
attributes["CardinalPoint"] = int(attributes["CardinalPoint"])
ifcopenshell.api.material.edit_profile_usage(
self.file,
usage=material_set_usage,
attributes=attributes,
)
profile_sets_to_regenerate = set()
for obj in objects:
obj_element = tool.Ifc.get_entity(obj)
obj_material_usage = ifcopenshell.util.element.get_material(obj_element)
if obj_material_usage and obj_material_usage.is_a("IfcMaterialProfileSetUsage"):
profile_sets_to_regenerate.add(obj_material_usage.ForProfileSet)
for profile_set in profile_sets_to_regenerate:
for material_profile in profile_set.MaterialProfiles:
model_profile.DumbProfileRegenerator().regenerate_from_profile_def(material_profile.Profile)
bpy.ops.bim.disable_editing_assigned_material(obj=active_obj.name)
+9 -2
View File
@@ -38,10 +38,17 @@ class AddArray(bpy.types.Operator, tool.Ifc.Operator):
assert (element := tool.Ifc.get_entity(obj))
ifc_file = tool.Ifc.get()
if not element.is_a("IfcElement") and not element.is_a("IfcAnnotation"):
allowed_types = (
"IfcElement",
"IfcAnnotation",
"IfcOpeningElement",
"IfcSpatialElement",
)
if not any(element.is_a(c) for c in allowed_types):
self.report(
{"ERROR"},
f"Adding array to element of type '{element.is_a()}' is not supported. Supported types: IfcElement, IfcAnnotation.",
f"Adding array to element of type '{element.is_a()}' is not supported. Supported types: {','.join(allowed_types)}.",
)
return {"CANCELLED"}
@@ -616,6 +616,9 @@ class FinishEditingDoor(bpy.types.Operator, tool.Ifc.Operator):
props.is_editing = False
update_door_modifier_representation(obj)
element_type = ifcopenshell.util.element.get_type(element)
if element_type:
tool.Model.mark_thumbnail_for_update(element_type)
pset = tool.Pset.get_element_pset(element, "BBIM_Door")
door_data = tool.Ifc.get().createIfcText(json.dumps(door_data, default=list))
@@ -36,12 +36,6 @@ def load_post(*args):
"sequence.edit_task_time", "Bonsai.Task.CalculateQuantities", task.calculate_quantities
)
ifcopenshell.api.add_post_listener(
"material.edit_profile_usage",
"Bonsai.Product.RegenerateProfileUsage",
product.regenerate_profile_usage,
)
ifcopenshell.api.add_post_listener(
"type.assign_type", "Bonsai.DumbWall.RegenerateFromType", wall.DumbWallPlaner().regenerate_from_type
)
+12 -20
View File
@@ -484,32 +484,21 @@ class AddBoolean(Operator, tool.Ifc.Operator):
class ShowOpenings(Operator, tool.Ifc.Operator):
bl_idname = "bim.show_openings"
bl_label = "Show"
bl_description = "Show Openings"
bl_label = "Show Openings"
bl_description = "Show openings for selected objects"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
objs = list(context.selected_objects)
# If several parts of an aggregation are selected, the aggregate openings may be queried more than once
objects_element_map = set()
while objs:
obj = objs.pop(0)
for obj in tool.Blender.get_selected_objects():
element = tool.Ifc.get_entity(obj)
if element:
if getattr(element, "Decomposes", None):
# Select aggregate recursively
if element.Decomposes and (aggregate := element.Decomposes[0].RelatingObject):
aggregate_obj = tool.Ifc.get_object(aggregate)
objs.append(aggregate_obj)
objects_element_map.add((obj, element))
for obj, element in objects_element_map:
if element is None:
continue
self.show_object_openings(obj, element)
DecorationsHandler.install(bpy.context)
bpy.ops.bim.update_openings_focus()
return {"FINISHED"}
def show_object_openings(self, obj, element):
def show_object_openings(self, obj: bpy.types.Object, element: ifcopenshell.entity_instance) -> None:
openings_elements = [rel.RelatedOpeningElement for rel in tool.Geometry.get_openings(element)]
if not openings_elements:
return
@@ -531,15 +520,18 @@ class UpdateOpeningsFocus(Operator):
preferences = tool.Blender.get_addon_preferences()
if preferences.opening_focus_opacity == 100:
return {"FINISHED"}
openings = set()
building_objects = set()
openings: set[bpy.types.Object] = set()
building_objects: set[bpy.types.Object] = set()
props = tool.Model.get_model_props()
for opening in props.openings:
if opening.obj:
openings.add(opening.obj)
opening_element = tool.Ifc.get_entity(opening.obj)
assert opening_element
building_element = opening_element.VoidsElements[0].RelatingBuildingElement
building_objects.add(tool.Ifc.get_object(building_element))
building_obj = tool.Ifc.get_object(building_element)
assert isinstance(building_obj, bpy.types.Object)
building_objects.add(building_obj)
for obj in context.scene.objects:
obj.color = [
@@ -608,8 +608,7 @@ class LoadTypeThumbnails(bpy.types.Operator):
while queue:
# if bpy.app.is_job_running("RENDER_PREVIEW") does not seem to reflect asset preview generation
element = queue.pop()
if tool.Model.update_thumbnail_for_element(element):
queue.append(element)
tool.Model.mark_thumbnail_for_update(element)
return {"FINISHED"}
@@ -212,7 +212,7 @@ class DumbProfileRegenerator:
# update related thumbnails
for element in self.get_element_types_using_profile(profile):
tool.Model.update_thumbnail_for_element(element, refresh=True)
tool.Model.mark_thumbnail_for_update(element)
def regenerate_from_profile(self, usecase_path, ifc_file, settings):
self.file = ifc_file
@@ -529,6 +529,9 @@ class FinishEditingWindow(bpy.types.Operator, tool.Ifc.Operator):
props.is_editing = False
update_window_modifier_representation(context)
element_type = ifcopenshell.util.element.get_type(element)
if element_type:
tool.Model.mark_thumbnail_for_update(element_type)
pset = tool.Pset.get_element_pset(element, "BBIM_Window")
window_data = tool.Ifc.get().createIfcText(json.dumps(window_data, default=list))
+101 -68
View File
@@ -17,7 +17,9 @@
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import bpy
import ifcopenshell
import bonsai.tool as tool
from typing import Any, Union
from ifcopenshell.util.doc import get_entity_doc
@@ -31,42 +33,46 @@ def refresh():
class RolesAddressesData:
@classmethod
def get_roles(cls, parent):
results = []
def get_roles(cls, parent: ifcopenshell.entity_instance) -> list[dict[str, Any]]:
props = tool.Owner.get_owner_props()
results: list[dict[str, Any]] = []
for role in parent.Roles or []:
results.append(
{
"id": role.id(),
"is_editing": bpy.context.scene.BIMOwnerProperties.active_role_id == role.id(),
"is_editing": props.active_role_id == role.id(),
"label": role.UserDefinedRole or role.Role,
"props": bpy.context.scene.BIMOwnerProperties.role_attributes,
"props": props.role_attributes,
}
)
return results
@classmethod
def get_addresses(cls, parent):
results = []
def get_addresses(cls, parent: ifcopenshell.entity_instance) -> list[dict[str, Any]]:
props = tool.Owner.get_owner_props()
results: list[dict[str, Any]] = []
for address in parent.Addresses or []:
results.append(
{
"id": address.id(),
"is_editing": bpy.context.scene.BIMOwnerProperties.active_address_id == address.id(),
"is_editing": props.active_address_id == address.id(),
"label": address.is_a(),
"props": bpy.context.scene.BIMOwnerProperties.address_attributes,
"props": props.address_attributes,
"list_attributes": cls.get_address_list_attributes(address),
}
)
return results
@classmethod
def get_address_list_attributes(cls, address):
results = []
props = bpy.context.scene.BIMOwnerProperties
def get_address_list_attributes(cls, address: ifcopenshell.entity_instance) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
props = tool.Owner.get_owner_props()
if address.is_a("IfcPostalAddress"):
names = ["AddressLines"]
elif address.is_a("IfcTelecomAddress"):
names = ["TelephoneNumbers", "FacsimileNumbers", "ElectronicMailAddresses", "MessagingIDs"]
else:
assert False, f"Unexpected entity: {address}"
for name in names:
if name == "AddressLines":
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.address_lines)]
@@ -78,6 +84,8 @@ class RolesAddressesData:
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.electronic_mail_addresses)]
elif name == "MessagingIDs":
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.messaging_ids)]
else:
assert False, f"Unexpected name: {name}"
results.append({"name": name, "items": items})
return results
@@ -92,14 +100,15 @@ class PeopleData(RolesAddressesData):
cls.is_loaded = True
@classmethod
def get_people(cls):
people = []
def get_people(cls) -> list[dict[str, Any]]:
props = tool.Owner.get_owner_props()
people: list[dict[str, Any]] = []
for person in tool.Ifc.get().by_type("IfcPerson"):
roles = cls.get_roles(person)
people.append(
{
"id": person.id(),
"props": bpy.context.scene.BIMOwnerProperties.person_attributes,
"props": props.person_attributes,
"name": cls.get_person_name(person),
"roles_label": ", ".join([r["label"] for r in roles]),
"is_editing": cls.get_person_is_editing(person),
@@ -112,7 +121,7 @@ class PeopleData(RolesAddressesData):
return people
@classmethod
def get_person_name(cls, person):
def get_person_name(cls, person: ifcopenshell.entity_instance) -> str:
if tool.Ifc.get_schema() == "IFC2X3":
name = person.Id
else:
@@ -124,20 +133,24 @@ class PeopleData(RolesAddressesData):
return name
@classmethod
def get_person_is_editing(cls, person):
return bpy.context.scene.BIMOwnerProperties.active_person_id == person.id()
def get_person_is_editing(cls, person: ifcopenshell.entity_instance) -> bool:
props = tool.Owner.get_owner_props()
return props.active_person_id == person.id()
@classmethod
def get_person_list_attributes(cls, person):
results = []
props = bpy.context.scene.BIMOwnerProperties
for name in ["MiddleNames", "PrefixTitles", "SuffixTitles"]:
def get_person_list_attributes(cls, person: ifcopenshell.entity_instance) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
props = tool.Owner.get_owner_props()
name: tool.Owner.PersonAttributeType
for name in ("MiddleNames", "PrefixTitles", "SuffixTitles"):
if name == "MiddleNames":
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.middle_names)]
elif name == "PrefixTitles":
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.prefix_titles)]
elif name == "SuffixTitles":
items = [{"id": id, "prop": prop} for id, prop in enumerate(props.suffix_titles)]
else:
assert False, name
results.append({"name": name, "items": items})
return results
@@ -152,17 +165,18 @@ class OrganisationsData(RolesAddressesData):
cls.is_loaded = True
@classmethod
def get_organisations(cls):
organisations = []
def get_organisations(cls) -> list[dict[str, Any]]:
props = tool.Owner.get_owner_props()
organisations: list[dict[str, Any]] = []
for organisation in tool.Ifc.get().by_type("IfcOrganization"):
roles = cls.get_roles(organisation)
organisations.append(
{
"id": organisation.id(),
"props": bpy.context.scene.BIMOwnerProperties.organisation_attributes,
"props": props.organisation_attributes,
"name": organisation.Name,
"roles_label": ", ".join([r["label"] for r in roles]),
"is_editing": bpy.context.scene.BIMOwnerProperties.active_organisation_id == organisation.id(),
"is_editing": props.active_organisation_id == organisation.id(),
"is_engaged": bool(organisation.Engages),
"roles": roles,
"addresses": cls.get_addresses(organisation),
@@ -186,26 +200,27 @@ class OwnerData:
cls.is_loaded = True
@classmethod
def get_user_person(cls):
def get_user_person(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
return [(str(p.id()), p[0] or "Unnamed", "") for p in tool.Ifc.get().by_type("IfcPerson")]
@classmethod
def get_user_organisation(cls):
def get_user_organisation(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
return [(str(p.id()), p[0] or "Unnamed", "") for p in tool.Ifc.get().by_type("IfcOrganization")]
@classmethod
def can_add_user(cls):
return tool.Ifc.get().by_type("IfcPerson") and tool.Ifc.get().by_type("IfcOrganization")
def can_add_user(cls) -> bool:
return bool(tool.Ifc.get().by_type("IfcPerson") and tool.Ifc.get().by_type("IfcOrganization"))
@classmethod
def get_users(cls):
results = []
def get_users(cls) -> list[dict[str, Any]]:
props = tool.Owner.get_owner_props()
results: list[dict[str, Any]] = []
for user in tool.Ifc.get().by_type("IfcPersonAndOrganization"):
results.append(
{
"id": user.id(),
"label": "{} ({})".format(user.ThePerson[0] or "Unnamed", user.TheOrganization[0] or "Unnamed"),
"is_active": bpy.context.scene.BIMOwnerProperties.active_user_id == user.id(),
"is_active": props.active_user_id == user.id(),
}
)
return results
@@ -224,48 +239,60 @@ class ActorData:
cls.data["actors"] = cls.actors()
@classmethod
def the_actor(cls):
if not (ifc_class := bpy.context.scene.BIMOwnerProperties.actor_type):
def the_actor(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
props = tool.Owner.get_owner_props()
if not (ifc_class := props.actor_type):
ifc_class = cls.actor_type()[0][0]
return [(str(p.id()), p[0] or "Unnamed", "") for p in tool.Ifc.get().by_type(ifc_class)]
@classmethod
def actors(cls):
actors = []
props = bpy.context.scene.BIMOwnerProperties
def actors(cls) -> list[dict[str, Any]]:
actors: list[dict[str, Any]] = []
props = tool.Owner.get_owner_props()
for actor in tool.Ifc.get().by_type(props.actor_class, include_subtypes=False):
is_editing = props.active_actor_id == actor.id()
if actor.TheActor.is_a("IfcPerson"):
the_actor = actor.TheActor.Identification or "N/A"
elif actor.TheActor.is_a("IfcOrganization"):
the_actor = actor.TheActor.Identification or "N/A"
elif actor.TheActor.is_a("IfcPersonAndOrganization"):
the_actor = actor.TheActor.ThePerson.Identification or "N/A"
the_actor += "-" + actor.TheActor.TheOrganization.Identification or "N/A"
the_actor: ifcopenshell.entity_instance = actor.TheActor
if the_actor.is_a("IfcPerson"):
the_actor_ = the_actor.Identification or "N/A"
elif the_actor.is_a("IfcOrganization"):
the_actor_ = the_actor.Identification or "N/A"
elif the_actor.is_a("IfcPersonAndOrganization"):
the_actor_ = the_actor.ThePerson.Identification or "N/A"
the_actor_ += "-" + the_actor.TheOrganization.Identification or "N/A"
else:
assert False, the_actor
actors.append(
{"id": actor.id(), "name": actor.Name or "Unnamed", "the_actor": the_actor, "is_editing": is_editing}
{
"id": actor.id(),
"name": actor.Name or "Unnamed",
"the_actor": the_actor_,
"is_editing": is_editing,
}
)
return actors
@classmethod
def actor_class(cls) -> list[tuple[str, str, str]]:
def actor_class(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
version = tool.Ifc.get_schema()
actor_doc = get_entity_doc(version, "IfcActor")
occupant_doc = get_entity_doc(version, "IfcOccupant")
assert actor_doc and occupant_doc
return [
("IfcActor", "Actor", get_entity_doc(version, "IfcActor").get("description", "")),
("IfcOccupant", "Occupant", get_entity_doc(version, "IfcOccupant").get("description", "")),
("IfcActor", "Actor", actor_doc.get("description", "")),
("IfcOccupant", "Occupant", occupant_doc.get("description", "")),
]
@classmethod
def actor_type(cls) -> list[tuple[str, str, str]]:
def actor_type(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
version = tool.Ifc.get_schema()
person_doc = get_entity_doc(version, "IfcPerson")
organization_doc = get_entity_doc(version, "IfcOrganization")
pao_doc = get_entity_doc(version, "IfcPersonAndOrganization")
assert person_doc and organization_doc and pao_doc
return [
("IfcPerson", "Person", get_entity_doc(version, "IfcPerson").get("description", "")),
("IfcOrganization", "Organisation", get_entity_doc(version, "IfcOrganization").get("description", "")),
(
"IfcPersonAndOrganization",
"User",
get_entity_doc(version, "IfcPersonAndOrganization").get("description", ""),
),
("IfcPerson", "Person", person_doc.get("description", "")),
("IfcOrganization", "Organisation", organization_doc.get("description", "")),
("IfcPersonAndOrganization", "User", pao_doc.get("description", "")),
]
@@ -279,25 +306,31 @@ class ObjectActorData:
cls.data = {"actor": cls.actor(), "actors": cls.actors()}
@classmethod
def actor(cls):
def actor(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
return [(str(p.id()), p.Name or "Unnamed", "") for p in tool.Ifc.get().by_type("IfcActor")]
@classmethod
def actors(cls):
results = []
element = tool.Ifc.get_entity(bpy.context.active_object)
def actors(cls) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
obj = bpy.context.active_object
if not obj:
return results
element = tool.Ifc.get_entity(obj)
if not element:
return results
for rel in getattr(element, "HasAssignments", []):
if rel.is_a("IfcRelAssignsToActor"):
actor = rel.RelatingActor
if actor.TheActor.is_a("IfcPerson"):
roles = cls.get_roles(actor.TheActor)
elif actor.TheActor.is_a("IfcOrganization"):
roles = cls.get_roles(actor.TheActor)
elif actor.TheActor.is_a("IfcPersonAndOrganization"):
roles = cls.get_roles(actor.TheActor.ThePerson)
roles.extend(cls.get_roles(actor.TheActor.TheOrganization))
the_actor: ifcopenshell.entity_instance = actor.TheActor
if the_actor.is_a("IfcPerson"):
roles = cls.get_roles(the_actor)
elif the_actor.is_a("IfcOrganization"):
roles = cls.get_roles(the_actor)
elif the_actor.is_a("IfcPersonAndOrganization"):
roles = cls.get_roles(the_actor.ThePerson)
roles.extend(cls.get_roles(the_actor.TheOrganization))
else:
assert False, the_actor
role = ", ".join(roles)
results.append(
{"id": actor.id(), "name": actor.Name or "Unnamed", "role": role, "ifc_class": actor.is_a()}
@@ -305,5 +338,5 @@ class ObjectActorData:
return results
@classmethod
def get_roles(cls, parent):
def get_roles(cls, parent: ifcopenshell.entity_instance) -> list[Union[str, None]]:
return [r.UserDefinedRole or r.Role for r in parent.Roles or []]
+162 -65
View File
@@ -19,25 +19,35 @@
import bpy
import bonsai.tool as tool
import bonsai.core.owner as core
from ifcopenshell.api.owner.add_address import ADDRESS_TYPE
from typing import TYPE_CHECKING, get_args
if TYPE_CHECKING:
import bpy._typing.rna_enums as rna_enums
class EnableEditingPerson(bpy.types.Operator, tool.Ifc.Operator):
class EnableEditingPerson(bpy.types.Operator):
bl_idname = "bim.enable_editing_person"
bl_label = "Enable Editing Person"
bl_options = {"REGISTER", "UNDO"}
person: bpy.props.IntProperty()
person: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
person: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.enable_editing_person(tool.Owner, person=tool.Ifc.get().by_id(self.person))
return {"FINISHED"}
class DisableEditingPerson(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingPerson(bpy.types.Operator):
bl_idname = "bim.disable_editing_person"
bl_label = "Disable Editing Person"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.disable_editing_person(tool.Owner)
return {"FINISHED"}
class AddPerson(bpy.types.Operator, tool.Ifc.Operator):
@@ -45,7 +55,7 @@ class AddPerson(bpy.types.Operator, tool.Ifc.Operator):
bl_label = "Add Person"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def _execute(self, context) -> None:
core.add_person(tool.Ifc)
@@ -62,57 +72,81 @@ class RemovePerson(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_person"
bl_label = "Remove Person"
bl_options = {"REGISTER", "UNDO"}
person: bpy.props.IntProperty()
person: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
person: int
def _execute(self, context):
core.remove_person(tool.Ifc, person=tool.Ifc.get().by_id(self.person))
class AddPersonAttribute(bpy.types.Operator, tool.Ifc.Operator):
class AddPersonAttribute(bpy.types.Operator):
bl_idname = "bim.add_person_attribute"
bl_label = "Add Person Attribute"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
name: bpy.props.EnumProperty( # pyright: ignore[reportRedeclaration]
items=tuple((i, i, "") for i in get_args(tool.Owner.PersonAttributeType)),
)
def _execute(self, context):
if TYPE_CHECKING:
name: tool.Owner.PersonAttributeType # pyright: ignore[reportIncompatibleVariableOverride]
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.add_person_attribute(tool.Owner, name=self.name)
return {"FINISHED"}
class RemovePersonAttribute(bpy.types.Operator, tool.Ifc.Operator):
class RemovePersonAttribute(bpy.types.Operator):
bl_idname = "bim.remove_person_attribute"
bl_label = "Remove Person Attribute"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
id: bpy.props.IntProperty()
name: bpy.props.EnumProperty( # pyright: ignore[reportRedeclaration]
items=tuple((i, i, "") for i in get_args(tool.Owner.PersonAttributeType)),
)
id: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
name: tool.Owner.PersonAttributeType # pyright: ignore[reportIncompatibleVariableOverride]
id: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.remove_person_attribute(tool.Owner, name=self.name, id=self.id)
return {"FINISHED"}
class EnableEditingRole(bpy.types.Operator, tool.Ifc.Operator):
class EnableEditingRole(bpy.types.Operator):
bl_idname = "bim.enable_editing_role"
bl_label = "Enable Editing Role"
bl_options = {"REGISTER", "UNDO"}
role: bpy.props.IntProperty()
role: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
role: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.enable_editing_role(tool.Owner, role=tool.Ifc.get().by_id(self.role))
return {"FINISHED"}
class DisableEditingRole(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingRole(bpy.types.Operator):
bl_idname = "bim.disable_editing_role"
bl_label = "Disable Editing Role"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.disable_editing_role(tool.Owner)
return {"FINISHED"}
class AddRole(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_role"
bl_label = "Add Role"
bl_options = {"REGISTER", "UNDO"}
parent: bpy.props.IntProperty()
parent: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
parent: int
def _execute(self, context):
core.add_role(tool.Ifc, parent=tool.Ifc.get().by_id(self.parent))
@@ -131,7 +165,10 @@ class RemoveRole(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_role"
bl_label = "Remove Role"
bl_options = {"REGISTER", "UNDO"}
role: bpy.props.IntProperty()
role: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
role: int
def _execute(self, context):
core.remove_role(tool.Ifc, role=tool.Ifc.get().by_id(self.role))
@@ -141,51 +178,74 @@ class AddAddress(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_address"
bl_label = "Add Address"
bl_options = {"REGISTER", "UNDO"}
parent: bpy.props.IntProperty()
ifc_class: bpy.props.StringProperty()
parent: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
ifc_class: bpy.props.EnumProperty( # pyright: ignore[reportRedeclaration]
items=tuple((i, i, "") for i in get_args(ADDRESS_TYPE)),
)
if TYPE_CHECKING:
parent: int
ifc_class: ADDRESS_TYPE
def _execute(self, context):
core.add_address(tool.Ifc, parent=tool.Ifc.get().by_id(self.parent), ifc_class=self.ifc_class)
class AddAddressAttribute(bpy.types.Operator, tool.Ifc.Operator):
class AddAddressAttribute(bpy.types.Operator):
bl_idname = "bim.add_address_attribute"
bl_label = "Add Address Attribute"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
name: bpy.props.EnumProperty( # pyright: ignore[reportRedeclaration]
items=tuple((i, i, "") for i in get_args(tool.Owner.AddressAttributeType)),
)
def _execute(self, context):
if TYPE_CHECKING:
name: tool.Owner.AddressAttributeType # pyright: ignore[reportIncompatibleVariableOverride]
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.add_address_attribute(tool.Owner, name=self.name)
return {"FINISHED"}
class RemoveAddressAttribute(bpy.types.Operator, tool.Ifc.Operator):
class RemoveAddressAttribute(bpy.types.Operator):
bl_idname = "bim.remove_address_attribute"
bl_label = "Remove Address Attribute"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
id: bpy.props.IntProperty()
name: bpy.props.EnumProperty( # pyright: ignore[reportRedeclaration]
items=tuple((i, i, "") for i in get_args(tool.Owner.AddressAttributeType)),
)
def _execute(self, context):
if TYPE_CHECKING:
name: tool.Owner.AddressAttributeType # pyright: ignore[reportIncompatibleVariableOverride]
id: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.remove_address_attribute(tool.Owner, name=self.name, id=self.id)
return {"FINISHED"}
class EnableEditingAddress(bpy.types.Operator, tool.Ifc.Operator):
class EnableEditingAddress(bpy.types.Operator):
bl_idname = "bim.enable_editing_address"
bl_label = "Enable Editing Address"
bl_options = {"REGISTER", "UNDO"}
address: bpy.props.IntProperty()
address: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
address: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.enable_editing_address(tool.Owner, address=tool.Ifc.get().by_id(self.address))
return {"FINISHED"}
class DisableEditingAddress(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingAddress(bpy.types.Operator):
bl_idname = "bim.disable_editing_address"
bl_label = "Disable Editing Address"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.disable_editing_address(tool.Owner)
return {"FINISHED"}
class EditAddress(bpy.types.Operator, tool.Ifc.Operator):
@@ -201,29 +261,37 @@ class RemoveAddress(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_address"
bl_label = "Remove Address"
bl_options = {"REGISTER", "UNDO"}
address: bpy.props.IntProperty()
address: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
address: int
def _execute(self, context):
core.remove_address(tool.Ifc, address=tool.Ifc.get().by_id(self.address))
class EnableEditingOrganisation(bpy.types.Operator, tool.Ifc.Operator):
class EnableEditingOrganisation(bpy.types.Operator):
bl_idname = "bim.enable_editing_organisation"
bl_label = "Enable Editing Organisation"
bl_options = {"REGISTER", "UNDO"}
organisation: bpy.props.IntProperty()
organisation: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
organisation: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.enable_editing_organisation(tool.Owner, organisation=tool.Ifc.get().by_id(self.organisation))
return {"FINISHED"}
class DisableEditingOrganisation(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingOrganisation(bpy.types.Operator):
bl_idname = "bim.disable_editing_organisation"
bl_label = "Disable Editing Organisation"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.disable_editing_organisation(tool.Owner)
return {"FINISHED"}
class AddOrganisation(bpy.types.Operator, tool.Ifc.Operator):
@@ -248,7 +316,10 @@ class RemoveOrganisation(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_organisation"
bl_label = "Remove Organisation"
bl_options = {"REGISTER", "UNDO"}
organisation: bpy.props.IntProperty()
organisation: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
organisation: int
def _execute(self, context):
core.remove_organisation(tool.Ifc, tool.Ifc.get().by_id(self.organisation))
@@ -258,8 +329,12 @@ class AddPersonAndOrganisation(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_person_and_organisation"
bl_label = "Add Person And Organisation"
bl_options = {"REGISTER", "UNDO"}
person: bpy.props.IntProperty()
organisation: bpy.props.IntProperty()
person: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
organisation: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
person: int
organisation: int
def _execute(self, context):
core.add_person_and_organisation(
@@ -271,7 +346,10 @@ class RemovePersonAndOrganisation(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_person_and_organisation"
bl_label = "Remove Person And Organisation"
bl_options = {"REGISTER", "UNDO"}
person_and_organisation: bpy.props.IntProperty()
person_and_organisation: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
person_and_organisation: int
def _execute(self, context):
core.remove_person_and_organisation(
@@ -279,24 +357,29 @@ class RemovePersonAndOrganisation(bpy.types.Operator, tool.Ifc.Operator):
)
class SetUser(bpy.types.Operator, tool.Ifc.Operator):
class SetUser(bpy.types.Operator):
bl_idname = "bim.set_user"
bl_label = "Set User"
bl_options = {"REGISTER", "UNDO"}
user: bpy.props.IntProperty()
user: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
user: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.set_user(tool.Owner, user=tool.Ifc.get().by_id(self.user))
return {"FINISHED"}
class ClearUser(bpy.types.Operator, tool.Ifc.Operator):
class ClearUser(bpy.types.Operator):
bl_idname = "bim.clear_user"
bl_label = "Clear User"
bl_options = {"REGISTER", "UNDO"}
user: bpy.props.IntProperty()
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.clear_user(tool.Owner)
return {"FINISHED"}
class AddActor(bpy.types.Operator, tool.Ifc.Operator):
@@ -305,28 +388,33 @@ class AddActor(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
props = bpy.context.scene.BIMOwnerProperties
props = tool.Owner.get_owner_props()
if props.the_actor:
core.add_actor(tool.Ifc, ifc_class=props.actor_class, actor=tool.Ifc.get().by_id(int(props.the_actor)))
class EnableEditingActor(bpy.types.Operator, tool.Ifc.Operator):
class EnableEditingActor(bpy.types.Operator):
bl_idname = "bim.enable_editing_actor"
bl_label = "Enable Editing Actor"
bl_options = {"REGISTER", "UNDO"}
actor: bpy.props.IntProperty()
actor: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
def _execute(self, context):
if TYPE_CHECKING:
actor: int
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.enable_editing_actor(tool.Owner, actor=tool.Ifc.get().by_id(self.actor))
return {"FINISHED"}
class DisableEditingActor(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingActor(bpy.types.Operator):
bl_idname = "bim.disable_editing_actor"
bl_label = "Disable Editing Actor"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
core.disable_editing_actor(tool.Owner)
return {"FINISHED"}
class EditActor(bpy.types.Operator, tool.Ifc.Operator):
@@ -342,7 +430,10 @@ class RemoveActor(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_actor"
bl_label = "Remove Actor"
bl_options = {"REGISTER", "UNDO"}
actor: bpy.props.IntProperty()
actor: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
actor: int
def _execute(self, context):
core.remove_actor(tool.Ifc, actor=tool.Ifc.get().by_id(self.actor))
@@ -352,21 +443,27 @@ class AssignActor(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.assign_actor"
bl_label = "Assign Actor"
bl_options = {"REGISTER", "UNDO"}
actor: bpy.props.IntProperty()
actor: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
actor: int
def _execute(self, context):
core.assign_actor(
tool.Ifc, actor=tool.Ifc.get().by_id(self.actor), element=tool.Ifc.get_entity(context.active_object)
)
assert (obj := context.active_object)
assert (element := tool.Ifc.get_entity(obj))
core.assign_actor(tool.Ifc, actor=tool.Ifc.get().by_id(self.actor), element=element)
class UnassignActor(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.unassign_actor"
bl_label = "Unassign Actor"
bl_options = {"REGISTER", "UNDO"}
actor: bpy.props.IntProperty()
actor: bpy.props.IntProperty() # pyright: ignore[reportRedeclaration]
if TYPE_CHECKING:
actor: int
def _execute(self, context):
core.unassign_actor(
tool.Ifc, actor=tool.Ifc.get().by_id(self.actor), element=tool.Ifc.get_entity(context.active_object)
)
assert (obj := context.active_object)
assert (element := tool.Ifc.get_entity(obj))
core.unassign_actor(tool.Ifc, actor=tool.Ifc.get().by_id(self.actor), element=element)
+36 -8
View File
@@ -20,6 +20,7 @@ import bpy
import bonsai.tool as tool
from bonsai.bim.prop import StrProperty, Attribute
from bonsai.bim.module.owner.data import OwnerData, ActorData, ObjectActorData
from typing import TYPE_CHECKING, Literal
from bpy.types import PropertyGroup
from bpy.props import (
PointerProperty,
@@ -33,45 +34,45 @@ from bpy.props import (
)
def get_user_person(self, context):
def get_user_person(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not OwnerData.is_loaded:
OwnerData.load()
return OwnerData.data["user_person"]
def get_user_organisation(self, context):
def get_user_organisation(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not OwnerData.is_loaded:
OwnerData.load()
return OwnerData.data["user_organisation"]
def get_the_actor(self, context):
def get_the_actor(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not ActorData.is_loaded:
ActorData.load()
return ActorData.data["the_actor"]
def get_actor(self, context):
def get_actor(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not ObjectActorData.is_loaded:
ObjectActorData.load()
return ObjectActorData.data["actor"]
def update_actor_type(self, context):
def update_actor_type(self: "BIMOwnerProperties", context: bpy.types.Context) -> None:
ActorData.data["the_actor"] = ActorData.the_actor()
def update_actor_class(self, context):
def update_actor_class(self: "BIMOwnerProperties", context: bpy.types.Context) -> None:
ActorData.data["actors"] = ActorData.actors()
def get_actor_class(self, context):
def get_actor_class(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not ActorData.is_loaded:
ActorData.load()
return ActorData.data["actor_class"]
def get_actor_type(self, context):
def get_actor_type(self: "BIMOwnerProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
if not ActorData.is_loaded:
ActorData.load()
return ActorData.data["actor_type"]
@@ -119,3 +120,30 @@ class BIMOwnerProperties(PropertyGroup):
items=get_the_actor, name="Actor", description="This entity represents an individual human being."
)
actor: EnumProperty(items=get_actor, name="Actor")
if TYPE_CHECKING:
active_person_id: int
person_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
middle_names: bpy.types.bpy_prop_collection_idprop[StrProperty]
prefix_titles: bpy.types.bpy_prop_collection_idprop[StrProperty]
suffix_titles: bpy.types.bpy_prop_collection_idprop[StrProperty]
active_organisation_id: int
organisation_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
active_role_id: int
role_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
active_address_id: int
address_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
address_lines: bpy.types.bpy_prop_collection_idprop[StrProperty]
telephone_numbers: bpy.types.bpy_prop_collection_idprop[StrProperty]
facsimile_numbers: bpy.types.bpy_prop_collection_idprop[StrProperty]
electronic_mail_addresses: bpy.types.bpy_prop_collection_idprop[StrProperty]
messaging_ids: bpy.types.bpy_prop_collection_idprop[StrProperty]
user_person: str
user_organisation: str
active_user_id: int
active_actor_id: int
actor_attributes: bpy.types.bpy_prop_collection_idprop[Attribute]
actor_class: Literal["IfcActor", "IfcOccupant"]
actor_type: str
the_actor: str
actor: str
+22 -13
View File
@@ -19,10 +19,11 @@
import bpy
import bonsai.bim.helper
import bonsai.tool as tool
from typing import Any
from bonsai.bim.module.owner.data import PeopleData, OrganisationsData, OwnerData, ActorData, ObjectActorData
def draw_roles(box, parent):
def draw_roles(box: bpy.types.UILayout, parent: dict[str, Any]) -> None:
row = box.row(align=True)
row.label(text="Roles")
op = row.operator("bim.add_role", icon="ADD", text="")
@@ -41,7 +42,7 @@ def draw_roles(box, parent):
row.operator("bim.remove_role", icon="X", text="").role = role["id"]
def draw_addresses(box, parent):
def draw_addresses(box: bpy.types.UILayout, parent: dict[str, Any]) -> None:
row = box.row(align=True)
row.label(text="Addresses")
op = row.operator("bim.add_address", icon="LINK_BLEND", text="")
@@ -87,12 +88,13 @@ class BIM_PT_people(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not PeopleData.is_loaded:
PeopleData.load()
assert self.layout
self.layout.use_property_split = True
self.layout.use_property_decorate = False
@@ -102,7 +104,8 @@ class BIM_PT_people(bpy.types.Panel):
for person in PeopleData.data["people"]:
self.draw_person(person)
def draw_person(self, person):
def draw_person(self, person: dict[str, Any]) -> None:
assert self.layout
if person["is_editing"]:
box = self.layout.box()
row = box.row(align=True)
@@ -146,12 +149,13 @@ class BIM_PT_organisations(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not OrganisationsData.is_loaded:
OrganisationsData.load()
assert self.layout
self.layout.use_property_split = True
self.layout.use_property_decorate = False
@@ -161,7 +165,8 @@ class BIM_PT_organisations(bpy.types.Panel):
for organisation in OrganisationsData.data["organisations"]:
self.draw_organisation(organisation)
def draw_organisation(self, organisation):
def draw_organisation(self, organisation: dict[str, Any]) -> None:
assert self.layout
if organisation["is_editing"]:
box = self.layout.box()
row = box.row(align=True)
@@ -193,15 +198,16 @@ class BIM_PT_owner(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not OwnerData.is_loaded:
OwnerData.load()
assert self.layout
self.layout.use_property_split = True
self.layout.use_property_decorate = False
props = context.scene.BIMOwnerProperties
props = tool.Owner.get_owner_props()
if not OwnerData.data["user_person"]:
self.layout.label(text="No people found.")
@@ -244,13 +250,14 @@ class BIM_PT_actor(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not ActorData.is_loaded:
ActorData.load()
self.props = context.scene.BIMOwnerProperties
assert self.layout
self.props = tool.Owner.get_owner_props()
self.layout.use_property_split = True
self.layout.use_property_decorate = False
@@ -268,7 +275,8 @@ class BIM_PT_actor(bpy.types.Panel):
for actor in ActorData.data["actors"]:
self.draw_actor(actor)
def draw_actor(self, actor):
def draw_actor(self, actor: dict[str, Any]) -> None:
assert self.layout
if actor["is_editing"]:
box = self.layout.box()
row = box.row(align=True)
@@ -295,13 +303,14 @@ class BIM_PT_object_actor(bpy.types.Panel):
@classmethod
def poll(cls, context):
return tool.Ifc.get()
return bool(tool.Ifc.get())
def draw(self, context):
if not ObjectActorData.is_loaded:
ObjectActorData.load()
self.props = context.scene.BIMOwnerProperties
assert self.layout
self.props = tool.Owner.get_owner_props()
if not ObjectActorData.data["actor"]:
row = self.layout.row(align=True)
@@ -58,7 +58,7 @@ def updateResourceName(self, context):
attributes={"Name": self.name},
)
if props.active_resource_id == self.ifc_definition_id:
attribute = props.resource_attributes.get("Name")
attribute = props.resource_attributes["Name"]
attribute.string_value = self.name
bonsai.bim.module.resource.data.refresh()
tool.Sequence.refresh_task_resources()
@@ -195,6 +195,17 @@ class AssignClass(bpy.types.Operator, tool.Ifc.Operator):
should_add_representation: bool
ifc_representation_class: str
@classmethod
def poll(cls, context):
if not tool.Ifc.get():
cls.poll_message_set("No IFC project loaded.")
return False
# object.select_all operator's requirement and it's generally more safe.
elif context.mode != "OBJECT":
cls.poll_message_set(f"Can only assign class in OBJECT mode, not in {context.mode} mode.")
return False
return True
def _execute(self, context):
ifc_file = tool.Ifc.get()
props = tool.Root.get_root_props()
@@ -426,7 +426,7 @@ class EnableEditingZone(bpy.types.Operator):
return {"FINISHED"}
class DisableEditingZone(bpy.types.Operator, tool.Ifc.Operator):
class DisableEditingZone(bpy.types.Operator):
bl_idname = "bim.disable_editing_zone"
bl_label = "Disable Editing Zone"
bl_options = {"REGISTER", "UNDO"}
+32
View File
@@ -1286,3 +1286,35 @@ class CopyTextToClipboard(bpy.types.Operator):
def execute(self, context):
context.window_manager.clipboard = self.text
return {"FINISHED"}
class ShowSystemInfo(bpy.types.Operator):
bl_idname = "bim.show_system_info"
bl_label = "System Info"
bl_description = "Show debug information and copy it to the clipboard."
bl_options = set()
info_text: bpy.props.StringProperty()
def execute(self, context):
# invoke_popup doesn't show a popup, if there's no `execute` method.
return {"FINISHED"}
def invoke(self, context, event):
assert context.window_manager
# Invoke the bim.copy_debug_information operator to get the info to the clipboard
bpy.ops.bim.copy_debug_information()
self.info_text = context.window_manager.clipboard
return context.window_manager.invoke_popup(self, width=600)
def draw(self, context):
assert self.layout
layout = self.layout
col = layout.column()
for line in self.info_text.split("\n"):
col.label(text=line)
col.separator()
col.label(text="(The information has been copied to the clipboard.)")
+32 -9
View File
@@ -531,11 +531,18 @@ class BIM_PT_tabs(Panel):
row.operator("bim.close_blend_warning", text="", icon="CANCEL")
gprops = tool.Geometry.get_geometry_props()
# Check that Blender mode and IFC Mode do match.
if context.mode == "OBJECT" and gprops.mode in ("OBJECT", "ITEM"):
pass
elif context.mode.startswith("EDIT") and gprops.mode == "EDIT":
pass
else:
# Occurs when user wasn't using IFC mode or TAB/Esc hotkeys to change mode.
# E.g. if user used TAB to set object's mode to EDIT and then used
# Blender mode property to set it back to OBJECT.
#
# We show warning only for objects connected to IFC,
# so users with vanilla Blender objects won't be affected.
elif tool.Geometry.get_active_or_representation_obj():
box = self.layout.box()
box.alert = True
row = box.row(align=True)
@@ -1182,8 +1189,10 @@ class UIData:
def draw_statusbar(self, context):
if not UIData.is_loaded:
UIData.load()
text = f"Bonsai v{UIData.data['version']}"
self.layout.label(text=text)
bonsai_version = f"Bonsai v{UIData.data['version']}"
layout = self.layout
row = layout.row()
row.operator("bim.show_system_info", text=bonsai_version, emboss=False)
def draw_custom_context_menu(self: bpy.types.Menu, context: bpy.types.Context) -> None:
@@ -1194,16 +1203,23 @@ def draw_custom_context_menu(self: bpy.types.Menu, context: bpy.types.Context) -
or not hasattr(context.button_prop, "identifier")
):
return
prop = context.button_pointer
prop_name = context.button_prop.identifier
prop_value = getattr(prop, prop_name, None)
if not isinstance(prop_value, str):
# E.g. `bim.props.Attribute`.
prop_struct: bpy.types.bpy_struct = context.button_pointer
# E.g. `IntProperty("int_value")`
prop: bpy.types.Property = context.button_prop
prop_name = prop.identifier
# TODO: when `prop_struct` doesn't have `prop_name`?
if not hasattr(prop_struct, prop_name):
return
prop_value = getattr(prop_struct, prop_name, ...)
if prop_value is ...:
return
version = tool.Ifc.get_schema()
assert self.layout
layout = self.layout
if isinstance(context.button_pointer, Attribute):
attr = context.button_pointer
if isinstance(prop_struct, Attribute):
attr = prop_struct
description = attr.description
ifc_class = attr.ifc_class
if ifc_class:
@@ -1226,6 +1242,13 @@ def draw_custom_context_menu(self: bpy.types.Menu, context: bpy.types.Context) -
op = layout.operator("bim.copy_text_to_clipboard", text="Copy Attribute Name", icon="COPYDOWN")
op.text = attr_name
else:
# Basically context menu for any Blender property will end up here,
# and will check 3 types of docs.
# So at least we're skipping all non-string properties.
if not isinstance(prop_value, str):
return
docs = None
# Ugly but we can't know which type of data is under the cursor so we test everything until it clicks
try:
docs = get_entity_doc(version, prop_value)
+57
View File
@@ -0,0 +1,57 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2022 Dion Moult <dion@thinkmoult.com>
#
# 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/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a core.py file to define all of its core functions. A core
# function describes what happens when the user wants to do something like
# pressing a button.
# Think of a core function as a short poem of pseudocode that describes what
# happens in different usecases. A core should be no more than 50 lines of code,
# even in the most complex of features. A core simply delegates tasks to tools
# in a sequence that describes the flow of logic in a feature - in other words,
# it tells tools to do different things. You will notice that the core doesn't
# have any code that deals with Blender or IFC directly - these are all little
# details that are hidden away in tools. The core is not interested in these
# details, the core is only concerned with the big picture.
# Imagine, no matter how complex a software can be, every feature can be
# described in regular sentences in under 50 lines. That is the purpose of the
# core.
# Here's the simplest possible core function. It does one thing only. Remember:
# core functions delegate tasks to tools, so all core functions need at least
# one tool.
def build_alignment(alignment):
# We're telling the demo tool to set a message. We aren't interested how the
# tool works, that's a detail. We aren't interested in the interface, like
# where the message is shown. You can name these functions whatever you feel
# best describes what's going on, like if you had to describe the feature to
# someone else.
alignment.build()
def add_survey_point(alignment,x,y):
alignment.add_survey_point(x,y)
+64 -46
View File
@@ -27,16 +27,16 @@ if TYPE_CHECKING:
import bonsai.tool as tool
def enable_editing_text(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
def enable_editing_text(drawing: type[tool.Drawing], obj: bpy.types.Object) -> None:
drawing.enable_editing_text(obj)
drawing.import_text_attributes(obj)
def disable_editing_text(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
def disable_editing_text(drawing: type[tool.Drawing], obj: bpy.types.Object) -> None:
drawing.disable_editing_text(obj)
def edit_text(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
def edit_text(drawing: type[tool.Drawing], obj: bpy.types.Object) -> None:
drawing.synchronise_ifc_and_text_attributes(obj)
drawing.update_text_size_pset(obj)
drawing.update_newline_at(obj)
@@ -44,17 +44,20 @@ def edit_text(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
drawing.disable_editing_text(obj)
def enable_editing_assigned_product(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
def enable_editing_assigned_product(drawing: type[tool.Drawing], obj: bpy.types.Object) -> None:
drawing.enable_editing_assigned_product(obj)
drawing.import_assigned_product(obj)
def disable_editing_assigned_product(drawing: tool.Drawing, obj: bpy.types.Object) -> None:
def disable_editing_assigned_product(drawing: type[tool.Drawing], obj: bpy.types.Object) -> None:
drawing.disable_editing_assigned_product(obj)
def edit_assigned_product(
ifc: tool.Ifc, drawing: tool.Drawing, obj: bpy.types.Object, product: Optional[ifcopenshell.entity_instance] = None
ifc: type[tool.Ifc],
drawing: type[tool.Drawing],
obj: bpy.types.Object,
product: Optional[ifcopenshell.entity_instance] = None,
) -> None:
element = ifc.get_entity(obj)
assert element
@@ -70,16 +73,16 @@ def edit_assigned_product(
drawing.disable_editing_assigned_product(obj)
def load_sheets(drawing: tool.Drawing) -> None:
def load_sheets(drawing: type[tool.Drawing]) -> None:
drawing.import_sheets()
drawing.enable_editing_sheets()
def disable_editing_sheets(drawing: tool.Drawing) -> None:
def disable_editing_sheets(drawing: type[tool.Drawing]) -> None:
drawing.disable_editing_sheets()
def add_sheet(ifc: tool.Ifc, drawing: tool.Drawing, titleblock: ifcopenshell.entity_instance) -> None:
def add_sheet(ifc: type[tool.Ifc], drawing: type[tool.Drawing], titleblock: ifcopenshell.entity_instance) -> None:
sheet = ifc.run("document.add_information")
layout = ifc.run("document.add_reference", information=sheet)
titleblock_reference = ifc.run("document.add_reference", information=sheet)
@@ -105,7 +108,7 @@ def add_sheet(ifc: tool.Ifc, drawing: tool.Drawing, titleblock: ifcopenshell.ent
drawing.import_sheets()
def regenerate_sheet(drawing: tool.Drawing, sheet: ifcopenshell.entity_instance) -> None:
def regenerate_sheet(drawing: type[tool.Drawing], sheet: ifcopenshell.entity_instance) -> None:
titleblock_uri = drawing.get_document_uri(sheet, "TITLEBLOCK")
drawing.create_svg_sheet(sheet, drawing.sanitise_filename(Path(titleblock_uri).stem))
try:
@@ -116,11 +119,11 @@ def regenerate_sheet(drawing: tool.Drawing, sheet: ifcopenshell.entity_instance)
drawing.delete_file(path_layout)
def open_layout(drawing: tool.Drawing, sheet: ifcopenshell.entity_instance) -> None:
def open_layout(drawing: type[tool.Drawing], sheet: ifcopenshell.entity_instance) -> None:
drawing.open_layout_svg(drawing.get_document_uri(sheet, "LAYOUT"))
def remove_sheet(ifc: tool.Ifc, drawing: tool.Drawing, sheet: ifcopenshell.entity_instance) -> None:
def remove_sheet(ifc: type[tool.Ifc], drawing: type[tool.Drawing], sheet: ifcopenshell.entity_instance) -> None:
for reference in drawing.get_document_references(sheet):
if drawing.get_reference_description(reference) in ("LAYOUT", "SHEET", "REVISION", "RASTER"):
uri = ifc.resolve_uri(drawing.get_document_uri(reference))
@@ -131,7 +134,11 @@ def remove_sheet(ifc: tool.Ifc, drawing: tool.Drawing, sheet: ifcopenshell.entit
def rename_sheet(
ifc: tool.Ifc, drawing: tool.Drawing, sheet: ifcopenshell.entity_instance, identification: str, name: str
ifc: type[tool.Ifc],
drawing: type[tool.Drawing],
sheet: ifcopenshell.entity_instance,
identification: str,
name: str,
) -> None:
if ifc.get_schema() == "IFC2X3":
attributes = {"DocumentId": identification, "Name": name}
@@ -159,31 +166,33 @@ def rename_sheet(
def rename_reference(
ifc: tool.Ifc, drawing: tool.Drawing, reference: ifcopenshell.entity_instance, identification: str
ifc: type[tool.Ifc], drawing: type[tool.Drawing], reference: ifcopenshell.entity_instance, identification: str
) -> None:
attributes = drawing.generate_reference_attributes(reference, Identification=identification)
ifc.run("document.edit_reference", reference=reference, attributes=attributes)
def load_schedules(drawing: tool.Drawing) -> None:
def load_schedules(drawing: type[tool.Drawing]) -> None:
drawing.import_documents("SCHEDULE")
drawing.enable_editing_schedules()
def load_references(drawing: tool.Drawing) -> None:
def load_references(drawing: type[tool.Drawing]) -> None:
drawing.import_documents("REFERENCE")
drawing.enable_editing_references()
def disable_editing_schedules(drawing: tool.Drawing) -> None:
def disable_editing_schedules(drawing: type[tool.Drawing]) -> None:
drawing.disable_editing_schedules()
def disable_editing_references(drawing: tool.Drawing) -> None:
def disable_editing_references(drawing: type[tool.Drawing]) -> None:
drawing.disable_editing_references()
def add_document(ifc: tool.Ifc, drawing: tool.Drawing, document_type: tool.Drawing.DOCUMENT_TYPE, uri: str) -> None:
def add_document(
ifc: type[tool.Ifc], drawing: type[tool.Drawing], document_type: type[tool.Drawing].DOCUMENT_TYPE, uri: str
) -> None:
document = ifc.run("document.add_information")
reference = ifc.run("document.add_reference", information=document)
name = drawing.get_path_filename(uri)
@@ -197,49 +206,50 @@ def add_document(ifc: tool.Ifc, drawing: tool.Drawing, document_type: tool.Drawi
def remove_document(
ifc: tool.Ifc,
drawing: tool.Drawing,
document_type: tool.Drawing.DOCUMENT_TYPE,
ifc: type[tool.Ifc],
drawing: type[tool.Drawing],
document_type: type[tool.Drawing].DOCUMENT_TYPE,
document: ifcopenshell.entity_instance,
) -> None:
ifc.run("document.remove_information", information=document)
drawing.import_documents(document_type)
def open_schedule(drawing: tool.Drawing, schedule: ifcopenshell.entity_instance) -> None:
def open_schedule(drawing: type[tool.Drawing], schedule: ifcopenshell.entity_instance) -> None:
drawing.open_spreadsheet(drawing.get_document_uri(schedule))
def open_reference(drawing: tool.Drawing, reference: ifcopenshell.entity_instance) -> None:
def open_reference(drawing: type[tool.Drawing], reference: ifcopenshell.entity_instance) -> None:
drawing.open_svg(drawing.get_document_uri(reference))
def update_document_name(
ifc: tool.Ifc, drawing: tool.Drawing, document: ifcopenshell.entity_instance, name=None
ifc: type[tool.Ifc], drawing: type[tool.Drawing], document: ifcopenshell.entity_instance, name=None
) -> None:
if drawing.get_name(document) != name:
ifc.run("document.edit_information", information=document, attributes={"Name": name})
def load_drawings(drawing: tool.Drawing) -> None:
def load_drawings(drawing: type[tool.Drawing]) -> None:
drawing.import_drawings()
drawing.enable_editing_drawings()
def disable_editing_drawings(drawing: tool.Drawing) -> None:
def disable_editing_drawings(drawing: type[tool.Drawing]) -> None:
drawing.disable_editing_drawings()
def add_drawing(
ifc: tool.Ifc,
collector: tool.Collector,
drawing: tool.Drawing,
target_view: Union[ifcopenshell.util.representation.TARGET_VIEW, None] = None,
location_hint: Union[str, None] = None,
ifc: type[tool.Ifc],
collector: type[tool.Collector],
drawing: type[tool.Drawing],
target_view: ifcopenshell.util.representation.TARGET_VIEW,
location_hint: Union[tool.Drawing.LocationHintLiteral, int],
) -> None:
assert location_hint is not None
drawing_name = drawing.ensure_unique_drawing_name(drawing.generate_drawing_name(target_view, location_hint))
drawing_matrix = drawing.generate_drawing_matrix(target_view, location_hint)
camera = drawing.create_camera(drawing_name, drawing_matrix, location_hint)
camera = drawing.create_camera(drawing_name, drawing_matrix, location_hint, target_view)
element = drawing.run_root_assign_class(
obj=camera,
ifc_class="IfcAnnotation",
@@ -295,10 +305,10 @@ def add_drawing(
def duplicate_drawing(
ifc: tool.Ifc,
blender: tool.Blender,
drawing_tool: tool.Drawing,
geometry: tool.Geometry,
ifc: type[tool.Ifc],
blender: type[tool.Blender],
drawing_tool: type[tool.Drawing],
geometry: type[tool.Geometry],
drawing: ifcopenshell.entity_instance,
should_duplicate_annotations: bool = False,
) -> ifcopenshell.entity_instance:
@@ -341,7 +351,9 @@ def duplicate_drawing(
return new_drawing
def remove_drawing(ifc: tool.Ifc, drawing_tool: tool.Drawing, drawing: ifcopenshell.entity_instance) -> None:
def remove_drawing(
ifc: type[tool.Ifc], drawing_tool: type[tool.Drawing], drawing: ifcopenshell.entity_instance
) -> None:
if drawing_tool.is_active_drawing(drawing):
drawing_tool.run_drawing_activate_model()
@@ -370,7 +382,7 @@ def remove_drawing(ifc: tool.Ifc, drawing_tool: tool.Drawing, drawing: ifcopensh
def update_drawing_name(
ifc: tool.Ifc, drawing_tool: tool.Drawing, drawing: ifcopenshell.entity_instance, name: str
ifc: type[tool.Ifc], drawing_tool: type[tool.Drawing], drawing: ifcopenshell.entity_instance, name: str
) -> None:
if drawing_tool.get_name(drawing) != name:
ifc.run("attribute.edit_attributes", product=drawing, attributes={"Name": name})
@@ -406,9 +418,9 @@ def update_drawing_name(
def add_annotation(
ifc: tool.Ifc,
collector: tool.Collector,
drawing_tool: tool.Drawing,
ifc: type[tool.Ifc],
collector: type[tool.Collector],
drawing_tool: type[tool.Drawing],
drawing: ifcopenshell.entity_instance,
object_type: str,
relating_type: ifcopenshell.entity_instance,
@@ -444,13 +456,16 @@ def add_annotation(
return obj
def build_schedule(drawing: tool.Drawing, schedule: ifcopenshell.entity_instance) -> None:
def build_schedule(drawing: type[tool.Drawing], schedule: ifcopenshell.entity_instance) -> None:
drawing.create_svg_schedule(schedule)
drawing.open_svg(drawing.get_path_with_ext(drawing.get_document_uri(schedule), "svg"))
def sync_references(
ifc: tool.Ifc, collector: tool.Collector, drawing_tool: tool.Drawing, drawing: ifcopenshell.entity_instance
ifc: type[tool.Ifc],
collector: type[tool.Collector],
drawing_tool: type[tool.Drawing],
drawing: ifcopenshell.entity_instance,
) -> None:
if not drawing_tool.has_annotation(drawing):
return
@@ -496,12 +511,15 @@ def sync_references(
drawing_tool.sync_object_representation(reference_obj)
def select_assigned_product(drawing: tool.Drawing, context: bpy.types.Context) -> None:
def select_assigned_product(drawing: type[tool.Drawing], context: bpy.types.Context) -> None:
drawing.select_assigned_product(context)
def activate_drawing_view(
ifc: tool.Ifc, blender: tool.Blender, drawing_tool: tool.Drawing, drawing: ifcopenshell.entity_instance
ifc: type[tool.Ifc],
blender: type[tool.Blender],
drawing_tool: type[tool.Drawing],
drawing: ifcopenshell.entity_instance,
) -> None:
camera = ifc.get_object(drawing)
if not camera:
+40 -36
View File
@@ -27,167 +27,171 @@ if TYPE_CHECKING:
from ifcopenshell.api.owner.add_actor import ACTOR_TYPE
def add_person(ifc: tool.Ifc) -> ifcopenshell.entity_instance:
def add_person(ifc: type[tool.Ifc]) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_person")
def remove_person(ifc: tool.Ifc, person: ifcopenshell.entity_instance) -> None:
def remove_person(ifc: type[tool.Ifc], person: ifcopenshell.entity_instance) -> None:
ifc.run("owner.remove_person", person=person)
def enable_editing_person(owner: tool.Owner, person: ifcopenshell.entity_instance) -> None:
def enable_editing_person(owner: type[tool.Owner], person: ifcopenshell.entity_instance) -> None:
owner.set_person(person)
owner.import_person_attributes()
def disable_editing_person(owner: tool.Owner) -> None:
def disable_editing_person(owner: type[tool.Owner]) -> None:
owner.clear_person()
def edit_person(ifc: tool.Ifc, owner: tool.Owner) -> None:
def edit_person(ifc: type[tool.Ifc], owner: type[tool.Owner]) -> None:
ifc.run("owner.edit_person", person=owner.get_person(), attributes=owner.export_person_attributes())
disable_editing_person(owner)
def add_person_attribute(owner: tool.Owner, name: str) -> None:
def add_person_attribute(owner: type[tool.Owner], name: tool.Owner.PersonAttributeType) -> None:
owner.add_person_attribute(name)
def remove_person_attribute(owner: tool.Owner, name: str, id: int) -> None:
def remove_person_attribute(owner: type[tool.Owner], name: tool.Owner.PersonAttributeType, id: int) -> None:
owner.remove_person_attribute(name, id)
def add_role(ifc: tool.Ifc, parent: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
def add_role(ifc: type[tool.Ifc], parent: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_role", assigned_object=parent)
def remove_role(ifc: tool.Ifc, role: ifcopenshell.entity_instance) -> None:
def remove_role(ifc: type[tool.Ifc], role: ifcopenshell.entity_instance) -> None:
ifc.run("owner.remove_role", role=role)
def enable_editing_role(owner: tool.Owner, role: ifcopenshell.entity_instance) -> None:
def enable_editing_role(owner: type[tool.Owner], role: ifcopenshell.entity_instance) -> None:
owner.set_role(role)
owner.import_role_attributes()
def disable_editing_role(owner: tool.Owner) -> None:
def disable_editing_role(owner: type[tool.Owner]) -> None:
owner.clear_role()
def edit_role(ifc: tool.Ifc, owner: tool.Owner) -> None:
def edit_role(ifc: type[tool.Ifc], owner: type[tool.Owner]) -> None:
ifc.run("owner.edit_role", role=owner.get_role(), attributes=owner.export_role_attributes())
owner.clear_role()
def add_address(
ifc: tool.Ifc, parent: ifcopenshell.entity_instance, ifc_class: ADDRESS_TYPE = "IfcPostalAddress"
ifc: type[tool.Ifc], parent: ifcopenshell.entity_instance, ifc_class: ADDRESS_TYPE = "IfcPostalAddress"
) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_address", assigned_object=parent, ifc_class=ifc_class)
def remove_address(ifc: tool.Ifc, address: ifcopenshell.entity_instance) -> None:
def remove_address(ifc: type[tool.Ifc], address: ifcopenshell.entity_instance) -> None:
ifc.run("owner.remove_address", address=address)
def enable_editing_address(owner: tool.Owner, address: ifcopenshell.entity_instance) -> None:
def enable_editing_address(owner: type[tool.Owner], address: ifcopenshell.entity_instance) -> None:
owner.set_address(address)
owner.import_address_attributes()
def disable_editing_address(owner: tool.Owner) -> None:
def disable_editing_address(owner: type[tool.Owner]) -> None:
owner.clear_address()
def edit_address(ifc: tool.Ifc, owner: tool.Owner) -> None:
def edit_address(ifc: type[tool.Ifc], owner: type[tool.Owner]) -> None:
address = owner.get_address()
ifc.run("owner.edit_address", address=address, attributes=owner.export_address_attributes())
owner.clear_address()
def add_address_attribute(owner: tool.Owner, name: str) -> None:
def add_address_attribute(owner: type[tool.Owner], name: tool.Owner.AddressAttributeType) -> None:
owner.add_address_attribute(name)
def remove_address_attribute(owner: tool.Owner, name: str, id: int) -> None:
def remove_address_attribute(owner: type[tool.Owner], name: tool.Owner.AddressAttributeType, id: int) -> None:
owner.remove_address_attribute(name, id)
def add_organisation(ifc: tool.Ifc) -> ifcopenshell.entity_instance:
def add_organisation(ifc: type[tool.Ifc]) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_organisation")
def remove_organisation(ifc: tool.Ifc, organisation: ifcopenshell.entity_instance) -> None:
def remove_organisation(ifc: type[tool.Ifc], organisation: ifcopenshell.entity_instance) -> None:
ifc.run("owner.remove_organisation", organisation=organisation)
def enable_editing_organisation(owner: tool.Owner, organisation: ifcopenshell.entity_instance) -> None:
def enable_editing_organisation(owner: type[tool.Owner], organisation: ifcopenshell.entity_instance) -> None:
owner.set_organisation(organisation)
owner.import_organisation_attributes()
def disable_editing_organisation(owner: tool.Owner) -> None:
def disable_editing_organisation(owner: type[tool.Owner]) -> None:
owner.clear_organisation()
def edit_organisation(ifc: tool.Ifc, owner: tool.Owner) -> None:
def edit_organisation(ifc: type[tool.Ifc], owner: type[tool.Owner]) -> None:
organisation = owner.get_organisation()
ifc.run("owner.edit_organisation", organisation=organisation, attributes=owner.export_organisation_attributes())
owner.clear_organisation()
def add_person_and_organisation(
ifc: tool.Ifc, person: ifcopenshell.entity_instance, organisation: ifcopenshell.entity_instance
ifc: type[tool.Ifc], person: ifcopenshell.entity_instance, organisation: ifcopenshell.entity_instance
) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_person_and_organisation", person=person, organisation=organisation)
def remove_person_and_organisation(
ifc: tool.Ifc, owner: tool.Owner, person_and_organisation: ifcopenshell.entity_instance
ifc: type[tool.Ifc], owner: type[tool.Owner], person_and_organisation: ifcopenshell.entity_instance
) -> None:
if owner.get_user() == person_and_organisation:
owner.clear_user()
ifc.run("owner.remove_person_and_organisation", person_and_organisation=person_and_organisation)
def set_user(owner: tool.Owner, user: ifcopenshell.entity_instance) -> None:
def set_user(owner: type[tool.Owner], user: ifcopenshell.entity_instance) -> None:
owner.set_user(user)
def get_user(owner: tool.Owner) -> Union[ifcopenshell.entity_instance, None]:
def get_user(owner: type[tool.Owner]) -> Union[ifcopenshell.entity_instance, None]:
return owner.get_user()
def clear_user(owner: tool.Owner) -> None:
def clear_user(owner: type[tool.Owner]) -> None:
owner.clear_user()
def add_actor(
ifc: tool.Ifc, ifc_class: ACTOR_TYPE, actor: ifcopenshell.entity_instance
ifc: type[tool.Ifc], ifc_class: ACTOR_TYPE, actor: ifcopenshell.entity_instance
) -> ifcopenshell.entity_instance:
return ifc.run("owner.add_actor", ifc_class=ifc_class, actor=actor)
def remove_actor(ifc: tool.Ifc, actor: ifcopenshell.entity_instance) -> None:
def remove_actor(ifc: type[tool.Ifc], actor: ifcopenshell.entity_instance) -> None:
ifc.run("owner.remove_actor", actor=actor)
def enable_editing_actor(owner: tool.Owner, actor: ifcopenshell.entity_instance) -> None:
def enable_editing_actor(owner: type[tool.Owner], actor: ifcopenshell.entity_instance) -> None:
owner.set_actor(actor)
owner.import_actor_attributes(actor)
def disable_editing_actor(owner: tool.Owner) -> None:
def disable_editing_actor(owner: type[tool.Owner]) -> None:
owner.clear_actor()
def edit_actor(ifc: tool.Ifc, owner: tool.Owner) -> None:
def edit_actor(ifc: type[tool.Ifc], owner: type[tool.Owner]) -> None:
ifc.run("owner.edit_actor", actor=owner.get_actor(), attributes=owner.export_actor_attributes())
disable_editing_actor(owner)
def assign_actor(ifc: tool.Ifc, actor: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance) -> None:
def assign_actor(
ifc: type[tool.Ifc], actor: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance
) -> None:
ifc.run("owner.assign_actor", relating_actor=actor, related_object=element)
def unassign_actor(ifc: tool.Ifc, actor: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance) -> None:
def unassign_actor(
ifc: type[tool.Ifc], actor: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance
) -> None:
ifc.run("owner.unassign_actor", relating_actor=actor, related_object=element)
+4
View File
@@ -74,6 +74,10 @@ class Aggregate:
def get_container(cls, element): pass
def get_relating_object(cls, related_element): pass
@interface
class Alignment:
def build_alignment(cls): pass
def add_survey_point(cls,x,y): pass
@interface
class Bcf:
+1
View File
@@ -17,6 +17,7 @@
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
from bonsai.tool.aggregate import Aggregate
from bonsai.tool.alignment import Alignment
from bonsai.tool.bcf import Bcf
from bonsai.tool.blender import Blender
from bonsai.tool.boundary import Boundary
+3
View File
@@ -164,6 +164,9 @@ class Aggregate(bonsai.core.tool.Aggregate):
if obj.original not in parts_objs:
if obj == props.editing_aggregate:
continue
# Skips adding the object to not_editing_objects if it already exists in the list
if any(obj == existing_obj.obj.original for existing_obj in props.not_editing_objects):
continue
not_editing_obj = props.not_editing_objects.add()
not_editing_obj.obj = obj.original
not_editing_obj.previous_display_type = obj.original.display_type
+120
View File
@@ -0,0 +1,120 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2022 Dion Moult <dion@thinkmoult.com>
#
# 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/>.
# ############################################################################ #
# Hey there! Welcome to the Bonsai code. Please feel free to reach
# out if you have any questions or need further guidance. Happy hacking!
# ############################################################################ #
# Every module has a tool file which implements all the functions that the core
# needs. Whereas the core is simply high level code, the tool file has the
# concrete implementations, dealing with exactly how things interact with
# Blender's property systems, IFC's data structures, the filesystem, geometry
# processing, and more.
import ifcopenshell.settings
import bpy
import bonsai.core.tool
import bonsai.tool as tool
import ifcopenshell.api
import ifcopenshell.api.alignment
import ifcopenshell
import ifcopenshell.api.cogo
# There is always one class in each tool file, which implements the interface
# defined by `core/tool.py`.
class Alignment(bonsai.core.tool.Alignment):
@classmethod
def add_survey_point(cls,x,y):
model = tool.Ifc.get()
point = model.createIfcCartesianPoint((x,y))
annotation = ifcopenshell.api.cogo.add_survey_point(model,point)
m = tool.Loader.create_point_cloud_mesh(annotation.Representation.Representations[0])
tool.Ifc.link(annotation.Representation.Representations[0],m)
# create a new Blender object
annotation_obj = bpy.data.objects.new(tool.Loader.get_name(annotation), m)
# link the blender object to with the IFC element
tool.Geometry.link(annotation, annotation_obj)
# assign the object to the blender collections
tool.Collector.assign(annotation_obj, should_clean_users_collection=False)
@classmethod
def build(cls):
coordinates = [(0.0,0.0),(100.0,0.0),(1000.,200.)]
radii = [(100.)]
vpoints = [(0.0,0.0),(100.0,0.0),(200.0,150.0)]
lengths = [(50.)]
model = tool.Ifc.get()
# create an IfcAlignment with Name="Dummy"
alignment = ifcopenshell.api.alignment.create_alignment_by_pi_method(model,"Dummy",coordinates,radii,vpoints,lengths)
ifcopenshell.api.alignment.create_geometric_representation(model, alignment)
ifcopenshell.api.alignment.add_stationing_to_alignment(model, alignment=alignment, start_station=0.0)
# IFC 4.1.5.1 alignments cannot be contained in spatial structures, but can be referenced into them
sites = model.by_type("IfcSite")
for site in sites:
ifcopenshell.api.spatial.reference_structure(model, products=[alignment], relating_structure=site)
# process the generated IfcReferent for the alignment
for rel in alignment.IsNestedBy:
for referent in rel.RelatedObjects:
if referent.is_a("IfcReferent"):
referent_obj = bpy.data.objects.new(tool.Loader.get_name(referent), None)
tool.Geometry.link(referent, referent_obj)
tool.Collector.assign(referent_obj, should_clean_users_collection=False)
# an alignment can be an aggregation of multiple child alignments (ie. multiple verticals for a single horizontal)
# get all the alignment curves
curves = []
for rel in alignment.IsDecomposedBy:
for agg in rel.RelatedObjects:
if agg.is_a("IfcAlignment"):
curves.append(ifcopenshell.api.alignment.get_curve(agg)) # 3D curve
# if there aren't any curves from aggregation, then there is only a single vertical or no vertical
if len(curves) == 0:
curves.append(ifcopenshell.api.alignment.get_curve(alignment))
settings = ifcopenshell.geom.settings()
for curve in curves:
shape = ifcopenshell.geom.create_shape(settings, curve)
# create a new Blender mesh
mesh_name = tool.Loader.get_mesh_name_from_shape(shape)
mesh = bpy.data.meshes.new(mesh_name)
m = tool.Loader.convert_geometry_to_mesh(shape, mesh)
# create a new Blender object
alignment_obj = bpy.data.objects.new(tool.Loader.get_name(alignment), m)
# link the blender object to with the alignment element
tool.Geometry.link(alignment, alignment_obj)
# assign the object to the blender collections
tool.Collector.assign(alignment_obj, should_clean_users_collection=False)
+8 -3
View File
@@ -71,7 +71,7 @@ class Blender(bonsai.core.tool.Blender):
OBJECT_TYPES_THAT_SUPPORT_EDIT_GPENCIL_MODE = ("GPENCIL",)
TYPE_MANAGER_ICON = "LIGHTPROBE_VOLUME"
BLENDER_ENUM_ITEM = Union[tuple[str, str, str], tuple[str, str, str, str], tuple[str, str, str, str, str]]
BLENDER_ENUM_ITEM = Union[tuple[str, str, str], tuple[str, str, str, int], tuple[str, str, str, str, int]]
"""
Options:
@@ -81,13 +81,17 @@ class Blender(bonsai.core.tool.Blender):
- (identifier, name, description, icon, number)
"""
BLENDER_ENUM_ITEMS = list[BLENDER_ENUM_ITEM]
@classmethod
def activate_camera(cls, obj: bpy.types.Object) -> None:
area = cls.get_view3d_area()
is_local_view = area.spaces[0].local_view is not None
assert area
assert isinstance((space := area.spaces[0]), bpy.types.SpaceView3D)
is_local_view = space.local_view is not None
assert bpy.context.screen and bpy.context.scene
if is_local_view:
# Turn off local view before activating drawing, and then turn it on again.
for a in bpy.context.screen.areas:
@@ -100,7 +104,8 @@ class Blender(bonsai.core.tool.Blender):
else:
bpy.context.scene.camera = obj
area.spaces[0].region_3d.view_perspective = "CAMERA"
assert space.region_3d
space.region_3d.view_perspective = "CAMERA"
@classmethod
def get_area_props(cls, context: bpy.types.Context) -> bpy.types.PropertyGroup:
+22 -9
View File
@@ -16,22 +16,33 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import bpy
import bonsai.bim.helper
import bonsai.tool as tool
import bonsai.core.tool
import ifcopenshell
from typing import Any, Union
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING:
from bonsai.bim.prop import Attribute
from bonsai.bim.module.context.prop import BIMContextProperties
class Context(bonsai.core.tool.Context):
@classmethod
def get_context_props(cls) -> BIMContextProperties:
assert bpy.context.scene
return bpy.context.scene.BIMContextProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def set_context(cls, context: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMContextProperties.active_context_id = context.id()
props = cls.get_context_props()
props.active_context_id = context.id()
@classmethod
def import_attributes(cls) -> None:
props = bpy.context.scene.BIMContextProperties
props = cls.get_context_props()
props.context_attributes.clear()
context = cls.get_context()
@@ -52,20 +63,22 @@ class Context(bonsai.core.tool.Context):
@classmethod
def clear_context(cls) -> None:
bpy.context.scene.BIMContextProperties.active_context_id = 0
props = cls.get_context_props()
props.active_context_id = 0
@classmethod
def get_context(cls) -> ifcopenshell.entity_instance:
return tool.Ifc.get().by_id(bpy.context.scene.BIMContextProperties.active_context_id)
props = cls.get_context_props()
return tool.Ifc.get().by_id(props.active_context_id)
@classmethod
def export_attributes(cls) -> dict[str, Any]:
def callback(attributes, blender_attribute) -> bool:
props = cls.get_context_props()
def callback(attributes: dict[str, Any], blender_attribute: Attribute) -> bool:
if blender_attribute.name == "Precision":
attributes["Precision"] = float(blender_attribute.get_value())
return True
return False
return bonsai.bim.helper.export_attributes(
bpy.context.scene.BIMContextProperties.context_attributes, callback=callback
)
return bonsai.bim.helper.export_attributes(props.context_attributes, callback=callback)
+104 -50
View File
@@ -51,7 +51,7 @@ from shapely.ops import unary_union
from lxml import etree
from mathutils import Vector, Matrix
from fractions import Fraction
from typing import Optional, Union, Iterable, Any, Literal, Sequence, TYPE_CHECKING, NamedTuple
from typing import Optional, Union, Iterable, Any, Literal, Sequence, TYPE_CHECKING, NamedTuple, get_args
from pathlib import Path
if TYPE_CHECKING:
@@ -61,6 +61,7 @@ if TYPE_CHECKING:
BIMAnnotationProperties,
BIMTextProperties,
BIMCameraProperties,
BIMAssignedProductProperties,
)
from bonsai.bim.module.drawing.prop import Drawing as DrawingProperties
@@ -68,6 +69,9 @@ if TYPE_CHECKING:
class Drawing(bonsai.core.tool.Drawing):
ANNOTATION_DATA_TYPE = Literal["empty", "curve", "mesh"]
DOCUMENT_TYPE = Literal["SCHEDULE", "REFERENCE"]
LocationHintLiteral = Literal["PERSPECTIVE", "ORTHOGRAPHIC", "NORTH", "SOUTH", "EAST", "WEST"]
LOCATION_HINT_LITERALS = ("PERSPECTIVE", "ORTHOGRAPHIC", "NORTH", "SOUTH", "EAST", "WEST")
LocationHintType = Union[LocationHintLiteral, str]
# ObjectType: annotation_name, description, icon, data_type
# fmt: off
@@ -102,15 +106,17 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def get_document_props(cls) -> DocProperties:
return bpy.context.scene.DocProperties
assert (scene := bpy.context.scene)
return scene.DocProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def get_annotation_props(cls) -> BIMAnnotationProperties:
return bpy.context.scene.BIMAnnotationProperties
assert (scene := bpy.context.scene)
return scene.BIMAnnotationProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def get_text_props(cls, obj: bpy.types.Object) -> BIMTextProperties:
return obj.BIMTextProperties
return obj.BIMTextProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def get_camera_props(cls, camera: Union[bpy.types.Object, bpy.types.Camera]) -> BIMCameraProperties:
@@ -121,7 +127,11 @@ class Drawing(bonsai.core.tool.Drawing):
data = camera
else:
assert isinstance(data := camera.data, bpy.types.Camera)
return data.BIMCameraProperties
return data.BIMCameraProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def get_object_assigned_product_props(cls, obj: bpy.types.Object) -> BIMAssignedProductProperties:
return obj.BIMAssignedProductProperties # pyright: ignore[reportAttributeAccessIssue]
@classmethod
def canonicalise_class_name(cls, name: str) -> str:
@@ -296,11 +306,14 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def create_camera(
cls, name: str, matrix: Matrix, location_hint: Literal["PERSPECTIVE", "ORTHOGRAPHIC"]
cls,
name: str,
matrix: Matrix,
location_hint: Union[LocationHintLiteral, int],
target_view: ifcopenshell.util.representation.TARGET_VIEW,
) -> bpy.types.Object:
camera = bpy.data.objects.new(name, (camera_data := bpy.data.cameras.new(name)))
props = cls.get_camera_props(camera_data)
camera.location = (0, 0, 1.5) # The view shall be 1.5m above the origin
camera_data.show_limits = True
if location_hint == "PERSPECTIVE":
props.camera_type = "PERSP"
@@ -308,7 +321,11 @@ class Drawing(bonsai.core.tool.Drawing):
props.camera_type = "ORTHO"
camera_data.ortho_scale = 50 # The default of 6m is too small
camera_data.clip_start = 0.002 # 2mm is close to zero but allows any GPU-drawn lines to be visible.
camera_data.clip_end = 10 # A slightly more reasonable default
if target_view == "MODEL_VIEW":
assert (space := tool.Blender.get_view3d_space())
camera_data.clip_end = max(space.clip_end, 10)
else:
camera_data.clip_end = 10 # A slightly more reasonable default
if bpy.context.scene.unit_settings.system == "IMPERIAL":
props.diagram_scale = '1/8"=1\'-0"|1/96'
else:
@@ -396,7 +413,8 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def disable_editing_assigned_product(cls, obj: bpy.types.Object) -> None:
obj.BIMAssignedProductProperties.is_editing_product = False
props = cls.get_object_assigned_product_props(obj)
props.is_editing_product = False
@classmethod
def enable_editing(cls, obj: bpy.types.Object) -> None:
@@ -437,7 +455,8 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def enable_editing_assigned_product(cls, obj: bpy.types.Object) -> None:
obj.BIMAssignedProductProperties.is_editing_product = True
props = cls.get_object_assigned_product_props(obj)
props.is_editing_product = True
@classmethod
def ensure_unique_drawing_name(cls, name: str) -> str:
@@ -588,48 +607,82 @@ class Drawing(bonsai.core.tool.Drawing):
def get_name(cls, element: ifcopenshell.entity_instance) -> Union[str, None]:
return element.Name
@classmethod
def update_camera_matrix(
cls,
matrix: Matrix,
*,
camera_dir: Vector,
up: Vector,
) -> None:
# Camera dir is actually Z-.
camera_dir = -camera_dir
right = up.cross(camera_dir)
assert isinstance(right, Vector)
matrix.col[0][:3] = right
matrix.col[1][:3] = up
matrix.col[2][:3] = camera_dir
@classmethod
def generate_drawing_matrix(
cls, target_view: ifcopenshell.util.representation.TARGET_VIEW, location_hint: str
cls,
target_view: ifcopenshell.util.representation.TARGET_VIEW,
location_hint: Union[LocationHintLiteral, int],
) -> Matrix:
assert bpy.context.scene
m = Matrix()
x, y, z = (0, 0, 0) if location_hint == 0 else bpy.context.scene.cursor.matrix.translation
if target_view == "PLAN_VIEW":
X, Y, Z = m.to_3x3()
if isinstance(location_hint, int):
if target_view == "REFLECTED_PLAN_VIEW":
# Flip Z axis.
m.col[2] *= -1
if location_hint:
z = tool.Ifc.get_object(tool.Ifc.get().by_id(location_hint)).matrix_world.translation.z
return mathutils.Matrix(((1, 0, 0, x), (0, 1, 0, y), (0, 0, 1, z + 1.6), (0, 0, 0, 1)))
elif target_view == "REFLECTED_PLAN_VIEW":
if location_hint:
z = tool.Ifc.get_object(tool.Ifc.get().by_id(location_hint)).matrix_world.translation.z
m = mathutils.Matrix()
m[2][2] = -1
m.translation = (x, y, z + 1.6)
return m
return mathutils.Matrix(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, 1)))
storey = tool.Ifc.get_object(tool.Ifc.get().by_id(location_hint))
assert isinstance(storey, bpy.types.Object)
z = storey.matrix_world.translation.z
if target_view == "PLAN_VIEW":
# Keep default camera direction - Z-.
m.translation = (x, y, z + 1.6)
return m
elif target_view == "REFLECTED_PLAN_VIEW":
m.translation = (x, y, z + 1.6)
else:
assert False, target_view
return m
elif target_view == "ELEVATION_VIEW":
m.translation = (x, y, z)
if location_hint == "NORTH":
return mathutils.Matrix(((-1, 0, 0, x), (0, 0, 1, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=-Y, up=Z)
elif location_hint == "SOUTH":
return mathutils.Matrix(((1, 0, 0, x), (0, 0, -1, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=Y, up=Z)
elif location_hint == "EAST":
return mathutils.Matrix(((0, 0, 1, x), (1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=-X, up=Z)
elif location_hint == "WEST":
return mathutils.Matrix(((0, 0, -1, x), (-1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=X, up=Z)
return m
elif target_view == "SECTION_VIEW":
m.translation = (x, y, z)
X, Y, Z = m.to_3x3()
if location_hint == "NORTH":
return mathutils.Matrix(((1, 0, 0, x), (0, 0, -1, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=Y, up=Z)
elif location_hint == "SOUTH":
return mathutils.Matrix(((-1, 0, 0, x), (0, 0, 1, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=-Y, up=Z)
elif location_hint == "EAST":
return mathutils.Matrix(((0, 0, -1, x), (-1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=X, up=Z)
elif location_hint == "WEST":
return mathutils.Matrix(((0, 0, 1, x), (1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
cls.update_camera_matrix(m, camera_dir=-X, up=Z)
return m
elif target_view == "MODEL_VIEW":
return mathutils.Matrix(((1, 0, 0, x), (0, 1, 0, y), (0, 0, 1, z), (0, 0, 0, 1)))
return mathutils.Matrix()
assert (space := tool.Blender.get_view3d_space())
assert (r3d := space.region_3d)
return r3d.view_matrix.inverted()
return m
@classmethod
def generate_sheet_identification(cls) -> str:
number = len([d for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == "SHEET"])
number += 1
return "A" + str(number).zfill(2)
@classmethod
@@ -742,7 +795,7 @@ class Drawing(bonsai.core.tool.Drawing):
ifc_importer.load_existing_meshes()
ifc_importer.material_creator.load_existing_materials()
ifc_importer.create_generic_elements(elements)
ifc_importer.setup_arrays(elements)
ifc_importer.setup_arrays(annotations_to_import=elements)
for obj in ifc_importer.added_data.values():
tool.Collector.assign(obj)
@@ -1002,11 +1055,14 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def import_assigned_product(cls, obj: bpy.types.Object) -> None:
element = tool.Ifc.get_entity(obj)
assert element
product = cls.get_assigned_product(element)
props = cls.get_object_assigned_product_props(obj)
if product:
obj.BIMAssignedProductProperties.relating_product = tool.Ifc.get_object(product)
assert isinstance(product_obj := tool.Ifc.get_object(product), bpy.types.Object)
props.relating_product = product_obj
else:
obj.BIMAssignedProductProperties.relating_product = None
props.relating_product = None
@classmethod
def open_with_user_command(cls, user_command: str, path: str) -> None:
@@ -1174,13 +1230,17 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def generate_drawing_name(
cls, target_view: ifcopenshell.util.representation.TARGET_VIEW, location_hint: str
cls,
target_view: ifcopenshell.util.representation.TARGET_VIEW,
location_hint: Union[LocationHintLiteral, int],
) -> str:
if target_view in ("PLAN_VIEW", "REFLECTED_PLAN_VIEW") and location_hint:
location = tool.Ifc.get().by_id(location_hint)
if target_view == "REFLECTED_PLAN_VIEW":
target_view = "RCP_VIEW"
return (location.Name or "UNNAMED").upper() + " " + target_view.split("_")[0]
if isinstance(location_hint, int):
if location_hint:
location = tool.Ifc.get().by_id(location_hint)
target_view_ = target_view
if target_view == "REFLECTED_PLAN_VIEW":
target_view_ = "RCP_VIEW"
return (location.Name or "UNNAMED").upper() + " " + target_view_.split("_")[0]
elif target_view in ("SECTION_VIEW", "ELEVATION_VIEW") and location_hint:
return location_hint + " " + target_view.split("_")[0]
elif target_view == "MODEL_VIEW" and location_hint:
@@ -1799,15 +1859,9 @@ class Drawing(bonsai.core.tool.Drawing):
@classmethod
def get_drawing_metadata(cls, drawing: ifcopenshell.entity_instance) -> list[str]:
# fmt: off
return [
v.strip()
for v in (
ifcopenshell.util.element.get_psets(drawing)["EPset_Drawing"].get("Metadata", "") or ""
).split(",")
if v
]
# fmt: on
pset_data = ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing")
metadata_str = pset_data.get("Metadata", "") or ""
return [v_ for v in metadata_str.split(",") if (v_ := v.strip())]
@classmethod
def get_annotation_z_index(cls, drawing: ifcopenshell.entity_instance) -> float:
+1 -1
View File
@@ -1030,7 +1030,7 @@ class Geometry(bonsai.core.tool.Geometry):
return item.is_a("IfcSweptAreaSolid") or item.is_a("IfcHalfSpaceSolid")
@classmethod
def is_profile_based(cls, data: bpy.types.Mesh) -> bool:
def is_profile_based(cls, data: TYPES_WITH_MESH_PROPERTIES) -> bool:
props = tool.Geometry.get_mesh_props(data)
return props.subshape_type == "PROFILE"
+15 -1
View File
@@ -587,13 +587,15 @@ class Model(bonsai.core.tool.Model):
def load_openings(cls, openings: list[ifcopenshell.entity_instance]) -> Iterable[bpy.types.Object]:
if not openings:
return []
elements = set(openings)
ifc_import_settings = import_ifc.IfcImportSettings.factory()
ifc_importer = import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = tool.Ifc.get()
ifc_importer.calculate_unit_scale()
ifc_importer.process_context_filter()
ifc_importer.material_creator.load_existing_materials()
ifc_importer.create_generic_elements(set(openings))
ifc_importer.create_generic_elements(elements)
ifc_importer.setup_arrays(openings_to_import=elements)
for opening_obj in ifc_importer.added_data.values():
tool.Collector.assign(opening_obj, should_clean_users_collection=False)
return ifc_importer.added_data.values()
@@ -1060,6 +1062,7 @@ class Model(bonsai.core.tool.Model):
if not refresh and element.id() in AuthoringData.type_thumbnails:
return # Already processed
assert isinstance(obj, bpy.types.Object)
obj.asset_generate_preview()
while not obj.preview:
pass
@@ -1144,6 +1147,17 @@ class Model(bonsai.core.tool.Model):
AuthoringData.type_thumbnails[element.id()] = obj.preview.icon_id
@classmethod
def mark_thumbnail_for_update(cls, element: ifcopenshell.entity_instance) -> None:
"""Mark the thumbnail for the provided element as outdated.
Allows postponing the thumbnail update until it is actually needed by the user.
"""
element_id = element.id()
if element_id not in AuthoringData.type_thumbnails:
return
del AuthoringData.type_thumbnails[element_id]
@classmethod
def get_selected_ifc_objects(cls) -> list[bpy.types.Object]:
return [obj for obj in tool.Blender.get_selected_objects() if tool.Ifc.get_entity(obj)]
+91 -46
View File
@@ -16,23 +16,35 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import bpy
import bonsai.core.tool
import bonsai.tool as tool
import bonsai.bim.helper
import ifcopenshell
from typing import Union, Any
from typing import Union, Any, TYPE_CHECKING, Literal
from typing_extensions import assert_never
if TYPE_CHECKING:
from bonsai.bim.module.owner.prop import BIMOwnerProperties
class Owner(bonsai.core.tool.Owner):
@classmethod
def get_owner_props(cls) -> BIMOwnerProperties:
return bpy.context.scene.BIMOwnerProperties
@classmethod
def set_user(cls, user: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_user_id = user.id()
props = cls.get_owner_props()
props.active_user_id = user.id()
@classmethod
def get_user(cls) -> Union[ifcopenshell.entity_instance, None]:
if bpy.context.scene.BIMOwnerProperties.active_user_id:
return tool.Ifc.get().by_id(bpy.context.scene.BIMOwnerProperties.active_user_id)
props = cls.get_owner_props()
active_user_id = props.active_user_id
if active_user_id:
return tool.Ifc.get().by_id(active_user_id)
elif tool.Ifc.get_schema() == "IFC2X3":
users = tool.Ifc.get().by_type("IfcPersonAndOrganization")
if users:
@@ -40,15 +52,17 @@ class Owner(bonsai.core.tool.Owner):
@classmethod
def clear_user(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_user_id = 0
props = cls.get_owner_props()
props.active_user_id = 0
@classmethod
def set_address(cls, address: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_address_id = address.id()
props = cls.get_owner_props()
props.active_address_id = address.id()
@classmethod
def import_address_attributes(cls) -> None:
props = bpy.context.scene.BIMOwnerProperties
props = props = cls.get_owner_props()
props.address_attributes.clear()
props.address_lines.clear()
props.telephone_numbers.clear()
@@ -58,7 +72,7 @@ class Owner(bonsai.core.tool.Owner):
address = cls.get_address()
def callback(name, prop, data):
def callback(name: str, prop, data: dict[str, Any]) -> None:
if name == "AddressLines":
for line in data[name] or []:
props.address_lines.add().name = line
@@ -79,15 +93,17 @@ class Owner(bonsai.core.tool.Owner):
@classmethod
def clear_address(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_address_id = 0
props = cls.get_owner_props()
props.active_address_id = 0
@classmethod
def get_address(cls) -> ifcopenshell.entity_instance:
return tool.Ifc().get().by_id(bpy.context.scene.BIMOwnerProperties.active_address_id)
props = cls.get_owner_props()
return tool.Ifc().get().by_id(props.active_address_id)
@classmethod
def export_address_attributes(cls) -> dict[str, Any]:
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
attributes = bonsai.bim.helper.export_attributes(props.address_attributes)
if cls.get_address().is_a("IfcPostalAddress"):
attributes["AddressLines"] = [l.name for l in props.address_lines] or None
@@ -98,9 +114,13 @@ class Owner(bonsai.core.tool.Owner):
attributes["MessagingIDs"] = [l.name for l in props.messaging_ids] or None
return attributes
AddressAttributeType = Literal[
"AddressLines", "TelephoneNumbers", "FacsimileNumbers", "ElectronicMailAddresses", "MessagingIDs"
]
@classmethod
def add_address_attribute(cls, name: str) -> None:
props = bpy.context.scene.BIMOwnerProperties
def add_address_attribute(cls, name: AddressAttributeType) -> None:
props = cls.get_owner_props()
if name == "AddressLines":
props.address_lines.add()
elif name == "TelephoneNumbers":
@@ -111,10 +131,12 @@ class Owner(bonsai.core.tool.Owner):
props.electronic_mail_addresses.add()
elif name == "MessagingIDs":
props.messaging_ids.add()
else:
assert_never(name)
@classmethod
def remove_address_attribute(cls, name: str, id: int) -> None:
props = bpy.context.scene.BIMOwnerProperties
def remove_address_attribute(cls, name: AddressAttributeType, id: int) -> None:
props = cls.get_owner_props()
if name == "AddressLines":
props.address_lines.remove(id)
elif name == "TelephoneNumbers":
@@ -125,47 +147,53 @@ class Owner(bonsai.core.tool.Owner):
props.electronic_mail_addresses.remove(id)
elif name == "MessagingIDs":
props.messaging_ids.remove(id)
else:
assert_never(name)
@classmethod
def set_organisation(cls, organisation: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_organisation_id = organisation.id()
props = cls.get_owner_props()
props.active_organisation_id = organisation.id()
@classmethod
def import_organisation_attributes(cls) -> None:
organisation = tool.Ifc.get().by_id(bpy.context.scene.BIMOwnerProperties.active_organisation_id)
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
organisation = tool.Ifc.get().by_id(props.active_organisation_id)
props.organisation_attributes.clear()
bonsai.bim.helper.import_attributes("IfcOrganization", props.organisation_attributes, organisation.get_info())
@classmethod
def clear_organisation(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_organisation_id = 0
props = cls.get_owner_props()
props.active_organisation_id = 0
@classmethod
def export_organisation_attributes(cls) -> dict[str, Any]:
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
attributes = bonsai.bim.helper.export_attributes(props.organisation_attributes)
return attributes
@classmethod
def get_organisation(cls) -> ifcopenshell.entity_instance:
return tool.Ifc().get().by_id(bpy.context.scene.BIMOwnerProperties.active_organisation_id)
props = cls.get_owner_props()
return tool.Ifc().get().by_id(props.active_organisation_id)
@classmethod
def set_person(cls, person: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_person_id = person.id()
props = cls.get_owner_props()
props.active_person_id = person.id()
@classmethod
def import_person_attributes(cls) -> None:
person = tool.Ifc.get().by_id(bpy.context.scene.BIMOwnerProperties.active_person_id)
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
person = tool.Ifc.get().by_id(props.active_person_id)
props.person_attributes.clear()
props.middle_names.clear()
props.prefix_titles.clear()
props.suffix_titles.clear()
def callback(name, prop, data):
def callback(name: str, prop, data: dict[str, Any]) -> None:
if name == "MiddleNames":
for name in data["MiddleNames"] or []:
props.middle_names.add().name = name or ""
@@ -180,11 +208,12 @@ class Owner(bonsai.core.tool.Owner):
@classmethod
def clear_person(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_person_id = 0
props = cls.get_owner_props()
props.active_person_id = 0
@classmethod
def export_person_attributes(cls) -> dict[str, Any]:
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
attributes = bonsai.bim.helper.export_attributes(props.person_attributes)
attributes["MiddleNames"] = [v.name for v in props.middle_names] if props.middle_names else None
attributes["PrefixTitles"] = [v.name for v in props.prefix_titles] if props.prefix_titles else None
@@ -193,69 +222,85 @@ class Owner(bonsai.core.tool.Owner):
@classmethod
def get_person(cls) -> ifcopenshell.entity_instance:
return tool.Ifc().get().by_id(bpy.context.scene.BIMOwnerProperties.active_person_id)
props = cls.get_owner_props()
return tool.Ifc().get().by_id(props.active_person_id)
PersonAttributeType = Literal["MiddleNames", "PrefixTitles", "SuffixTitles"]
@classmethod
def add_person_attribute(cls, name: str) -> None:
def add_person_attribute(cls, name: PersonAttributeType) -> None:
props = cls.get_owner_props()
if name == "MiddleNames":
bpy.context.scene.BIMOwnerProperties.middle_names.add()
props.middle_names.add()
elif name == "PrefixTitles":
bpy.context.scene.BIMOwnerProperties.prefix_titles.add()
props.prefix_titles.add()
elif name == "SuffixTitles":
bpy.context.scene.BIMOwnerProperties.suffix_titles.add()
props.suffix_titles.add()
else:
assert_never(name)
@classmethod
def remove_person_attribute(cls, name: str, id: int) -> None:
def remove_person_attribute(cls, name: PersonAttributeType, id: int) -> None:
props = cls.get_owner_props()
if name == "MiddleNames":
bpy.context.scene.BIMOwnerProperties.middle_names.remove(id)
props.middle_names.remove(id)
elif name == "PrefixTitles":
bpy.context.scene.BIMOwnerProperties.prefix_titles.remove(id)
props.prefix_titles.remove(id)
elif name == "SuffixTitles":
bpy.context.scene.BIMOwnerProperties.suffix_titles.remove(id)
props.suffix_titles.remove(id)
else:
assert_never(name)
@classmethod
def set_role(cls, role: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_role_id = role.id()
props = cls.get_owner_props()
props.active_role_id = role.id()
@classmethod
def import_role_attributes(cls) -> None:
role = cls.get_role()
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
props.role_attributes.clear()
bonsai.bim.helper.import_attributes("IfcActorRole", props.role_attributes, role.get_info())
@classmethod
def clear_role(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_role_id = 0
props = cls.get_owner_props()
props.active_role_id = 0
@classmethod
def get_role(cls) -> ifcopenshell.entity_instance:
return tool.Ifc().get().by_id(bpy.context.scene.BIMOwnerProperties.active_role_id)
props = cls.get_owner_props()
return tool.Ifc().get().by_id(props.active_role_id)
@classmethod
def export_role_attributes(cls) -> dict[str, Any]:
return bonsai.bim.helper.export_attributes(bpy.context.scene.BIMOwnerProperties.role_attributes)
props = cls.get_owner_props()
return bonsai.bim.helper.export_attributes(props.role_attributes)
@classmethod
def set_actor(cls, actor: ifcopenshell.entity_instance) -> None:
bpy.context.scene.BIMOwnerProperties.active_actor_id = actor.id()
props = cls.get_owner_props()
props.active_actor_id = actor.id()
@classmethod
def import_actor_attributes(cls, actor: ifcopenshell.entity_instance) -> None:
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
props.actor_attributes.clear()
bonsai.bim.helper.import_attributes2(actor, props.actor_attributes)
@classmethod
def clear_actor(cls) -> None:
bpy.context.scene.BIMOwnerProperties.active_actor_id = 0
props = cls.get_owner_props()
props.active_actor_id = 0
@classmethod
def export_actor_attributes(cls) -> dict[str, Any]:
props = bpy.context.scene.BIMOwnerProperties
props = cls.get_owner_props()
attributes = bonsai.bim.helper.export_attributes(props.actor_attributes)
return attributes
@classmethod
def get_actor(cls) -> ifcopenshell.entity_instance:
return tool.Ifc().get().by_id(bpy.context.scene.BIMOwnerProperties.active_actor_id)
props = cls.get_owner_props()
return tool.Ifc().get().by_id(props.active_actor_id)
+1 -1
View File
@@ -339,7 +339,7 @@ class Sequence(bonsai.core.tool.Sequence):
@classmethod
def get_task_attribute_value(cls, attribute_name: str) -> Any:
props = cls.get_work_schedule_props()
return props.task_attributes.get(attribute_name).get_value()
return props.task_attributes[attribute_name].get_value()
@classmethod
def get_active_task(cls) -> ifcopenshell.entity_instance:
+6 -1
View File
@@ -22,8 +22,12 @@ import bonsai.core.tool
import bonsai.tool as tool
import pytest
from test.bim.bootstrap import NewFile
from typing import TYPE_CHECKING
from bonsai.tool.blender import Blender as subject
if TYPE_CHECKING:
import bpy._typing.rna_enums as rna_enums
class TestImplementsTool(NewFile):
def test_run(self):
@@ -34,6 +38,7 @@ class TestCopyNodeGraph(NewFile):
def test_run(self):
material_to = bpy.data.materials.new("material_to")
material_to.use_nodes = True
assert material_to.node_tree
material_to_nodes = material_to.node_tree.nodes
assert len(material_to_nodes) == 2
for node in material_to_nodes:
@@ -70,7 +75,7 @@ class TestBlenderErrorMessageExtraction(NewFile):
bl_idname = "object.test_fail_operator"
bl_label = "Test Fail Operator"
def execute(self, context):
def execute(self, context) -> "set[rna_enums.OperatorReturnItems]":
self.report({"INFO"}, "Info message.")
subject.report_operator_errors(self, ERROR_REPORTS)
return {"FINISHED"}
+6 -4
View File
@@ -138,6 +138,7 @@ class TestAddBrickifcProject(NewFile):
class TestAddBrickifcReference(NewFile):
def test_run(self):
TestAddBrickifcProject().test_run()
assert BrickStore.graph
element = tool.Ifc.get().createIfcChiller(ifcopenshell.guid.new())
element.Name = "Chiller"
project = URIRef(f"http://example.org/digitaltwin#{tool.Ifc.get().by_type('IfcProject')[0].GlobalId}")
@@ -173,6 +174,7 @@ class TestAddRelation(NewFile):
class TestRemoveRelation(NewFile):
def test_run(self):
TestAddRelation().test_run()
assert BrickStore.graph
source, relation, destination = list(
BrickStore.graph.triples((None, URIRef("https://brickschema.org/schema/Brick#feeds"), None))
)[0]
@@ -321,7 +323,7 @@ class TestGetConvertableBrickSystems(NewFile):
class TestGetParentSpace(NewFile):
def test_run(cls):
def test_run(self):
ifc = ifcopenshell.file()
element = ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcBuildingStorey")
subelement = ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcSpace")
@@ -333,17 +335,17 @@ class TestGetParentSpace(NewFile):
class TestGetElementContainer(NewFile):
def test_nothing(cls):
def test_nothing(self):
pass
class TestGetElementSystems(NewFile):
def test_nothing(cls):
def test_nothing(self):
pass
class TestGetElementFeeds(NewFile):
def test_run(cls):
def test_run(self):
pass
+25 -8
View File
@@ -20,6 +20,9 @@ import bpy
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.api.aggregate
import ifcopenshell.api.feature
import ifcopenshell.api.group
import ifcopenshell.api.spatial
import ifcopenshell.util.element
import bonsai.core.tool
import bonsai.tool as tool
@@ -34,6 +37,7 @@ class TestImplementsTool(NewFile):
class TestAssign(NewIfc):
def test_walls_are_placed_in_its_spatial_collection(self):
assert bpy.context.scene
wall_obj = bpy.data.objects.new("Object", None)
wall_element = tool.Ifc.get().createIfcWall()
tool.Ifc.link(wall_element, wall_obj)
@@ -48,6 +52,7 @@ class TestAssign(NewIfc):
assert "IfcSite" in wall_obj.users_collection[0].name
def test_walls_are_unsorted_if_not_decomposes(self):
assert bpy.context.scene
wall_obj = bpy.data.objects.new("Object", None)
wall_element = tool.Ifc.get().createIfcWall()
tool.Ifc.link(wall_element, wall_obj)
@@ -57,6 +62,7 @@ class TestAssign(NewIfc):
assert "Unsorted" in wall_obj.users_collection[0].name
def test_spatial_structure_elements_are_placed_in_a_collection_of_the_same_name(self):
assert bpy.context.scene
building_obj = bpy.data.objects.new("IfcBuilding/Name", None)
building_element = tool.Ifc.get().createIfcBuilding()
tool.Ifc.link(building_element, building_obj)
@@ -71,6 +77,7 @@ class TestAssign(NewIfc):
assert building_obj.users_collection[0].name == building_obj.name
def test_spaces_are_special_and_are_placed_in_a_spaces_collection(self):
assert bpy.context.scene
space_obj = bpy.data.objects.new("IfcSpace/Name", None)
space_element = tool.Ifc.get().createIfcSpace()
tool.Ifc.link(space_element, space_obj)
@@ -85,6 +92,7 @@ class TestAssign(NewIfc):
assert space_obj.users_collection[0].name == "IfcSpace"
def test_multiple_assigns_do_not_create_duplicate_spatial_structure_collections(self):
assert bpy.context.scene
space_obj = bpy.data.objects.new("IfcSpace/Name", None)
space_element = tool.Ifc.get().createIfcSpace()
tool.Ifc.link(space_element, space_obj)
@@ -102,6 +110,7 @@ class TestAssign(NewIfc):
assert not bpy.data.collections.get("IfcSite/My Site.001")
def test_spatial_zone_elements_are_not_placed_in_a_collection_of_the_same_name(self):
assert bpy.context.scene
space_obj = bpy.data.objects.new("IfcSpaceZone/Name", None)
space_element = tool.Ifc.get().createIfcSpatialZone()
tool.Ifc.link(space_element, space_obj)
@@ -116,6 +125,7 @@ class TestAssign(NewIfc):
assert space_obj.users_collection[0].name != space_obj.name
def test_aggregates_are_also_placed_in_their_container(self):
assert bpy.context.scene
element_obj = bpy.data.objects.new("IfcElementAssembly/Name", None)
element = tool.Ifc.get().createIfcElementAssembly()
subelement_obj = bpy.data.objects.new("IfcBeam/Name", None)
@@ -142,6 +152,7 @@ class TestAssign(NewIfc):
assert "IfcSite" in subelement_obj.users_collection[0].name
def test_projects_are_placed_in_a_collection_of_the_same_name(self):
assert bpy.context.scene
tool.Ifc.set(ifcopenshell.file())
element_obj = bpy.data.objects.new("IfcProject/Name", None)
element = tool.Ifc.get().createIfcProject()
@@ -152,6 +163,7 @@ class TestAssign(NewIfc):
assert element_obj.users_collection[0].name == element_obj.name
def test_multiple_assigns_do_not_create_duplicate_collections(self):
assert bpy.context.scene
tool.Ifc.set(ifcopenshell.file())
element_obj = bpy.data.objects.new("IfcProject/Name", None)
element = tool.Ifc.get().createIfcProject()
@@ -163,6 +175,7 @@ class TestAssign(NewIfc):
assert not bpy.data.collections.get("IfcProject/Name.001")
def test_own_collections_are_retained_and_name_synced(self):
assert bpy.context.scene
building_obj = bpy.data.objects.new("IfcBuilding/Name", None)
building_element = tool.Ifc.get().createIfcBuilding()
tool.Ifc.link(building_element, building_obj)
@@ -178,22 +191,24 @@ class TestAssign(NewIfc):
)
subject.assign(building_obj)
assert bpy.context.scene.collection.children.find(building_collection.name) != -1
assert bpy.data.collections.get("IfcSite/My Site").children.find(building_collection.name) == -1
assert bpy.data.collections.get("IfcProject/My Project").children.find(building_collection.name) == -1
assert bpy.data.collections["IfcSite/My Site"].children.find(building_collection.name) == -1
assert bpy.data.collections["IfcProject/My Project"].children.find(building_collection.name) == -1
assert bpy.context.scene.collection.children.find(building_collection.name) != -1
assert building_collection.objects.find(building_obj.name) != -1
assert building_collection.name == "IfcBuilding/Name"
def test_types_are_placed_in_the_types_collection(self):
assert bpy.context.scene
element_obj = bpy.data.objects.new("IfcWallType/Name", None)
element = tool.Ifc.get().createIfcWallType()
tool.Ifc.link(element, element_obj)
bpy.context.scene.collection.objects.link(element_obj)
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcTypeProduct"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcTypeProduct")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcTypeProduct")
def test_openings_are_placed_in_their_voided_elements_container(self):
assert bpy.context.scene
element_obj = bpy.data.objects.new("IfcOpeningElement/Name", None)
element = tool.Ifc.get().createIfcOpeningElement()
tool.Ifc.link(element, element_obj)
@@ -210,6 +225,7 @@ class TestAssign(NewIfc):
assert element_obj.users_collection[0].name == "IfcSite/My Site"
def test_grids_are_placed_in_their_container(self):
assert bpy.context.scene
element_obj = bpy.data.objects.new("IfcGrid/Name", None)
element = tool.Ifc.get().createIfcGrid()
tool.Ifc.link(element, element_obj)
@@ -223,6 +239,7 @@ class TestAssign(NewIfc):
assert element_obj.users_collection[0].name == "IfcSite/My Site"
def test_grids_axes_are_placed_in_the_grids_container(self):
assert bpy.context.scene
element_obj = bpy.data.objects.new("IfcGrid/Name", None)
axis_obj = bpy.data.objects.new("IfcGrid/Name", None)
axis = tool.Ifc.get().createIfcGridAxis()
@@ -250,7 +267,7 @@ class TestAssign(NewIfc):
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcAnnotation/DRAWING"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcAnnotation/DRAWING")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcAnnotation/DRAWING")
def test_annotations_are_placed_in_their_drawings_collection(self):
self.test_drawings_are_placed_in_their_own_collection()
@@ -272,7 +289,7 @@ class TestAssign(NewIfc):
tool.Ifc.link(element, element_obj)
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcStructuralItem"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcStructuralItem")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcStructuralItem")
def test_structural_connections_are_placed_in_a_connections_collection(self):
element_obj = bpy.data.objects.new("IfcStructuralCurveConnection/Name", None)
@@ -280,7 +297,7 @@ class TestAssign(NewIfc):
tool.Ifc.link(element, element_obj)
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcStructuralItem"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcStructuralItem")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcStructuralItem")
class TestAssignIFC4X3(NewIfc4X3):
@@ -290,7 +307,7 @@ class TestAssignIFC4X3(NewIfc4X3):
tool.Ifc.link(element, element_obj)
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcLinearPositioningElement"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcLinearPositioningElement")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcLinearPositioningElement")
def test_referents_are_placed_in_a_special_collection(self):
element_obj = bpy.data.objects.new("Name", None)
@@ -298,4 +315,4 @@ class TestAssignIFC4X3(NewIfc4X3):
tool.Ifc.link(element, element_obj)
subject.assign(element_obj)
assert element_obj.users_collection[0].name == "IfcReferent"
assert bpy.data.collections.get("IfcProject/My Project").children.get("IfcReferent")
assert bpy.data.collections["IfcProject/My Project"].children.get("IfcReferent")
+16 -14
View File
@@ -34,7 +34,8 @@ class TestSetContext(test.bim.bootstrap.NewFile):
ifc = ifcopenshell.file()
context = ifc.createIfcGeometricRepresentationContext()
subject.set_context(context)
assert bpy.context.scene.BIMContextProperties.active_context_id == context.id()
props = subject.get_context_props()
assert props.active_context_id == context.id()
class TestImportAttributes(test.bim.bootstrap.NewFile):
@@ -48,11 +49,11 @@ class TestImportAttributes(test.bim.bootstrap.NewFile):
context.Precision = 1
subject.set_context(context)
subject.import_attributes()
props = bpy.context.scene.BIMContextProperties
assert props.context_attributes.get("ContextIdentifier").string_value == "ContextIdentifier"
assert props.context_attributes.get("ContextType").string_value == "ContextType"
assert props.context_attributes.get("CoordinateSpaceDimension").int_value == 1
assert props.context_attributes.get("Precision").string_value == "1.0"
props = subject.get_context_props()
assert props.context_attributes["ContextIdentifier"].string_value == "ContextIdentifier"
assert props.context_attributes["ContextType"].string_value == "ContextType"
assert props.context_attributes["CoordinateSpaceDimension"].int_value == 1
assert props.context_attributes["Precision"].string_value == "1.0"
def test_importing_a_subcontext(self):
ifc = ifcopenshell.file()
@@ -63,11 +64,11 @@ class TestImportAttributes(test.bim.bootstrap.NewFile):
subcontext.UserDefinedTargetView = "UserDefinedTargetView"
subject.set_context(subcontext)
subject.import_attributes()
props = bpy.context.scene.BIMContextProperties
assert props.context_attributes.get("TargetScale").float_value == 0.5
assert props.context_attributes.get("TargetView").enum_value == "NOTDEFINED"
assert props.context_attributes.get("UserDefinedTargetView").string_value == "UserDefinedTargetView"
assert not props.context_attributes.get("Precision")
props = subject.get_context_props()
assert props.context_attributes["TargetScale"].float_value == 0.5
assert props.context_attributes["TargetView"].enum_value == "NOTDEFINED"
assert props.context_attributes["UserDefinedTargetView"].string_value == "UserDefinedTargetView"
assert not props.context_attributes["Precision"]
def test_importing_twice(self):
ifc = ifcopenshell.file()
@@ -78,15 +79,16 @@ class TestImportAttributes(test.bim.bootstrap.NewFile):
subject.import_attributes()
context.ContextIdentifier = "ContextIdentifier2"
subject.import_attributes()
props = bpy.context.scene.BIMContextProperties
assert props.context_attributes.get("ContextIdentifier").string_value == "ContextIdentifier2"
props = subject.get_context_props()
assert props.context_attributes["ContextIdentifier"].string_value == "ContextIdentifier2"
class TestClearContext(test.bim.bootstrap.NewFile):
def test_run(self):
TestSetContext().test_run()
subject.clear_context()
assert bpy.context.scene.BIMContextProperties.active_context_id == 0
props = subject.get_context_props()
assert props.active_context_id == 0
class TestGetContext(test.bim.bootstrap.NewFile):
+42 -14
View File
@@ -18,9 +18,11 @@
import os
from pathlib import Path
import numpy as np
import bpy
import mathutils
import ifcopenshell
import ifcopenshell.api.root
import ifcopenshell.guid
import ifcopenshell.util.element
import bonsai.core.tool
@@ -55,7 +57,7 @@ class TestCreateAnnotationObject(NewFile):
class TestCreateCamera(NewFile):
def test_run(self):
obj = subject.create_camera("Name", mathutils.Matrix(), "PERSPECTIVE")
obj = subject.create_camera("Name", mathutils.Matrix(), "PERSPECTIVE", "PLAN_VIEW")
assert obj.name == "Name"
assert obj.matrix_world == mathutils.Matrix()
assert isinstance(obj.data, bpy.types.Camera)
@@ -68,7 +70,7 @@ class TestCreateCamera(NewFile):
class TestCreateSvgSheet(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcProject")
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
tool.Ifc.set(ifc)
ifc_path = Path("test/files/temp/test.ifc").absolute()
bpy.ops.bim.save_project(filepath=str(ifc_path), should_save_as=True)
@@ -92,6 +94,7 @@ class TestDeleteCollection(NewFile):
class TestDeleteDrawingElements(NewFile):
def test_run(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
obj = bpy.data.objects.new("Object", bpy.data.meshes.new("Mesh"))
@@ -155,13 +158,15 @@ class TestDisableEditingText(NewFile):
class TestDisableEditingAssignedProduct(NewFile):
def test_run(self):
obj = bpy.data.objects.new("Object", None)
obj.BIMAssignedProductProperties.is_editing_product = True
props = subject.get_object_assigned_product_props(obj)
props.is_editing_product = True
subject.disable_editing_assigned_product(obj)
assert obj.BIMAssignedProductProperties.is_editing_product == False
assert props.is_editing_product == False
class TestEnableEditing(NewFile):
def test_run(self):
assert bpy.context.scene
obj = bpy.data.objects.new("Object", None)
bpy.context.scene.collection.objects.link(obj)
subject.enable_editing(obj)
@@ -211,8 +216,9 @@ class TestEnableEditingText(NewFile):
class TestEnableEditingAssignedProduct(NewFile):
def test_run(self):
obj = bpy.data.objects.new("Object", None)
props = subject.get_object_assigned_product_props(obj)
subject.enable_editing_assigned_product(obj)
assert obj.BIMAssignedProductProperties.is_editing_product == True
assert props.is_editing_product == True
class TestEnsureUniqueDrawingName(NewFile):
@@ -314,6 +320,7 @@ class TestGetDocumentUri(NewFile):
class TestGetDrawingCollection(NewFile):
def test_run(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
obj = bpy.data.objects.new("Object", None)
@@ -375,9 +382,10 @@ class TestGetName(NewFile):
class TestGenerateDrawingMatrix(NewFile):
def test_returning_the_origin_as_a_fallback(self):
assert subject.generate_drawing_matrix("PLAN_VIEW", None) == mathutils.Matrix()
assert subject.generate_drawing_matrix("PLAN_VIEW", 0) == mathutils.Matrix()
def test_creating_a_plan_view_at_the_cursor_at_a_storey(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
obj = bpy.data.objects.new("Object", None)
@@ -392,11 +400,12 @@ class TestGenerateDrawingMatrix(NewFile):
assert round(m[2][3], 3) == 4.6
def test_creating_an_rcp_at_the_origin(self):
assert subject.generate_drawing_matrix("REFLECTED_PLAN_VIEW", None) == mathutils.Matrix(
assert subject.generate_drawing_matrix("REFLECTED_PLAN_VIEW", 0) == mathutils.Matrix(
((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, 1))
)
def test_creating_an_rcp_at_the_cursor_at_a_storey(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
obj = bpy.data.objects.new("Object", None)
@@ -410,61 +419,78 @@ class TestGenerateDrawingMatrix(NewFile):
)
def test_creating_a_north_elevation_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("ELEVATION_VIEW", "NORTH") == mathutils.Matrix(
((-1, 0, 0, 1), (0, 0, 1, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_a_south_elevation_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("ELEVATION_VIEW", "SOUTH") == mathutils.Matrix(
((1, 0, 0, 1), (0, 0, -1, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_an_east_elevation_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("ELEVATION_VIEW", "EAST") == mathutils.Matrix(
((0, 0, 1, 1), (1, 0, 0, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_a_west_elevation_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("ELEVATION_VIEW", "WEST") == mathutils.Matrix(
((0, 0, -1, 1), (-1, 0, 0, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_a_north_section_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("SECTION_VIEW", "NORTH") == mathutils.Matrix(
((1, 0, 0, 1), (0, 0, -1, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_a_south_section_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("SECTION_VIEW", "SOUTH") == mathutils.Matrix(
((-1, 0, 0, 1), (0, 0, 1, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_an_east_section_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("SECTION_VIEW", "EAST") == mathutils.Matrix(
((0, 0, -1, 1), (-1, 0, 0, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_creating_a_west_section_at_the_cursor(self):
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.generate_drawing_matrix("SECTION_VIEW", "WEST") == mathutils.Matrix(
((0, 0, 1, 1), (1, 0, 0, 2), (0, 1, 0, 3), (0, 0, 0, 1))
)
def test_aligning_model_view_camera_to_viewport(self):
assert (space := tool.Blender.get_view3d_space())
assert (r3d := space.region_3d)
viewport = r3d.view_matrix.inverted()
generated = subject.generate_drawing_matrix("MODEL_VIEW", "PERSPECTIVE")
assert np.allclose(generated, viewport)
generated = subject.generate_drawing_matrix("MODEL_VIEW", "ORTHOGRAPHIC")
assert np.allclose(generated, viewport)
class TestGenerateSheetIdentification(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
subject.generate_sheet_identification() == "A01"
assert subject.generate_sheet_identification() == "A01"
document = ifc.createIfcDocumentInformation()
subject.generate_sheet_identification() == "A02"
assert subject.generate_sheet_identification() == "A02"
class TestGetTextLiteral(NewFile):
@@ -598,9 +624,9 @@ class TestImportTextAttributes(NewFile):
subject.import_text_attributes(obj)
props = tool.Drawing.get_text_props(obj)
literal_props = props.literals[0]
assert literal_props.attributes.get("Literal").string_value == "Literal"
assert literal_props.attributes.get("Path").enum_value == "RIGHT"
assert literal_props.attributes.get("BoxAlignment").string_value == "bottom-left"
assert literal_props.attributes["Literal"].string_value == "Literal"
assert literal_props.attributes["Path"].enum_value == "RIGHT"
assert literal_props.attributes["BoxAlignment"].string_value == "bottom-left"
class TestImportAssignedProduct(NewFile):
@@ -615,7 +641,8 @@ class TestImportAssignedProduct(NewFile):
tool.Ifc.link(wall, wall_obj)
tool.Ifc.link(label, label_obj)
subject.import_assigned_product(label_obj)
assert label_obj.BIMAssignedProductProperties.relating_product == wall_obj
props = subject.get_object_assigned_product_props(label_obj)
assert props.relating_product == wall_obj
def test_doing_nothing_if_no_product_to_import(self):
ifc = ifcopenshell.file()
@@ -624,7 +651,8 @@ class TestImportAssignedProduct(NewFile):
label_obj = bpy.data.objects.new("Object", None)
tool.Ifc.link(label, label_obj)
subject.import_assigned_product(label_obj)
assert label_obj.BIMAssignedProductProperties.relating_product is None
props = subject.get_object_assigned_product_props(label_obj)
assert props.relating_product is None
class TestOpenSchedule(NewFile):
+20 -19
View File
@@ -59,13 +59,13 @@ class TestImportProjectedCRS(NewFile):
projected_crs.MapUnit = unit
subject.import_projected_crs()
props = tool.Georeference.get_georeference_props()
assert props.projected_crs.get("Name").string_value == "Name"
assert props.projected_crs.get("Description").string_value == "Description"
assert props.projected_crs.get("GeodeticDatum").string_value == "GeodeticDatum"
assert props.projected_crs.get("VerticalDatum").string_value == "VerticalDatum"
assert props.projected_crs.get("MapProjection").string_value == "MapProjection"
assert props.projected_crs.get("MapZone").string_value == "MapZone"
assert props.projected_crs.get("MapUnit").enum_value == str(unit.id())
assert props.projected_crs["Name"].string_value == "Name"
assert props.projected_crs["Description"].string_value == "Description"
assert props.projected_crs["GeodeticDatum"].string_value == "GeodeticDatum"
assert props.projected_crs["VerticalDatum"].string_value == "VerticalDatum"
assert props.projected_crs["MapProjection"].string_value == "MapProjection"
assert props.projected_crs["MapZone"].string_value == "MapZone"
assert props.projected_crs["MapUnit"].enum_value == str(unit.id())
def test_run_ifc2x3(self):
ifc = ifcopenshell.file(schema="IFC2X3")
@@ -100,13 +100,13 @@ class TestImportCoordinateOperation(NewFile):
map_conversion.Scale = 6
subject.import_coordinate_operation()
props = tool.Georeference.get_georeference_props()
assert props.coordinate_operation.get("Eastings").string_value == "1.0"
assert props.coordinate_operation.get("Northings").string_value == "2.0"
assert props.coordinate_operation.get("OrthogonalHeight").string_value == "3.0"
assert props.coordinate_operation["Eastings"].string_value == "1.0"
assert props.coordinate_operation["Northings"].string_value == "2.0"
assert props.coordinate_operation["OrthogonalHeight"].string_value == "3.0"
assert props.x_axis_abscissa == "4.0"
assert props.x_axis_ordinate == "5.0"
assert props.grid_north_angle == "-51.3401917"
assert props.coordinate_operation.get("Scale").string_value == "6.0"
assert props.coordinate_operation["Scale"].string_value == "6.0"
def test_run_ifc2x3(self):
ifc = ifcopenshell.file(schema="IFC2X3")
@@ -220,6 +220,7 @@ class TestGetCursorLocation(NewFile):
ifcopenshell.api.run("context.add_context", ifc, context_type="Model")
unit = ifcopenshell.api.run("unit.add_si_unit", ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", ifc, units=[unit])
assert bpy.context.scene
bpy.context.scene.cursor.location = (1.0, 2.0, 3.0)
assert subject.get_cursor_location() == [1000.0, 2000.0, 3000.0]
@@ -229,7 +230,7 @@ class TestXyz2Enh(NewFile):
ifc = ifcopenshell.file()
ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcProject")
tool.Ifc.set(ifc)
assert subject.xyz2enh([0.0, 0.0, 0.0]) == (0.0, 0.0, 0.0)
assert subject.xyz2enh((0.0, 0.0, 0.0)) == (0.0, 0.0, 0.0)
def test_using_the_blender_offset(self):
ifc = ifcopenshell.file()
@@ -238,7 +239,7 @@ class TestXyz2Enh(NewFile):
props = tool.Georeference.get_georeference_props()
props.has_blender_offset = True
props.blender_offset_x = "1.0"
assert subject.xyz2enh([0.0, 0.0, 0.0]) == (1.0, 0.0, 0.0)
assert subject.xyz2enh((0.0, 0.0, 0.0)) == (1.0, 0.0, 0.0)
def test_using_the_map_conversion(self):
ifc = ifcopenshell.file()
@@ -248,7 +249,7 @@ class TestXyz2Enh(NewFile):
ifcopenshell.api.run("georeference.add_georeferencing", ifc)
map_conversion = ifc.by_type("IfcMapConversion")[0]
map_conversion.Eastings = 1.0
assert subject.xyz2enh([0.0, 0.0, 0.0]) == (1.0, 0.0, 0.0)
assert subject.xyz2enh((0.0, 0.0, 0.0)) == (1.0, 0.0, 0.0)
def test_applying_both_blender_offset_and_map_conversion(self):
props = tool.Georeference.get_georeference_props()
@@ -261,7 +262,7 @@ class TestXyz2Enh(NewFile):
ifcopenshell.api.run("georeference.add_georeferencing", ifc)
map_conversion = ifc.by_type("IfcMapConversion")[0]
map_conversion.Northings = 1.0
assert subject.xyz2enh([0.0, 0.0, 0.0]) == (1.0, 1.0, 0.0)
assert subject.xyz2enh((0.0, 0.0, 0.0)) == (1.0, 1.0, 0.0)
class TestEnh2Xyz(NewFile):
@@ -269,7 +270,7 @@ class TestEnh2Xyz(NewFile):
ifc = ifcopenshell.file()
ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcProject")
tool.Ifc.set(ifc)
assert subject.enh2xyz([0.0, 0.0, 0.0]) == (0.0, 0.0, 0.0)
assert subject.enh2xyz((0.0, 0.0, 0.0)) == (0.0, 0.0, 0.0)
def test_using_the_blender_offset(self):
ifc = ifcopenshell.file()
@@ -278,7 +279,7 @@ class TestEnh2Xyz(NewFile):
props = tool.Georeference.get_georeference_props()
props.has_blender_offset = True
props.blender_offset_x = "1.0"
assert subject.enh2xyz([0.0, 0.0, 0.0]) == (-1.0, 0.0, 0.0)
assert subject.enh2xyz((0.0, 0.0, 0.0)) == (-1.0, 0.0, 0.0)
def test_using_the_map_conversion(self):
ifc = ifcopenshell.file()
@@ -288,7 +289,7 @@ class TestEnh2Xyz(NewFile):
ifcopenshell.api.run("georeference.add_georeferencing", ifc)
map_conversion = ifc.by_type("IfcMapConversion")[0]
map_conversion.Eastings = 1.0
assert subject.enh2xyz([0.0, 0.0, 0.0]) == (-1.0, 0.0, 0.0)
assert subject.enh2xyz((0.0, 0.0, 0.0)) == (-1.0, 0.0, 0.0)
def test_applying_both_blender_offset_and_map_conversion(self):
props = tool.Georeference.get_georeference_props()
@@ -301,4 +302,4 @@ class TestEnh2Xyz(NewFile):
ifcopenshell.api.run("georeference.add_georeferencing", ifc)
map_conversion = ifc.by_type("IfcMapConversion")[0]
map_conversion.Northings = 1.0
assert subject.enh2xyz([0.0, 0.0, 0.0]) == (-1.0, -1.0, 0.0)
assert subject.enh2xyz((0.0, 0.0, 0.0)) == (-1.0, -1.0, 0.0)
+10 -10
View File
@@ -79,11 +79,11 @@ class TestImportLibraryAttributes(NewFile):
library = ifc.createIfcLibraryInformation("Name", "Version", None, "VersionDate", "Location", "Description")
subject.import_library_attributes(library)
props = tool.Library.get_library_props()
assert props.library_attributes.get("Name").string_value == "Name"
assert props.library_attributes.get("Version").string_value == "Version"
assert props.library_attributes.get("VersionDate").string_value == "VersionDate"
assert props.library_attributes.get("Location").string_value == "Location"
assert props.library_attributes.get("Description").string_value == "Description"
assert props.library_attributes["Name"].string_value == "Name"
assert props.library_attributes["Version"].string_value == "Version"
assert props.library_attributes["VersionDate"].string_value == "VersionDate"
assert props.library_attributes["Location"].string_value == "Location"
assert props.library_attributes["Description"].string_value == "Description"
class TestImportReferenceAttributes(NewFile):
@@ -92,11 +92,11 @@ class TestImportReferenceAttributes(NewFile):
reference = ifc.createIfcLibraryReference("Location", "Identification", "Name", "Description", "Language")
subject.import_reference_attributes(reference)
props = tool.Library.get_library_props()
assert props.reference_attributes.get("Location").string_value == "Location"
assert props.reference_attributes.get("Identification").string_value == "Identification"
assert props.reference_attributes.get("Name").string_value == "Name"
assert props.reference_attributes.get("Description").string_value == "Description"
assert props.reference_attributes.get("Language").string_value == "Language"
assert props.reference_attributes["Location"].string_value == "Location"
assert props.reference_attributes["Identification"].string_value == "Identification"
assert props.reference_attributes["Name"].string_value == "Name"
assert props.reference_attributes["Description"].string_value == "Description"
assert props.reference_attributes["Language"].string_value == "Language"
class TestImportReferences(NewFile):
+2
View File
@@ -19,7 +19,9 @@
import bpy
import ifcopenshell
import ifcopenshell.api.material
import ifcopenshell.api.root
import ifcopenshell.api.style
import ifcopenshell.api.type
import ifcopenshell.util.element
import ifcopenshell.util.representation
import ifcopenshell.util.unit
+75 -65
View File
@@ -36,7 +36,7 @@ class TestAddAddressAttribute(NewFile):
subject().add_address_attribute("FacsimileNumbers")
subject().add_address_attribute("ElectronicMailAddresses")
subject().add_address_attribute("MessagingIDs")
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
assert len(props.address_lines) == 1
assert len(props.telephone_numbers) == 1
assert len(props.facsimile_numbers) == 1
@@ -49,7 +49,7 @@ class TestAddPersonAttribute(NewFile):
subject().add_person_attribute("MiddleNames")
subject().add_person_attribute("PrefixTitles")
subject().add_person_attribute("SuffixTitles")
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
assert len(props.middle_names) == 1
assert len(props.prefix_titles) == 1
assert len(props.suffix_titles) == 1
@@ -61,7 +61,8 @@ class TestClearActor(NewFile):
actor = ifc.createIfcActor()
subject().set_actor(actor)
subject().clear_actor()
assert bpy.context.scene.BIMOwnerProperties.active_actor_id == 0
props = subject.get_owner_props()
assert props.active_actor_id == 0
class TestClearAddress(NewFile):
@@ -70,12 +71,13 @@ class TestClearAddress(NewFile):
address = ifc.createIfcPostalAddress()
subject().set_address(address)
subject().clear_address()
assert bpy.context.scene.BIMOwnerProperties.active_address_id == 0
props = subject.get_owner_props()
assert props.active_address_id == 0
class TestClearOrganisation(NewFile):
def test_run(self):
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
props.active_organisation_id = 1
subject().clear_organisation()
assert props.active_organisation_id == 0
@@ -83,7 +85,7 @@ class TestClearOrganisation(NewFile):
class TestClearPerson(NewFile):
def test_run(self):
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
props.active_person_id = 1
subject().clear_person()
assert props.active_person_id == 0
@@ -94,14 +96,16 @@ class TestClearRole(NewFile):
role = ifcopenshell.file().createIfcActorRole()
subject().set_role(role)
subject().clear_role()
assert bpy.context.scene.BIMOwnerProperties.active_role_id == 0
props = subject.get_owner_props()
assert props.active_role_id == 0
class TestClearUser(NewFile):
def test_run(self):
TestSetUser().test_run()
subject.clear_user()
assert bpy.context.scene.BIMOwnerProperties.active_user_id == 0
props = subject.get_owner_props()
assert props.active_user_id == 0
class TestExportActorAttributes(NewFile):
@@ -288,11 +292,11 @@ class TestImportActorAttributes(NewFile):
actor.ObjectType = "ObjectType"
subject.set_actor(actor)
subject.import_actor_attributes(actor)
props = bpy.context.scene.BIMOwnerProperties
assert props.actor_attributes.get("GlobalId").string_value == "GlobalId"
assert props.actor_attributes.get("Name").string_value == "Name"
assert props.actor_attributes.get("Description").string_value == "Description"
assert props.actor_attributes.get("ObjectType").string_value == "ObjectType"
props = subject.get_owner_props()
assert props.actor_attributes["GlobalId"].string_value == "GlobalId"
assert props.actor_attributes["Name"].string_value == "Name"
assert props.actor_attributes["Description"].string_value == "Description"
assert props.actor_attributes["ObjectType"].string_value == "ObjectType"
def test_importing_an_occupant(self):
ifc = ifcopenshell.file()
@@ -305,12 +309,12 @@ class TestImportActorAttributes(NewFile):
actor.PredefinedType = "TENANT"
subject.set_actor(actor)
subject.import_actor_attributes(actor)
props = bpy.context.scene.BIMOwnerProperties
assert props.actor_attributes.get("GlobalId").string_value == "GlobalId"
assert props.actor_attributes.get("Name").string_value == "Name"
assert props.actor_attributes.get("Description").string_value == "Description"
assert props.actor_attributes.get("ObjectType").string_value == "ObjectType"
assert props.actor_attributes.get("PredefinedType").enum_value == "TENANT"
props = subject.get_owner_props()
assert props.actor_attributes["GlobalId"].string_value == "GlobalId"
assert props.actor_attributes["Name"].string_value == "Name"
assert props.actor_attributes["Description"].string_value == "Description"
assert props.actor_attributes["ObjectType"].string_value == "ObjectType"
assert props.actor_attributes["PredefinedType"].enum_value == "TENANT"
class TestImportAddressAttributes(NewFile):
@@ -330,16 +334,16 @@ class TestImportAddressAttributes(NewFile):
address.Country = "Country"
subject().set_address(address)
subject().import_address_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.address_attributes.get("Purpose").enum_value == "USERDEFINED"
assert props.address_attributes.get("Description").string_value == "Description"
assert props.address_attributes.get("UserDefinedPurpose").string_value == "UserDefinedPurpose"
assert props.address_attributes.get("InternalLocation").string_value == "InternalLocation"
assert props.address_attributes.get("PostalBox").string_value == "PostalBox"
assert props.address_attributes.get("Town").string_value == "Town"
assert props.address_attributes.get("Region").string_value == "Region"
assert props.address_attributes.get("PostalCode").string_value == "PostalCode"
assert props.address_attributes.get("Country").string_value == "Country"
props = subject.get_owner_props()
assert props.address_attributes["Purpose"].enum_value == "USERDEFINED"
assert props.address_attributes["Description"].string_value == "Description"
assert props.address_attributes["UserDefinedPurpose"].string_value == "UserDefinedPurpose"
assert props.address_attributes["InternalLocation"].string_value == "InternalLocation"
assert props.address_attributes["PostalBox"].string_value == "PostalBox"
assert props.address_attributes["Town"].string_value == "Town"
assert props.address_attributes["Region"].string_value == "Region"
assert props.address_attributes["PostalCode"].string_value == "PostalCode"
assert props.address_attributes["Country"].string_value == "Country"
assert len(props.address_lines) == 2
assert props.address_lines[0].name == "Address"
assert props.address_lines[1].name == "Lines"
@@ -351,8 +355,8 @@ class TestImportAddressAttributes(NewFile):
address.Purpose = "OFFICE"
subject().set_address(address)
subject().import_address_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.address_attributes.get("Purpose").enum_value == "OFFICE"
props = subject.get_owner_props()
assert props.address_attributes["Purpose"].enum_value == "OFFICE"
assert len(props.address_lines) == 0
def test_importing_a_telecom_address(self):
@@ -370,10 +374,10 @@ class TestImportAddressAttributes(NewFile):
address.MessagingIDs = ["Messaging", "IDs"]
subject().set_address(address)
subject().import_address_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.address_attributes.get("Purpose").enum_value == "USERDEFINED"
assert props.address_attributes.get("Description").string_value == "Description"
assert props.address_attributes.get("UserDefinedPurpose").string_value == "UserDefinedPurpose"
props = subject.get_owner_props()
assert props.address_attributes["Purpose"].enum_value == "USERDEFINED"
assert props.address_attributes["Description"].string_value == "Description"
assert props.address_attributes["UserDefinedPurpose"].string_value == "UserDefinedPurpose"
assert [a.name for a in props.telephone_numbers] == ["Telephone", "Numbers"]
assert [a.name for a in props.facsimile_numbers] == ["Facsimile", "Numbers"]
assert [a.name for a in props.electronic_mail_addresses] == ["Electronic", "Mail", "Addresses"]
@@ -386,8 +390,8 @@ class TestImportAddressAttributes(NewFile):
address.Purpose = "OFFICE"
subject().set_address(address)
subject().import_address_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.address_attributes.get("Purpose").enum_value == "OFFICE"
props = subject.get_owner_props()
assert props.address_attributes["Purpose"].enum_value == "OFFICE"
assert len(props.telephone_numbers) == 0
assert len(props.facsimile_numbers) == 0
assert len(props.electronic_mail_addresses) == 0
@@ -404,10 +408,10 @@ class TestImportOrganisationAttributes(NewFile):
organisation.Description = "Description"
subject().set_organisation(organisation)
subject().import_organisation_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.organisation_attributes.get("Identification").string_value == "Identification"
assert props.organisation_attributes.get("Name").string_value == "Name"
assert props.organisation_attributes.get("Description").string_value == "Description"
props = subject.get_owner_props()
assert props.organisation_attributes["Identification"].string_value == "Identification"
assert props.organisation_attributes["Name"].string_value == "Name"
assert props.organisation_attributes["Description"].string_value == "Description"
def test_overwriting_a_previous_import(self):
ifc = ifcopenshell.file()
@@ -420,9 +424,9 @@ class TestImportOrganisationAttributes(NewFile):
organisation.Identification = "Identification2"
organisation.Description = None
subject().import_organisation_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.organisation_attributes.get("Identification").string_value == "Identification2"
assert props.organisation_attributes.get("Description").string_value == ""
props = subject.get_owner_props()
assert props.organisation_attributes["Identification"].string_value == "Identification2"
assert props.organisation_attributes["Description"].string_value == ""
class TestImportPersonAttributes(NewFile):
@@ -438,10 +442,10 @@ class TestImportPersonAttributes(NewFile):
person.SuffixTitles = ("suffix", "titles")
subject().set_person(person)
subject().import_person_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.person_attributes.get("Identification").string_value == "identification"
assert props.person_attributes.get("GivenName").string_value == "given_name"
assert props.person_attributes.get("FamilyName").string_value == "family_name"
props = subject.get_owner_props()
assert props.person_attributes["Identification"].string_value == "identification"
assert props.person_attributes["GivenName"].string_value == "given_name"
assert props.person_attributes["FamilyName"].string_value == "family_name"
assert len(props.middle_names) == 2
assert props.middle_names[0].name == "middle"
assert props.middle_names[1].name == "names"
@@ -463,9 +467,9 @@ class TestImportPersonAttributes(NewFile):
person.Identification = "identification2"
person.GivenName = None
subject().import_person_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.person_attributes.get("Identification").string_value == "identification2"
assert props.person_attributes.get("GivenName").string_value == ""
props = subject.get_owner_props()
assert props.person_attributes["Identification"].string_value == "identification2"
assert props.person_attributes["GivenName"].string_value == ""
class TestImportRoleAttributes(NewFile):
@@ -478,10 +482,10 @@ class TestImportRoleAttributes(NewFile):
role.Description = "Description"
subject().set_role(role)
subject().import_role_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.role_attributes.get("Role").enum_value == "USERDEFINED"
assert props.role_attributes.get("UserDefinedRole").string_value == "UserDefinedRole"
assert props.role_attributes.get("Description").string_value == "Description"
props = subject.get_owner_props()
assert props.role_attributes["Role"].enum_value == "USERDEFINED"
assert props.role_attributes["UserDefinedRole"].string_value == "UserDefinedRole"
assert props.role_attributes["Description"].string_value == "Description"
def test_importing_twice(self):
ifc = ifcopenshell.file()
@@ -492,8 +496,8 @@ class TestImportRoleAttributes(NewFile):
subject().import_role_attributes()
role.Role = "ARCHITECT"
subject().import_role_attributes()
props = bpy.context.scene.BIMOwnerProperties
assert props.role_attributes.get("Role").enum_value == "ARCHITECT"
props = subject.get_owner_props()
assert props.role_attributes["Role"].enum_value == "ARCHITECT"
class TestRemoveAddressAttribute(NewFile):
@@ -503,7 +507,7 @@ class TestRemoveAddressAttribute(NewFile):
subject().remove_address_attribute("FacsimileNumbers", 0)
subject().remove_address_attribute("ElectronicMailAddresses", 0)
subject().remove_address_attribute("MessagingIDs", 0)
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
assert len(props.address_lines) == 0
assert len(props.telephone_numbers) == 0
assert len(props.facsimile_numbers) == 0
@@ -519,7 +523,7 @@ class TestRemovePersonAttribute(NewFile):
subject().remove_person_attribute("PrefixTitles", 0)
subject().add_person_attribute("SuffixTitles")
subject().remove_person_attribute("SuffixTitles", 0)
props = bpy.context.scene.BIMOwnerProperties
props = subject.get_owner_props()
assert len(props.middle_names) == 0
assert len(props.prefix_titles) == 0
assert len(props.suffix_titles) == 0
@@ -530,7 +534,8 @@ class TestSetActor(NewFile):
ifc = ifcopenshell.file()
actor = ifc.createIfcActor()
subject().set_actor(actor)
assert bpy.context.scene.BIMOwnerProperties.active_actor_id == actor.id()
props = subject.get_owner_props()
assert props.active_actor_id == actor.id()
class TestSetAddress(NewFile):
@@ -538,28 +543,32 @@ class TestSetAddress(NewFile):
ifc = ifcopenshell.file()
address = ifc.createIfcPostalAddress()
subject().set_address(address)
assert bpy.context.scene.BIMOwnerProperties.active_address_id == address.id()
props = subject.get_owner_props()
assert props.active_address_id == address.id()
class TestSetOrganisation(NewFile):
def test_run(self):
organisation = ifcopenshell.file().createIfcOrganization()
subject().set_organisation(organisation)
assert bpy.context.scene.BIMOwnerProperties.active_organisation_id == organisation.id()
props = subject.get_owner_props()
assert props.active_organisation_id == organisation.id()
class TestSetPerson(NewFile):
def test_run(self):
person = ifcopenshell.file().createIfcPerson()
subject().set_person(person)
assert bpy.context.scene.BIMOwnerProperties.active_person_id == person.id()
props = subject.get_owner_props()
assert props.active_person_id == person.id()
class TestSetRole(NewFile):
def test_run(self):
role = ifcopenshell.file().createIfcActorRole()
subject().set_role(role)
assert bpy.context.scene.BIMOwnerProperties.active_role_id == role.id()
props = subject.get_owner_props()
assert props.active_role_id == role.id()
class TestSetUser(NewFile):
@@ -568,4 +577,5 @@ class TestSetUser(NewFile):
tool.Ifc.set(ifc)
user = ifc.createIfcPersonAndOrganization()
subject.set_user(user)
assert bpy.context.scene.BIMOwnerProperties.active_user_id == user.id()
props = subject.get_owner_props()
assert props.active_user_id == user.id()
+6 -6
View File
@@ -391,8 +391,8 @@ class TestImportSurfaceAttributes(NewFile):
props = tool.Style.get_style_props()
style = ifc.create_entity("IfcSurfaceStyle", "Name", "BOTH")
subject.import_surface_attributes(style)
assert props.attributes.get("Name").string_value == "Name"
assert props.attributes.get("Side").enum_value == "BOTH"
assert props.attributes["Name"].string_value == "Name"
assert props.attributes["Side"].enum_value == "BOTH"
def test_importing_surface_attributes_twice(self):
tool.Ifc.set(ifc := ifcopenshell.file())
@@ -400,12 +400,12 @@ class TestImportSurfaceAttributes(NewFile):
props = tool.Style.get_style_props()
subject.import_surface_attributes(style)
assert len(props.attributes) == 2
assert props.attributes.get("Name").string_value == "Name"
assert props.attributes.get("Side").enum_value == "BOTH"
assert props.attributes["Name"].string_value == "Name"
assert props.attributes["Side"].enum_value == "BOTH"
subject.import_surface_attributes(style)
assert len(props.attributes) == 2
assert props.attributes.get("Name").string_value == "Name"
assert props.attributes.get("Side").enum_value == "BOTH"
assert props.attributes["Name"].string_value == "Name"
assert props.attributes["Side"].enum_value == "BOTH"
class TestImportPresentationStyles(NewFile):
+22 -18
View File
@@ -19,6 +19,7 @@
import bpy
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.unit
import bonsai.core.tool
import bonsai.tool as tool
import numpy as np
@@ -43,6 +44,7 @@ class TestAddPorts(NewFile):
element = tool.Ifc.get_entity(obj)
obj.matrix_world = Euler((pi / 2, 0, pi / 2)).to_matrix().to_4x4() @ obj.matrix_world
# move origin
assert isinstance(obj.data, bpy.types.Mesh)
for v in obj.data.vertices:
v.co += Vector((0, 0, 2.5))
return obj, element
@@ -90,6 +92,7 @@ class TestAddPorts(NewFile):
class TestCreateEmptyAtCursorWithElementOrientation(NewFile):
def test_run(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc().set(ifc)
obj = bpy.data.objects.new("Object", None)
@@ -161,7 +164,7 @@ class TestGetPorts(NewFile):
element = ifc.createIfcDuctSegment()
port = ifc.createIfcDistributionPort()
ifcopenshell.api.run("system.assign_port", ifc, element=element, port=port)
subject.get_ports(element) == [port]
assert subject.get_ports(element) == [port]
class TestImportSystemAttributes(NewFile):
@@ -175,10 +178,10 @@ class TestImportSystemAttributes(NewFile):
system.ObjectType = "ObjectType"
subject().import_system_attributes(system)
props = tool.System.get_system_props()
assert props.system_attributes.get("GlobalId").string_value == "GlobalId"
assert props.system_attributes.get("Name").string_value == "Name"
assert props.system_attributes.get("Description").string_value == "Description"
assert props.system_attributes.get("ObjectType").string_value == "ObjectType"
assert props.system_attributes["GlobalId"].string_value == "GlobalId"
assert props.system_attributes["Name"].string_value == "Name"
assert props.system_attributes["Description"].string_value == "Description"
assert props.system_attributes["ObjectType"].string_value == "ObjectType"
def test_importing_a_building_system(self):
ifc = ifcopenshell.file()
@@ -192,12 +195,12 @@ class TestImportSystemAttributes(NewFile):
system.LongName = "LongName"
subject().import_system_attributes(system)
props = tool.System.get_system_props()
assert props.system_attributes.get("GlobalId").string_value == "GlobalId"
assert props.system_attributes.get("Name").string_value == "Name"
assert props.system_attributes.get("Description").string_value == "Description"
assert props.system_attributes.get("ObjectType").string_value == "ObjectType"
assert props.system_attributes.get("PredefinedType").enum_value == "SHADING"
assert props.system_attributes.get("LongName").string_value == "LongName"
assert props.system_attributes["GlobalId"].string_value == "GlobalId"
assert props.system_attributes["Name"].string_value == "Name"
assert props.system_attributes["Description"].string_value == "Description"
assert props.system_attributes["ObjectType"].string_value == "ObjectType"
assert props.system_attributes["PredefinedType"].enum_value == "SHADING"
assert props.system_attributes["LongName"].string_value == "LongName"
def test_importing_a_distribution_system(self):
ifc = ifcopenshell.file()
@@ -211,12 +214,12 @@ class TestImportSystemAttributes(NewFile):
system.LongName = "LongName"
subject().import_system_attributes(system)
props = tool.System.get_system_props()
assert props.system_attributes.get("GlobalId").string_value == "GlobalId"
assert props.system_attributes.get("Name").string_value == "Name"
assert props.system_attributes.get("Description").string_value == "Description"
assert props.system_attributes.get("ObjectType").string_value == "ObjectType"
assert props.system_attributes.get("PredefinedType").enum_value == "ELECTRICAL"
assert props.system_attributes.get("LongName").string_value == "LongName"
assert props.system_attributes["GlobalId"].string_value == "GlobalId"
assert props.system_attributes["Name"].string_value == "Name"
assert props.system_attributes["Description"].string_value == "Description"
assert props.system_attributes["ObjectType"].string_value == "ObjectType"
assert props.system_attributes["PredefinedType"].enum_value == "ELECTRICAL"
assert props.system_attributes["LongName"].string_value == "LongName"
class TestImportSystems(NewFile):
@@ -245,7 +248,7 @@ class TestLoadPorts(NewFile):
port = ifc.create_entity("IfcDistributionPort")
subject.load_ports(element, [port])
obj = tool.Ifc.get_object(port)
assert obj
assert isinstance(obj, bpy.types.Object)
assert obj.users_collection
assert list(obj.location) == [0, 0, 0]
@@ -262,6 +265,7 @@ class TestRunRootAssignClass(NewFile):
class TestSelectSystemProducts(NewFile):
def test_run(self):
assert bpy.context.scene
ifc = ifcopenshell.file()
tool.Ifc().set(ifc)
element = ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcPump")
+5 -3
View File
@@ -18,6 +18,8 @@
import bpy
import ifcopenshell
import ifcopenshell.api.root
import ifcopenshell.api.type
import bonsai.core.tool
import bonsai.tool as tool
from test.bim.bootstrap import NewFile
@@ -153,9 +155,9 @@ class TestGetTypeOccurrences(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
wall_type = ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcWallType")
wall = ifcopenshell.api.run("root.create_entity", ifc, ifc_class="IfcWall")
ifcopenshell.api.run("type.assign_type", ifc, related_objects=[wall], relating_type=wall_type)
wall_type = ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcWallType")
wall = ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcWall")
ifcopenshell.api.type.assign_type(ifc, related_objects=[wall], relating_type=wall_type)
assert subject.get_type_occurrences(wall_type) == (wall,)
+4
View File
@@ -104,6 +104,7 @@ class TestExportUnitAttributes(NewFile):
class TestGetSceneUnitName(NewFile):
def test_getting_an_imperial_name(self):
assert bpy.context.scene
props = tool.Blender.get_bim_props()
bpy.context.scene.unit_settings.system = "IMPERIAL"
bpy.context.scene.unit_settings.length_unit = "MILES"
@@ -130,12 +131,14 @@ class TestGetSceneUnitName(NewFile):
assert subject.get_scene_unit_name("VOLUMEUNIT") == "cubic inch"
def test_getting_a_name_with_no_unit_system(self):
assert bpy.context.scene
bpy.context.scene.unit_settings.system = "NONE"
assert subject.get_scene_unit_name("LENGTHUNIT") == "foot"
class TestGetSceneUnitSIPrefix:
def test_run(self):
assert bpy.context.scene
bpy.context.scene.unit_settings.system = "METRIC"
bpy.context.scene.unit_settings.length_unit = "METERS"
assert subject.get_scene_unit_si_prefix("LENGTHUNIT") is None
@@ -298,6 +301,7 @@ class TestImportUnits(NewFile):
class TestIsSceneUnitMetric(NewFile):
def test_run(self):
assert bpy.context.scene
props = bpy.context.scene.unit_settings
props.system = "METRIC"
assert subject.is_scene_unit_metric() is True
+1 -1
View File
@@ -130,7 +130,7 @@ void print_usage(bool suggest_help = true)
#ifdef WITH_HDF5
<< " .h5 HDF Hierarchical Data Format storing positions, normals and indices\n"
#endif
#ifdef IFOPSH_WITH_CGAL
#ifdef IFOPSH_WITH_CITYJSON
<< " .cityjson City JSON format for geospatial data\n"
#endif
<< " .ttl TTL/WKT RDF Turtle with Well-Known-Text geometry\n"
+3 -3
View File
@@ -5,12 +5,12 @@ IfcMax is a 3ds Max importer plugin able to import the IFC file format.
Community builds are available for 3ds Max by Josef Wienerroither (also known
as ``FrogsInSpace`` or ``spacefrog``). Builds are available for IfcOpenShell
v0.7.0 for 3ds Max version 2020-2024. Older builds are also available for
IfcOpenShell v0.6.0 for 3ds Max version 2015-2022.
v0.8.3 for 3ds Max version 2017-2026. Older builds are also available based
on IfcOpenShell v0.6 and v0.7 in the github release section linked below.
It is recommended to use the latest version of IfcOpenShell and 3ds Max.
- `Visit FrogsInSpace official website for IfcMax <https://www.frogsinspace.at/?p=3454>`__.
- `Visit FrogsInSpace official website for IfcMax <https://www.frogsinspace.at/?p=4168>`__.
- `Download IfcMax plugins <https://github.com/FrogsInSpace/IfcOpenShell/releases>`__.
.. note::
@@ -30,7 +30,7 @@ Presently, this API supports:
4. Creating geometric representations from a business logical definition
5. Mapping individual business logical segments to geometric segments (complete for horizontal, missing clothoid for vertical, not implemented for cant)
6. Using curve geometry to determine IfcCurveSegment.Transition transition code.
7. Utility functions for printing business logical and geometric representations, as well as minimumal geometry evaluations
7. Utility functions for printing business logical and geometric representations, as well as minimal geometry evaluations
Future versions of this API will support:
1. Defining alignments using the PI method, including transition spirals
@@ -23,7 +23,9 @@ import ifcopenshell.guid
from ifcopenshell import entity_instance
def add_stationing_to_alignment(file: ifcopenshell.file, alignment: entity_instance, start_station: float) -> None:
def add_stationing_to_alignment(
file: ifcopenshell.file, alignment: entity_instance, start_station: float, plus_seperator=3, accuracy=3
) -> None:
"""
Adds stationing to an alignment by creating an IfcReferent with the Pset_Stationing property set to establish the stationing at the start of the alignment.
Note - this function assumes the stationing has not been previously defined
@@ -43,20 +45,20 @@ def add_stationing_to_alignment(file: ifcopenshell.file, alignment: entity_insta
# the example is a circle. a better way would be to pass a representation into the function
object_placement = None
representation = None
# basis_curve = ifcopenshell.api.alignment.get_basis_curve(alignment)
# if basis_curve:
# object_placement = file.createIfcLinearPlacement(
# RelativePlacement=file.createIfcAxis2PlacementLinear(
# Location=file.createIfcPointByDistanceExpression(
# DistanceAlong=file.createIfcLengthMeasure(0.0),
# OffsetLateral=None,
# OffsetVertical=None,
# OffsetLongitudinal=None,
# BasisCurve=basis_curve,
# )
# ),
# CartesianPosition=None,
# )
basis_curve = ifcopenshell.api.alignment.get_basis_curve(alignment)
if basis_curve:
object_placement = file.createIfcLinearPlacement(
RelativePlacement=file.createIfcAxis2PlacementLinear(
Location=file.createIfcPointByDistanceExpression(
DistanceAlong=file.createIfcLengthMeasure(0.0),
OffsetLateral=None,
OffsetVertical=None,
OffsetLongitudinal=None,
BasisCurve=basis_curve,
)
),
CartesianPosition=None,
)
# representation = file.create_entity(
# name="IfcCircle",
# position=file.createIfcAxis2Placement2D(Location=file.createIfcCartesianPoint(Coordinates=(0.0, 0.0)),
@@ -67,7 +69,7 @@ def add_stationing_to_alignment(file: ifcopenshell.file, alignment: entity_insta
start_referent = file.createIfcReferent(
GlobalId=ifcopenshell.guid.new(),
OwnerHistory=None,
Name=ifcopenshell.util.stationing.station_as_string(start_station),
Name=ifcopenshell.util.stationing.station_as_string(start_station, plus_seperator, accuracy),
Description=None,
ObjectType=None,
ObjectPlacement=object_placement,
@@ -0,0 +1,31 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
"""
Coordinate Geometry (cogo) functions primarily for survey points and control monument for layout, parcels, etc.
"""
from .add_survey_point import add_survey_point
from .assign_survey_point import assign_survey_point
from .edit_survey_point import edit_survey_point
__all__ = [
"add_survey_point",
"assign_survey_point",
"edit_survey_point",
]
@@ -0,0 +1,44 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import ifcopenshell
from ifcopenshell import entity_instance
import typing
def add_survey_point(file: ifcopenshell.file, survey_point: entity_instance) -> entity_instance:
"""
Adds a single survey point to the model based on IFC Concept Template 4.1.7.1.2.5.
Survey points are located relative to IfcRepresentationContext.WorldCoordinateSystem
:param survey_point: The survey point
:return: an IfcAnnotation entity
Example:
.. code:: python
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0)))
"""
context = ifcopenshell.util.representation.get_context(file,"Model","Annotation","MODEL_VIEW")
shape_representation = file.createIfcShapeRepresentation(ContextOfItems=context,RepresentationIdentifier='Annotation',RepresentationType='Point',Items=[survey_point])
representation = file.createIfcProductDefinitionShape(Representations=[shape_representation])
annotation = file.createIfcAnnotation(ifcopenshell.guid.new(),ObjectPlacement=context.WorldCoordinateSystem,Representation=representation,PredefinedType="SURVEY")
site = file.by_type("IfcSite")[0]
ifcopenshell.api.spatial.assign_container(file,relating_structure=site,products=[annotation])
return annotation
@@ -0,0 +1,38 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import ifcopenshell
from ifcopenshell import entity_instance
import typing
def assign_survey_point(annotation: entity_instance, survey_point: entity_instance):
"""
Assigns a coordinate point to a survey point annotation
:param annotaton: The survey point annotation
:param survey_point: The survey point
:return: None
Example:
.. code:: python
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0)))
ifcopenshell.api.cogo.assign_surve_point(annotation,file.createIfcCartesianPoint(4000.0,3500.0,100.0))
"""
annotation.Representation.Representations[0].Items = [survey_point]
@@ -0,0 +1,40 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import ifcopenshell
from ifcopenshell import entity_instance
import typing
def edit_survey_point(annotation: entity_instance, x:float,y:float,z:float=0.0):
"""
Edits the location of a previously defined survey point
:param survey_point: The survey point
:return: None
Example:
.. code:: python
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0)))
ifcopenshell.api.cogo.edit_surve_point(annotation,3500.0,2000.0)
"""
if annotation.Representation.Representations[0].Items[0].Dim == 2:
annotation.Representation.Representations[0].Items[0].Coordinates = ((x,y))
else:
annotation.Representation.Representations[0].Items[0].Coordinates = ((x,y,z))
@@ -506,7 +506,9 @@ class Usecase:
def reuse_existing_contexts(self) -> None:
added_contexts = set([e for e in self.added_elements.values() if e.is_a("IfcGeometricRepresentationContext")])
added_contexts -= set(self.existing_contexts)
for added_context in added_contexts:
sorted_added_contexts = [c for c in added_contexts if c.is_a() == "IfcGeometricRepresentationContext"]
sorted_added_contexts.extend([c for c in added_contexts if c.is_a() == "IfcGeometricRepresentationSubContext"])
for added_context in sorted_added_contexts:
equivalent_existing_context = self.get_equivalent_existing_context(added_context)
if not equivalent_existing_context:
equivalent_existing_context = self.create_equivalent_context(added_context)
@@ -541,18 +543,22 @@ class Usecase:
parent = self.get_equivalent_existing_context(added_context.ParentContext)
if not parent:
parent = self.create_equivalent_context(added_context.ParentContext)
return ifcopenshell.api.context.add_context(
self.existing_contexts.append(parent)
context = ifcopenshell.api.context.add_context(
self.file,
parent=parent,
context_type=added_context.ContextType,
context_identifier=added_context.ContextIdentifier,
target_view=added_context.TargetView,
)
return ifcopenshell.api.context.add_context(
self.file,
context_type=added_context.ContextType,
context_identifier=added_context.ContextIdentifier,
)
else:
context = ifcopenshell.api.context.add_context(
self.file,
context_type=added_context.ContextType,
context_identifier=added_context.ContextIdentifier,
)
self.existing_contexts.append(context)
return context
def file_add(
self, element: ifcopenshell.entity_instance, conversion_factor: Optional[float] = None
+44 -6
View File
@@ -32,7 +32,8 @@ from typing import TYPE_CHECKING
from typing import Union
from typing import overload
from typing import Literal
from typing import Any
from typing import TypedDict
from typing_extensions import assert_never
from . import ifcopenshell_wrapper
from .entity_instance import entity_instance
@@ -42,6 +43,31 @@ from ifcopenshell.util.mvd_info import MvdInfo, LARK_AVAILABLE
if TYPE_CHECKING:
import ifcopenshell.util.schema
InverseReference = tuple[int, Any]
ElementInverses = dict[int, list[InverseReference]]
class CreateOperation(TypedDict):
action: Literal["create"]
value: Any
class EditOperation(TypedDict):
action: Literal["edit"]
id: int
index: int
old: Any
new: Any
class DeleteOperation(TypedDict):
action: Literal["delete"]
inverses: ElementInverses
value: Any
class BatchDeleteOperation(TypedDict):
action: Literal["batch_delete"]
inverses: ElementInverses
TransactionOperation = Union[CreateOperation, EditOperation, DeleteOperation, BatchDeleteOperation]
HEADER_FIELDS = {
"file_description": [
"description",
@@ -66,6 +92,10 @@ class UndoSystemError(Exception):
class Transaction:
operations: list[TransactionOperation]
batch_inverses: list[ElementInverses]
batch_delete_ids: set[int]
def __init__(self, ifc_file: file):
self.file: file = ifc_file
self.operations = []
@@ -80,14 +110,14 @@ class Transaction:
info[key] = self.serialise_value(element, value)
return info
def serialise_value(self, element, value):
def serialise_value(self, element, value) -> Any:
return element.walk(
lambda v: isinstance(v, entity_instance),
lambda v: {"id": v.id()} if v.id() else {"type": v.is_a(), "value": v.wrappedValue},
value,
)
def unserialise_value(self, element, value):
def unserialise_value(self, element, value) -> Any:
return element.walk(
lambda v: isinstance(v, dict),
lambda v: self.file.by_id(v["id"]) if v.get("id") else self.file.create_entity(v["type"], v["value"]),
@@ -137,10 +167,10 @@ class Transaction:
{"action": "delete", "inverses": inverses, "value": self.serialise_entity_instance(element)}
)
def get_element_inverses(self, element):
inverses = {}
def get_element_inverses(self, element: ifcopenshell.entity_instance) -> ElementInverses:
inverses: ElementInverses = {}
for inverse in self.file.get_inverse(element):
inverse_references = []
inverse_references: list[InverseReference] = []
for i, attribute in enumerate(inverse):
if self.has_element_reference(attribute, element):
inverse_references.append((i, self.serialise_value(inverse, attribute)))
@@ -187,6 +217,8 @@ class Transaction:
inverse = self.file.by_id(inverse_id)
for index, value in data:
inverse[index] = self.unserialise_value(inverse, value)
else:
assert_never(operation["action"])
def commit(self) -> None:
for operation in self.operations:
@@ -206,6 +238,8 @@ class Transaction:
self.file.remove(element)
elif operation["action"] == "batch_delete":
pass
else:
assert_never(operation["action"])
file_dict = {}
@@ -235,6 +269,10 @@ class file:
wrapped_data: ifcopenshell_wrapper.file
units: dict[str, entity_instance] = {}
history_size: int = 64
history: list[Transaction]
"""Chronological order - from oldest to newest."""
future: list[Transaction]
"""Reversed chronological order - from newest to oldest."""
to_delete: Union[set[ifcopenshell.entity_instance], None] = None
"""Entities for batch removal."""
@@ -23,7 +23,7 @@ import ifcopenshell
import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper
import ifcopenshell.util.attribute
import ifcopenshell.util.schema
from typing import Optional, Literal
from typing import Optional, Literal, Any, Union, TypedDict, NotRequired
try:
import glob
@@ -48,20 +48,44 @@ IFC4x3_HTML_LOCATION = BASE_MODULE_PATH / "IFC4.3-html"
IFC4x3_DEV_LOCATION = BASE_MODULE_PATH / "IFC4.3.x-development"
IFC4x3_SPEC_URL_TEMPLATE = "https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/%s.htm"
# entities schema
# entity -> description, spec_url, attributes[], predefined_types[]
# types schema
# type -> description, spec_url
class BaseData(TypedDict):
description: str
spec_url: str
class EntityData(BaseData):
attributes: NotRequired[dict[str, str]]
predefined_types: NotRequired[dict[str, str]]
class PsetData(TypedDict):
# Apparently some psets in ifc4 are missing spec url / description.
description: NotRequired[str]
spec_url: NotRequired[str]
properties: dict[str, str]
class PropertyData(TypedDict):
description: str
# in IFC4x3 there is no children[] for properties
children: NotRequired[dict[str, "PropertyData"]]
class ClassesSuggestions(TypedDict):
name: str
predefined_type: NotRequired[str]
class SchemaData(TypedDict):
entities: dict[str, EntityData]
types: dict[str, BaseData]
properties: dict[str, PsetData]
classes_suggestions: dict[str, ClassesSuggestions]
# properties schema
# pset/qset -> description, spec_url, properties[]
# property -> description, children[]
# child -> description
# note: in IFC4x3 there is no children[] for properties
SUPPORTED_SCHEMA = ifcopenshell.util.schema.IFC_SCHEMA
SCHEMA_FILES: dict[SUPPORTED_SCHEMA, dict] = {
SCHEMA_FILES: dict[SUPPORTED_SCHEMA, dict[str, Path]] = {
"IFC2X3": {
"entities": BASE_MODULE_PATH / "schema/ifc2x3_entities.json",
"properties": BASE_MODULE_PATH / "schema/ifc2x3_properties.json",
@@ -82,7 +106,7 @@ SCHEMA_FILES: dict[SUPPORTED_SCHEMA, dict] = {
},
}
db = None
db: dict[SUPPORTED_SCHEMA, SchemaData] = None
schema_by_name: dict[SUPPORTED_SCHEMA, Optional[ifcopenshell_wrapper.schema_definition]] = {
"IFC2X3": None,
"IFC4": None,
@@ -90,7 +114,7 @@ schema_by_name: dict[SUPPORTED_SCHEMA, Optional[ifcopenshell_wrapper.schema_defi
}
def get_db(version):
def get_db(version: ifcopenshell.util.schema.IFC_SCHEMA) -> Union[SchemaData, None]:
global db
if not db:
db = {ifc_version: dict() for ifc_version in SCHEMA_FILES}
@@ -117,7 +141,10 @@ def get_schema_by_name(version: str) -> ifcopenshell_wrapper.schema_definition:
return schema_by_name[version]
def get_class_suggestions(version, class_name):
def get_class_suggestions(
version: ifcopenshell.util.schema.IFC_SCHEMA,
class_name: str,
) -> Union[ClassesSuggestions, None]:
db = get_db(version)
if not db:
return
@@ -125,7 +152,11 @@ def get_class_suggestions(version, class_name):
return class_suggestions
def get_entity_doc(version, entity_name, recursive=True):
def get_entity_doc(
version: ifcopenshell.util.schema.IFC_SCHEMA,
entity_name: str,
recursive: bool = True,
) -> Union[EntityData, None]:
db = get_db(version)
if db:
entity = copy.deepcopy(db["entities"].get(entity_name))
@@ -144,37 +175,46 @@ def get_entity_doc(version, entity_name, recursive=True):
return entity
def get_attribute_doc(version, entity, attribute, recursive=True):
def get_attribute_doc(
version: ifcopenshell.util.schema.IFC_SCHEMA,
entity: str,
attribute: str,
recursive=True,
) -> Union[str, None]:
db = get_db(version)
if db:
entity = get_entity_doc(version, entity, recursive)
if entity:
return entity["attributes"].get(attribute)
entity_ = get_entity_doc(version, entity, recursive)
if entity_ and "attributes" in entity_:
return entity_["attributes"].get(attribute)
def get_predefined_type_doc(version, entity, predefined_type):
def get_predefined_type_doc(
version: ifcopenshell.util.schema.IFC_SCHEMA,
entity: str,
predefined_type: str,
) -> Union[str, None]:
db = get_db(version)
if db:
entity = db["entities"].get(entity)
if entity:
return entity.get("predefined_types", {}).get(predefined_type)
entity_ = db["entities"].get(entity)
if entity_:
return entity_.get("predefined_types", {}).get(predefined_type)
def get_property_set_doc(version, pset):
def get_property_set_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, pset: str) -> Union[PsetData, None]:
db = get_db(version)
if db:
return db["properties"].get(pset)
def get_property_doc(version, pset, prop):
def get_property_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, pset: str, prop: str) -> Union[str, None]:
db = get_db(version)
if db:
pset = db["properties"].get(pset)
if pset:
return pset["properties"].get(prop)
pset_ = db["properties"].get(pset)
if pset_:
return pset_["properties"].get(prop)
def get_type_doc(version, ifc_type):
def get_type_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, ifc_type: str) -> Union[BaseData, None]:
db = get_db(version)
if db:
return db["types"].get(ifc_type)
@@ -209,7 +249,7 @@ def get_inverse_attributes(el):
class DocExtractor:
def clean_highlighted_words(self, text):
def clean_highlighted_words(self, text: str) -> str:
text = re.sub(r"\b_([a-zA-Z0-9]+)_\b", r"\1", text)
text = re.sub(r"\*\*([a-zA-Z0-9]+)\*\*", r"\1", text)
return text
@@ -1255,10 +1255,15 @@ def get_aggregate(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.e
element = file.by_type("IfcBeam")[0]
aggregate = ifcopenshell.util.element.get_aggregate(element)
"""
if decomposes := getattr(element, "Decomposes", None):
is_not_ifc2x3 = element.file.schema != "IFC2X3"
if is_not_ifc2x3 or decomposes[0].is_a("IfcRelAggregates"):
return decomposes[0].RelatingObject
if not (decomposes := getattr(element, "Decomposes", None)):
return
is_ifc2x3 = element.file.schema == "IFC2X3"
rel: ifcopenshell.entity_instance = decomposes[0]
if is_ifc2x3 and not rel.is_a("IfcRelAggregates"):
# In IFCF2X3 Decomposes is used for both aggregates and nests,
# but only for 1 at the time.
return
return rel.RelatingObject
def get_nest(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
@@ -294,8 +294,13 @@ def resolve_representation(representation: ifcopenshell.entity_instance) -> ifco
:param representation: IfcRepresentation
:return: Representation resolved from mappings
"""
if len(representation.Items) == 1 and representation.Items[0].is_a("IfcMappedItem"):
return resolve_representation(representation.Items[0].MappingSource.MappedRepresentation)
# Tekla 2023 has missing items and mapped representation, though it's invalid IFC.
if (
len(representation.Items or []) == 1
and representation.Items[0].is_a("IfcMappedItem")
and (mapped_rep := representation.Items[0].MappingSource.MappedRepresentation)
):
return resolve_representation(mapped_rep)
return representation
@@ -41,6 +41,7 @@ def test_add_stationing_to_alignment():
alignment = ifcopenshell.api.alignment.create_alignment_by_pi_method(
file, "TestAlignment", coordinates, radii, vpoints, lengths
)
ifcopenshell.api.alignment.create_geometric_representation(file, alignment)
ifcopenshell.api.alignment.add_stationing_to_alignment(file, alignment, 2000.0)
@@ -54,3 +55,4 @@ def test_add_stationing_to_alignment():
ifcopenshell.util.element.get_pset(element=referent, name="Pset_Stationing", prop="Station")
== 2000.0
)
assert referent.ObjectPlacement != None
@@ -0,0 +1,45 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import pytest
import ifcopenshell.api.alignment
import ifcopenshell.api.context
import ifcopenshell.api.cogo
def test_add_survey_point():
file = ifcopenshell.file(schema="IFC4X3_ADD2")
project = file.createIfcProject(Name="Test")
site = file.createIfcSite(GlobalId=ifcopenshell.guid.new(),Name="MySite")
ifcopenshell.api.aggregate.assign_object(file,relating_object=project,products=[site])
geometric_representation_context = ifcopenshell.api.context.add_context(file, context_type="Model")
axis_model_representation_subcontext = ifcopenshell.api.context.add_context(
file,
context_type="Model",
context_identifier="Annotation",
target_view="MODEL_VIEW",
parent=geometric_representation_context,
)
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint((50.0,10.0)))
assert annotation
assert annotation.PredefinedType == "SURVEY"
assert annotation.Representation.Representations[0].RepresentationIdentifier == "Annotation"
assert annotation.Representation.Representations[0].RepresentationType == "Point"
assert annotation.Representation.Representations[0].Items[0].Coordinates == pytest.approx((50.0,10.0))
@@ -0,0 +1,48 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import pytest
import ifcopenshell.api.alignment
import ifcopenshell.api.context
import ifcopenshell.api.cogo
def test_assign_survey_point():
file = ifcopenshell.file(schema="IFC4X3_ADD2")
project = file.createIfcProject(Name="Test")
site = file.createIfcSite(GlobalId=ifcopenshell.guid.new(),Name="MySite")
ifcopenshell.api.aggregate.assign_object(file,relating_object=project,products=[site])
geometric_representation_context = ifcopenshell.api.context.add_context(file, context_type="Model")
axis_model_representation_subcontext = ifcopenshell.api.context.add_context(
file,
context_type="Model",
context_identifier="Annotation",
target_view="MODEL_VIEW",
parent=geometric_representation_context,
)
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint((50.0,10.0)))
assert annotation
assert annotation.PredefinedType == "SURVEY"
assert annotation.Representation.Representations[0].RepresentationIdentifier == "Annotation"
assert annotation.Representation.Representations[0].RepresentationType == "Point"
assert annotation.Representation.Representations[0].Items[0].Coordinates == pytest.approx((50.0,10.0))
ifcopenshell.api.cogo.assign_survey_point(annotation,file.createIfcCartesianPoint((20.0,30.0,40.0)))
assert annotation.Representation.Representations[0].Items[0].Coordinates == pytest.approx((20.0,30.0,40.0))
@@ -0,0 +1,48 @@
# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2025 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import pytest
import ifcopenshell.api.alignment
import ifcopenshell.api.context
import ifcopenshell.api.cogo
def test_edit_survey_point():
file = ifcopenshell.file(schema="IFC4X3_ADD2")
project = file.createIfcProject(Name="Test")
site = file.createIfcSite(GlobalId=ifcopenshell.guid.new(),Name="MySite")
ifcopenshell.api.aggregate.assign_object(file,relating_object=project,products=[site])
geometric_representation_context = ifcopenshell.api.context.add_context(file, context_type="Model")
axis_model_representation_subcontext = ifcopenshell.api.context.add_context(
file,
context_type="Model",
context_identifier="Annotation",
target_view="MODEL_VIEW",
parent=geometric_representation_context,
)
annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint((50.0,10.0)))
assert annotation
assert annotation.PredefinedType == "SURVEY"
assert annotation.Representation.Representations[0].RepresentationIdentifier == "Annotation"
assert annotation.Representation.Representations[0].RepresentationType == "Point"
assert annotation.Representation.Representations[0].Items[0].Coordinates == pytest.approx((50.0,10.0))
ifcopenshell.api.cogo.edit_survey_point(annotation,20.0,30.0)
assert annotation.Representation.Representations[0].Items[0].Coordinates == pytest.approx((20.0,30.0))
@@ -81,6 +81,29 @@ class TestAppendAssetIFC2X3(test.bootstrap.IFC2X3):
# make sure it's still valid
assert context.WorldCoordinateSystem
def test_add_new_contexts_if_necessary(self):
library = ifcopenshell.api.project.create_file(version=self.file.schema)
ifcopenshell.api.root.create_entity(library, ifc_class="IfcProject")
lib_context = ifcopenshell.api.context.add_context(library, context_type="Model")
lib_subcontext = ifcopenshell.api.context.add_context(
library, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=lib_context
)
# It has no contexts right now
ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcProject")
material = ifcopenshell.api.material.add_material(library, name="Material")
style = ifcopenshell.api.style.add_style(library)
ifcopenshell.api.style.assign_material_style(library, material=material, style=style, context=lib_subcontext)
ifcopenshell.api.project.append_asset(self.file, library=library, element=material)
assert len(self.file.by_type("IfcProject")) == 1
assert len(self.file.by_type("IfcGeometricRepresentationContext", include_subtypes=False)) == 1
assert len(self.file.by_type("IfcGeometricRepresentationSubContext", include_subtypes=False)) == 1
context = self.file.by_type("IfcMaterial")[0].HasRepresentation[0].Representations[0].ContextOfItems
# make sure it's still valid
assert context.WorldCoordinateSystem
def test_append_a_single_type_product_even_though_an_inverse_material_relationship_is_shared(self):
library = ifcopenshell.api.project.create_file(version=self.file.schema)
element = ifcopenshell.api.root.create_entity(library, ifc_class="IfcWallType")
@@ -66,7 +66,7 @@ class Patcher:
def patch(self) -> None:
self.qto_template_cache: dict[str, list[ifcopenshell.entity_instance]] = {}
templates_schema = self.file.schema
templates_schema = self.file.schema_identifier
# No official qto templates in IFC2X3, fallback to IFC4.
if templates_schema == "IFC2X3":
templates_schema = "IFC4"