Compare commits

..

3 Commits

Author SHA1 Message Date
Petru Conduraru 1f6e350b4c ci: drop toposort/igraph install, no longer needed after #8527
#8527 dropped Optimise's hard toposort dependency in favour of stdlib
graphlib as the fallback backend, so the pip install added here is now
dead weight: nothing in ifcpatch imports toposort any more, and igraph
was always an optional speed-up guarded by pytest.importorskip in
test_Optimise.py, never a hard requirement.

Verified against #8527's merged code (v0.8.0@382f5e0c21) with neither
package installed: all 6 test_Optimise.py tests pass or skip cleanly
(the two igraph-specific tests skip via importorskip instead of
erroring), so the install step served no remaining purpose.

This contribution was produced with the assistance of an AI coding tool.
2026-07-24 08:08:41 +03:00
Petru Conduraru a177a22885 ci: install toposort/igraph before the ifcpatch test step
test_Optimise.py (added in 57cfd9d1fd) exercises the Optimise recipe's
patch(), which since 7ebdd046b6 hard-requires the `toposort` package
as its fallback path (igraph is optional and its tests properly
pytest.importorskip when absent). ci.yml never installed either, so
every `cd ../ifcpatch && make test` run since 07-18 has been failing
with ModuleNotFoundError, contributing to the same "Test
ifcopenshell-python" step failure alongside the validate_stub crash
fixed in the previous commit.

Verified locally: test/test_Optimise.py's 6 tests (both the igraph and
pure-python toposort fallback paths) fail with ModuleNotFoundError
without these packages installed, and pass with them installed.

Generated with the assistance of an AI coding tool.
2026-07-23 09:41:41 +03:00
Petru Conduraru e57b5ac5ed ifcwrap: rename geometry backref helper to fix stub validation crash
The #1124 fix (824c1fc280) named its pythoncode backref helper
`_geometry_with_backref` with a leading underscore. validate_stub.py's
get_function_node_name() skips any leading-underscore name (its only
exception is `_is`), so the helper never gets added to the parsed
`subnames` set. When get_names_tree_lines() later processes
`geometry = property(_geometry_with_backref)`, find_method_by_name()
can't find the backing function and the `assert (wrapped_function :=
find_method_by_name(arg))` at validate_stub.py:154 raises AssertionError
instead of the expected clean stub/wrapper diff, crashing the CI
`ci.yml` -> compile-and-test -> "Test ifcopenshell-python" step
(`make test-parallel`) on every push since 824c1fc280.

Renaming to `geometry_with_backref_` (trailing underscore) matches the
existing local convention in the same class bodies for backing-
implementation helpers (calc_volume_, calc_surface_area_), which
validate_stub.py's heuristic already handles correctly.

Also add the six new SVG edge-classification settings-flag classes
(SvgEmitFlushEdges, SvgRenderCreaseEdges, SvgRenderSharpEdges,
SvgRidgeAngleMinDegrees, SvgUseEdgeClassification,
SvgValleyAngleMinDegrees) to ifcopenshell_wrapper.pyi. These were added
to the C++/SWIG side by the SVG edge classification commits but never
synced to the stub, and validate_stub would report them as a
stub/wrapper discrepancy once the crash above is fixed.

Reproduced by building ifcopenshell against the exact CI-tested commit
(c68e4a0eee) with SWIG 4.1.0 (matching ci.yml's pinned build-from-source
version) and running validate_stub.py's actual logic against the
generated ifcopenshell_wrapper.py: crashed identically to the CI log
before this change, passed cleanly after. test/util/scripts/test_validate_stub.py::TestValidateStub::test_run
passes against the rebuilt wrapper.

Generated with the assistance of an AI coding tool.
2026-07-23 09:41:41 +03:00
165 changed files with 768 additions and 5245 deletions
+2 -2
View File
@@ -21,12 +21,12 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
- name: Checkout Build Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/build-outputs
path: ./build
+2 -2
View File
@@ -9,13 +9,13 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
path: IfcOpenShell
- name: Checkout Build Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/build-outputs
path: ifcopenshell_build
+2 -2
View File
@@ -35,12 +35,12 @@ jobs:
aws --version
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
- name: Checkout Build Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/build-outputs
path: ./build
+2 -2
View File
@@ -35,12 +35,12 @@ jobs:
aws --version
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
- name: Checkout Build Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/build-outputs
path: ./build
+2 -2
View File
@@ -27,12 +27,12 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
- name: Checkout Build Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/build-outputs
path: ${{ matrix.deps_dir }}
+2 -2
View File
@@ -19,8 +19,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7 # https://github.com/actions/checkout
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6 # https://github.com/actions/checkout
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
fetch-tags: true
fetch-depth: 0
+3 -3
View File
@@ -65,8 +65,8 @@ jobs:
config:
short_name: macos
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
python-version: '3.11'
@@ -98,7 +98,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout bonsai_unstable_repo repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/bonsai_unstable_repo
token: ${{ secrets.IFCOPENBOT_TOKEN }}
+2 -2
View File
@@ -48,8 +48,8 @@ jobs:
config:
short_name: macos
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
python-version: '3.11'
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -37,8 +37,8 @@ jobs:
short_name: macosm164
}
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.11'
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.11'
- name: Compile
@@ -21,7 +21,7 @@ jobs:
date: ${{ steps.date.outputs.date }}
verdate: ${{ steps.verdate.outputs.verdate }}
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- name: Set env
run: echo ok go
@@ -75,7 +75,7 @@ jobs:
echo "ARTIFACTS_DIR=/home/runner/work/artifacts" >> $GITHUB_ENV
fi
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
+2 -2
View File
@@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-22.04
needs: activate
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
@@ -86,7 +86,7 @@ jobs:
name: Docker Build, Tag, Push
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
lfs: true
@@ -47,10 +47,10 @@ jobs:
short_name: macosm164
}
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
+2 -2
View File
@@ -38,10 +38,10 @@ jobs:
short_name: macosm164
}
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.11'
- name: Compile
+2 -2
View File
@@ -25,8 +25,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
python-version: '3.11'
+2 -2
View File
@@ -19,8 +19,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
architecture: 'x64' # optional x64 or x86. Defaults to x64 if not specified
python-version: '3.11'
+2 -2
View File
@@ -10,9 +10,9 @@ jobs:
publish_website:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- name: Checkout ifctester_org_static_html
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/ifctester_org_static_html
token: ${{ secrets.IFCOPENBOT_TOKEN }}
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7 # https://github.com/actions/setup-python
- uses: actions/checkout@v6
- uses: actions/setup-python@v6 # https://github.com/actions/setup-python
with:
python-version: '3.11' # Version range or exact version of a Python version to use, using SemVer's version range syntax
- name: Compile
+3 -3
View File
@@ -34,7 +34,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
@@ -85,7 +85,7 @@ jobs:
cmake --build build-ifcopenshell --target install -j "$(nproc)"
- name: Set up Python 3.11
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: 3.11
@@ -120,7 +120,7 @@ jobs:
PY
- name: Set up Python 3.12
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: 3.12
+3 -3
View File
@@ -12,15 +12,15 @@ jobs:
MIN_BLENDER_PY_VERSION: "3.11"
steps:
- name: Action - checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v6
- name: Action - install python
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: ${{ env.MIN_IOS_PY_VERSION }}
- name: Action - install python
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: ${{ env.MIN_BLENDER_PY_VERSION }}
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout IfcOpenShell
uses: actions/checkout@v7
uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v7
@@ -25,7 +25,7 @@ jobs:
echo "name=$(basename $WHEEL)" >> $GITHUB_OUTPUT
- name: Checkout wasm-wheels
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/wasm-wheels
path: wasm-wheels
+4 -6
View File
@@ -43,12 +43,12 @@ jobs:
CLICOLOR_FORCE: "1"
CMAKE_COLOR_DIAGNOSTICS: "ON"
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
with:
submodules: recursive
- name: Set up Python
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: 3.11
@@ -257,15 +257,13 @@ jobs:
cd ../ifcdiff && make test || ERROR=1
cd ../ifcpatch && make test || ERROR=1
pip install -e ../ifc5d --no-deps
pip install odfpy openpyxl
pip install odfpy xlsxwriter
cd ../ifc5d && make test || ERROR=1
pip install -e ../ifcquery --no-deps
cd ../ifcquery && make test || ERROR=1
pip install -e ../ifcedit --no-deps
cd ../ifcedit && make test || ERROR=1
# Pinned <2: mcp 2.0.0 renamed mcp.server.fastmcp.FastMCP to
# mcp.server.mcpserver.MCPServer, which ifcmcp doesn't support yet.
pip install "mcp>=1.0,<2"
pip install mcp
pip install -e ../ifcmcp --no-deps
cd ../ifcmcp && make test || ERROR=1
pip install -e ../ifctester --no-deps
@@ -11,10 +11,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: '3.x'
+3 -3
View File
@@ -27,12 +27,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout (recursive)
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
fetch-depth: 0
- name: Checkout intermediate Pages repo
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/aichat_ifcopenshell_org_static_html
ref: gh-pages
@@ -42,7 +42,7 @@ jobs:
run: |
rsync -av --delete --exclude='.git/' src/ifcchat/ output/
- name: Setup Python
uses: actions/setup-python@v7
uses: actions/setup-python@v6
with:
python-version: "3.x"
- name: Download wheels
@@ -7,7 +7,7 @@ jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- uses: astral-sh/setup-uv@v7
@@ -27,12 +27,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout (recursive)
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
fetch-depth: 0
- name: Checkout intermediate Pages repo
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
repository: IfcOpenShell/wasm_ifcopenshell_org_static_html
ref: gh-pages
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
submodules: recursive
- name: Install C++ dependencies
+1 -1
View File
@@ -3,7 +3,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
<metadata>
<id>blenderbim-nightly</id>
<version>blenderbim_build_version</version>
<version>blenderbim_build_version-alpha</version>
<packageSourceUrl>https://github.com/IfcOpenShell/IfcOpenShell</packageSourceUrl>
<owners>fbpyr</owners>
<!-- == SOFTWARE SPECIFIC SECTION == -->
+11 -14
View File
@@ -3,12 +3,11 @@
apt update && apt install git wget curl ptpython mono-devel micro
mkdir -p /home/runner/work/IfcOpenShell && cd /home/runner/work/IfcOpenShell
git clone https://github.com/IfcOpenShell/IfcOpenShell
cd /home/runner/work/IfcOpenShell/IfcOpenShell/choco/bonsai/
cd /home/runner/work/IfcOpenShell/IfcOpenShell/choco/blenderbim/
micro choco_release.py # paste this script, comment out push command
export CHOCO_TOKEN="secret_choco_release_token"
python3 choco_release.py
"""
import datetime
import hashlib
import os
@@ -29,7 +28,7 @@ def get_repo_tag_names() -> list[str]:
def request_repo_info(url: str):
req = request.Request(url)
req = request.Request(url)
resp = request.urlopen(req)
if not resp.status == 200:
print(f"[ERROR] could not contact server: {url}")
@@ -86,15 +85,13 @@ def run(command: str) -> None:
start = datetime.datetime.now()
URL_CHOCO_PACKAGE = "https://community.chocolatey.org/packages/blender"
URL_BLENDER_CMAKE = (
"https://raw.githubusercontent.com/blender/blender/{}/build_files/cmake/Modules/FindPythonLibsUnix.cmake"
)
RE_BLENDER_VERSION_MIN_MAJ = r"Latest Version.+<span>Blender (\d+\.\d+)\..+</span>"
RE_BLENDER_VERSION_MIN_MAJ_PAT = r"Latest Version.+<span>Blender (\d+\.\d+\.\d+)</span>"
URL_CHOCO_PACKAGE = "https://community.chocolatey.org/packages/blender"
URL_BLENDER_CMAKE = "https://raw.githubusercontent.com/blender/blender/{}/build_files/cmake/Modules/FindPythonLibsUnix.cmake"
RE_BLENDER_VERSION_MIN_MAJ = r"Latest Version.+<span>Blender (\d+\.\d+)\..+</span>"
RE_BLENDER_VERSION_MIN_MAJ_PAT = r"Latest Version.+<span>Blender (\d+\.\d+\.\d+)</span>"
RE_BLENDER_PYTHON_VERSION_MAJ_MIN = r"\(_PYTHON_VERSION_SUPPORTED (\d+\.\d+)\)"
BLENDERBIM_DIR = pathlib.Path("/home/runner/work/IfcOpenShell/IfcOpenShell/choco/bonsai/")
BLENDERBIM_DIR = pathlib.Path("/home/runner/work/IfcOpenShell/IfcOpenShell/choco/blenderbim/")
print("_____ check choco release needed?")
@@ -151,7 +148,7 @@ print(f"{blender_python_version_maj_min=}")
python_version = f"py{found[0].replace('.', '')}"
print(f"{python_version=}")
blenderbim_build_version = target_release_tag.replace("bonsai-", "")
blenderbim_build_version = target_release_tag.replace("blenderbim-", "")
# url_blenderbim_py3x_win_zip
release_zip_file_name, url_blenderbim_py3x_win_zip = get_release_zip(target_release_tag)
@@ -169,15 +166,15 @@ topics = {
"path": HERE_DIR / "blenderbim.nuspec",
"key_values": {
"latest_blender_version_maj_min_pat": latest_blender_release_maj_min_pat,
"blenderbim_build_version": blenderbim_build_version,
"blenderbim_build_version" : blenderbim_build_version,
},
},
"install": {
"path": HERE_DIR / "tools" / "chocolateyinstall.ps1",
"key_values": {
"url_blenderbim_py3x_win_zip": url_blenderbim_py3x_win_zip,
"url_blenderbim_py3x_win_zip" : url_blenderbim_py3x_win_zip,
"sha256sum_blenderbim_py3x_win_zip": sha256sum_blenderbim_py3x_win_zip,
"latest_blender_version_maj_min": blender_version_min_maj,
"latest_blender_version_maj_min" : blender_version_min_maj,
},
},
"uninstall": {
+2 -5
View File
@@ -121,7 +121,7 @@ import tarfile
import threading
from datetime import datetime
ssl._create_default_https_context = ssl._create_unverified_context # ty:ignore[invalid-assignment]
ssl._create_default_https_context = ssl._create_unverified_context
import time
from collections.abc import Generator, Sequence
@@ -697,10 +697,7 @@ def build_dependency(
compr = "xz"
else:
raise RuntimeError("fix source for new download type")
# ty: false positive bug upstream.
download_tarfile = tarfile.open(
name=download_tarfile_path, mode=f"r:{compr}"
) # ty:ignore[no-matching-overload]
download_tarfile = tarfile.open(name=download_tarfile_path, mode=f"r:{compr}")
# tarfile seriously doesn't have a function to retrieve the root directory more easily
extract_dir_name = os.path.commonprefix([x for x in download_tarfile.getnames() if x != "."])
# run([tar, "--exclude=\"*/*\"", "-tf", download_name], cwd=build_dir).strip() no longer works
+3 -3
View File
@@ -1,5 +1,5 @@
black==26.3.1
ruff==0.16.0
ruff==0.15.22
poethepoet
ty==0.0.63
gersemi==0.28.0
ty==0.0.61
gersemi==0.26.1
+6 -52
View File
@@ -10,7 +10,6 @@ if bonsai_lib_path:
import argparse
import base64
import json
import urllib.parse
import xml.etree.ElementTree as ET
import pystache
@@ -19,53 +18,8 @@ from aiohttp import web
sio_port = 8080 # default port
def get_asset_version() -> str:
"""A cache-busting token appended to locally served static asset URLs.
Browsers otherwise keep serving a stale cached copy of static/js and
static/css after Bonsai ships a code change, until the user does a hard
refresh. Using the Bonsai version (which includes the build's commit
hash) means the token changes on every shipped update.
"""
if bonsai_version:
return urllib.parse.quote(bonsai_version, safe="")
# Fallback for standalone runs without BONSAI_VERSION set (e.g. running
# sioserver.py directly outside of Blender): derive a token from the
# newest mtime among the static assets, so it still changes whenever the
# shipped files change.
static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
latest_mtime = 0
for root, _dirs, files in os.walk(static_dir):
for name in files:
latest_mtime = max(latest_mtime, int(os.path.getmtime(os.path.join(root, name))))
return f"dev-{latest_mtime}"
asset_version = get_asset_version()
@web.middleware
async def no_cache_static_middleware(request: web.Request, handler):
"""Force revalidation of locally served static assets.
Query-string version stamping (see `asset_version`) busts the cache for
the HTML-referenced entry points, but JS files that statically import
other local modules (e.g. cost.js/gantt.js importing utilities/costui.js)
reference those modules by an un-stamped relative path. Marking all
/static/ and /jsgantt/ responses as no-cache makes browsers always
revalidate with the server (a cheap conditional GET / 304 when nothing
changed), so nested imports also pick up shipped changes without
requiring a hard refresh.
"""
response = await handler(request)
if request.path.startswith("/static/") or request.path.startswith("/jsgantt/"):
response.headers["Cache-Control"] = "no-cache, must-revalidate"
return response
sio = socketio.AsyncServer(cors_allowed_origins="*", async_mode="aiohttp", max_http_buffer_size=10000000)
app = web.Application(middlewares=[no_cache_static_middleware])
app = web.Application()
sio.attach(app)
@@ -245,28 +199,28 @@ class BlenderNamespace(socketio.AsyncNamespace):
async def schedules(request):
with open("templates/index.html", "r") as f:
template = f.read()
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version, "v": asset_version})
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version})
return web.Response(text=html_content, content_type="text/html")
async def costing(request):
with open("templates/costing.html", "r") as f:
template = f.read()
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version, "v": asset_version})
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version})
return web.Response(text=html_content, content_type="text/html")
async def sequencing(request):
with open("templates/gantt.html", "r") as f:
template = f.read()
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version, "v": asset_version})
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version})
return web.Response(text=html_content, content_type="text/html")
async def documentation(request):
with open("templates/drawings.html", "r") as f:
template = f.read()
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version, "v": asset_version})
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version})
return web.Response(text=html_content, content_type="text/html")
@@ -275,7 +229,7 @@ async def documentation(request):
async def demo(request):
with open("templates/demo.html", "r") as f:
template = f.read()
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version, "v": asset_version})
html_content = pystache.render(template, {"port": sio_port, "version": bonsai_version})
return web.Response(text=html_content, content_type="text/html")
@@ -250,14 +250,6 @@ export class CostUI {
},
});
CostUI.addRibbonButton({
text: "Download CSV",
icon: "fa-solid fa-file-csv",
callback: () => {
CostUI.downloadCsv();
},
});
CostUI.addRibbonButton({
text: "Hide Schedules",
icon: "fa-regular fa-eye-slash",
@@ -531,81 +523,6 @@ export class CostUI {
}
}
static downloadCsv() {
const tables = document.querySelectorAll("table[id^='cost-items-']");
if (tables.length === 0) {
alert("No cost schedule loaded to export!");
return;
}
tables.forEach((table) => {
const scheduleId = table.id.split("-").pop();
const csv = CostUI.tableToCsv(table);
if (csv === null) {
return;
}
const nameEl = document.querySelector(
"#cost-schedule-container-" + scheduleId + " .form-header span"
);
const scheduleName = nameEl
? nameEl.textContent
: "cost_schedule_" + scheduleId;
CostUI.triggerCsvDownload(csv, scheduleName + ".csv");
});
}
static tableToCsv(table) {
const escapeCsvCell = (value) => {
const text = (value === null || value === undefined ? "" : value)
.toString()
.trim();
if (/[",\n]/.test(text)) {
return '"' + text.replace(/"/g, '""') + '"';
}
return text;
};
const cellText = (cell) => {
const input = cell.querySelector("input");
return input ? input.value : cell.innerText;
};
// The Actions column only holds buttons (edit/delete/etc), not data.
const isDataColumn = (column) => column && column !== "Actions";
const headerCells = Array.from(table.querySelectorAll("thead th")).filter(
(th) => isDataColumn(th.getAttribute("data-column"))
);
if (headerCells.length === 0) {
return null;
}
const rows = [headerCells.map((th) => escapeCsvCell(th.textContent)).join(",")];
table.querySelectorAll("tbody tr").forEach((row) => {
const cells = Array.from(row.children).filter((cell) =>
isDataColumn(cell.getAttribute("data-column"))
);
if (cells.length === 0) {
return; // e.g. the "No cost items found" placeholder row.
}
rows.push(cells.map((cell) => escapeCsvCell(cellText(cell))).join(","));
});
return rows.join("\n");
}
static triggerCsvDownload(csvContent, filename) {
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
static createCostTable({ costSchedule, currency, callbacks }) {
const preferences = CostUI.getColumnPreferences();
const isScheduleOfRates = costSchedule.PredefinedType === "SCHEDULEOFRATES";
@@ -7,7 +7,7 @@
<link
rel="stylesheet"
type="text/css"
href="/static/css/cost.css?v={{v}}"
href="/static/css/cost.css"
id="index-stylesheet"
/>
<link
@@ -21,7 +21,7 @@
/>
<script
type="text/javascript"
src="/static/js/jquery.min.js?v={{v}}"
src="/static/js/jquery.min.js"
></script>
<script
type="text/javascript"
@@ -34,7 +34,7 @@
<script>
var SOCKET_PORT = {{port}};
</script>
<script type="module" defer src="./static/js/cost.js?v={{v}}"></script>
<script type="module" defer src="./static/js/cost.js"></script>
</head>
<body>
<nav>
@@ -12,14 +12,14 @@
/>
<!-- here we request the CSS file from the server, -->
<!-- using registered static path in the server -->
<link rel="stylesheet" href="/static/css/demo.css?v={{v}}" id="demo-stylesheet" />
<link rel="stylesheet" href="/static/css/demo.css" id="demo-stylesheet" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"
/>
<script
type="text/javascript"
src="/static/js/jquery.min.js?v={{v}}"
src="/static/js/jquery.min.js"
></script>
<script
type="text/javascript"
@@ -33,7 +33,7 @@
</script>
<!-- here we request the JS file from the server-->
<!-- using registered static path in the server -->
<script defer src="./static/js/demo.js?v={{v}}"></script>
<script defer src="./static/js/demo.js"></script>
</head>
<body>
<!-- the navigation bar at the top of the page. -->
@@ -15,7 +15,7 @@
/>
<link
rel="stylesheet"
href="/static/css/drawings.css?v={{v}}"
href="/static/css/drawings.css"
id="drawings-stylesheet"
/>
<link
@@ -24,7 +24,7 @@
/>
<script
type="text/javascript"
src="/static/js/jquery.min.js?v={{v}}"
src="/static/js/jquery.min.js"
></script>
<script
type="text/javascript"
@@ -45,7 +45,7 @@
<script>
var SOCKET_PORT = {{port}};
</script>
<script defer src="./static/js/drawings.js?v={{v}}"></script>
<script defer src="./static/js/drawings.js"></script>
</head>
<body>
<nav>
@@ -9,25 +9,25 @@
type="image/x-icon"
href="https://bonsaibim.org/assets/images/favicon-blender.png"
/>
<link rel="stylesheet" type="text/css" href="/jsgantt/jsgantt.css?v={{v}}" />
<link rel="stylesheet" href="/static/css/gantt.css?v={{v}}" id="gantt-stylesheet" />
<link rel="stylesheet" type="text/css" href="/jsgantt/jsgantt.css" />
<link rel="stylesheet" href="/static/css/gantt.css" id="gantt-stylesheet" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"
/>
<script
type="text/javascript"
src="/static/js/jquery.min.js?v={{v}}"
src="/static/js/jquery.min.js"
></script>
<script
type="text/javascript"
src="https://cdn.socket.io/4.0.0/socket.io.min.js"
></script>
<script type="text/javascript" src="./jsgantt/jsgantt.js?v={{v}}"></script>
<script type="text/javascript" src="./jsgantt/jsgantt.js"></script>
<script>
var SOCKET_PORT = {{port}};
</script>
<script type="module" defer src="./static/js/gantt.js?v={{v}}"></script>
<script type="module" defer src="./static/js/gantt.js"></script>
</head>
<body>
<nav class="no-print">
@@ -9,7 +9,7 @@
type="image/x-icon"
href="https://bonsaibim.org/assets/images/favicon-blender.png"
/>
<link rel="stylesheet" href="/static/css/index.css?v={{v}}" id="index-stylesheet" />
<link rel="stylesheet" href="/static/css/index.css" id="index-stylesheet" />
<link
rel="stylesheet"
id="tabulator-stylesheet"
@@ -21,7 +21,7 @@
/>
<script
type="text/javascript"
src="/static/js/jquery.min.js?v={{v}}"
src="/static/js/jquery.min.js"
></script>
<script
type="text/javascript"
@@ -34,7 +34,7 @@
<script>
var SOCKET_PORT = {{port}};
</script>
<script defer src="./static/js/index.js?v={{v}}"></script>
<script defer src="./static/js/index.js"></script>
</head>
<body>
<nav>
+3 -4
View File
@@ -418,10 +418,9 @@ def get_user(ifc: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None
def viewport_shading_changed_callback(area: bpy.types.Area) -> None:
shading_type = area.spaces.active.shading.type
tool.Style.restore_material_style_types(shading_type)
if shading_type == "SOLID":
area.spaces.active.shading.color_type = "MATERIAL"
shading = area.spaces.active.shading.type
if shading == "RENDERED":
tool.Style.get_style_props().active_style_type = "External"
def subscribe_to_viewport_shading_changes():
+5 -2
View File
@@ -236,8 +236,11 @@ def import_attribute(
elif data_type == "integer":
new.int_value = 0 if new.is_null else int(data[attribute.name()])
elif data_type == "float":
measure_class = attribute.type_of_attribute().declared_type().name()
new.special_type = tool.Pset.get_special_type_for_measure_class(measure_class)
attribute_type = attribute.type_of_attribute()
if attribute_type._is("IfcLengthMeasure"):
new.special_type = "LENGTH"
elif attribute_type._is("IfcForceMeasure"):
new.special_type = "FORCE"
new.float_value = 0.0 if new.is_null else float(data[attribute.name()])
elif data_type == "enum":
attribute_type = attribute.type_of_attribute()
+4
View File
@@ -133,6 +133,10 @@ class MaterialCreator:
if shape_has_openings and coords.is_a("IfcIndexedTextureMap"):
continue
tool.Loader.load_indexed_map(coords, self.mesh)
elif tool.Style.get_texture_style(material):
# No explicit coordinate mapping (e.g. IFC2X3 has no IsMappedBy,
# and IFC4 COORD uses generated UVs). Bake XY→UV as fallback.
tool.Loader.load_generated_uv_map(self.mesh)
def assign_material_slots_to_faces(self) -> None:
if not self.mesh["ios_materials"]:
+1 -1
View File
@@ -162,7 +162,7 @@ class ProjectLibraryData:
library_file = IfcStore.library_file
if library_file is None or library_file.schema == "IFC2X3":
return results
root = library_file.by_type("IfcProject")[0]
root = tool.Project.get_root_context(library_file)
results.append((str(root.id()), f"{root.is_a()} {root.Name or 'Unnamed'}", root.Description or ""))
for library_id, data in cls.data["project_libraries"].items():
results.append((str(library_id), data["Name"] or "Unnamed", data["Description"] or ""))
@@ -281,7 +281,7 @@ class RefreshLibrary(bpy.types.Operator):
elements = {e for e in elements if not tool.Project.is_element_assigned_to_project_library(e, rels)}
self.props.add_library_project_library("Unassigned", len(elements), 0, False)
root_context = library_file.by_type("IfcProject")[0]
root_context = tool.Project.get_root_context(library_file)
hierarchy = tool.Project.get_project_hierarchy(library_file)
tool.Project.load_project_libraries_to_ui(root_context, hierarchy)
return {"FINISHED"}
@@ -761,22 +761,21 @@ class EditProjectLibrary(bpy.types.Operator):
attributes = bonsai.bim.helper.export_attributes(props.project_library_attributes)
ifcopenshell.api.attribute.edit_attributes(library_file, project_library, attributes)
# Update parent library. Tear down the old IfcRelDeclares/IfcRelNests before
# creating the new one; a library must have exactly one of the two, never both.
# Update parent library.
previous_parent_library = tool.Project.get_parent_library(project_library)
new_parent_library = library_file.by_id(int(props.parent_library))
if previous_parent_library != new_parent_library:
if previous_parent_library is not None:
if previous_parent_library.is_a("IfcProject"):
ifcopenshell.api.project.unassign_declaration(
library_file, [project_library], previous_parent_library
)
else:
ifcopenshell.api.nest.unassign_object(library_file, [project_library])
if new_parent_library.is_a("IfcProject"):
ifcopenshell.api.project.assign_declaration(library_file, [project_library], new_parent_library)
else:
if previous_parent_library is None:
# Edited library was a root in a library-only file; nest it under the new parent.
ifcopenshell.api.nest.assign_object(library_file, [project_library], new_parent_library)
elif previous_parent_library.is_a("IfcProject"):
# Then new one is IfcProjectLibrary.
ifcopenshell.api.nest.assign_object(library_file, [project_library], new_parent_library)
else: # Previous is IfcProjectLibrary.
ifcopenshell.api.nest.unassign_object(library_file, [project_library])
# If new one is IfcProject, then it's already assigned by default.
if new_parent_library.is_a("IfcProjectLibrary"):
ifcopenshell.api.nest.assign_object(library_file, [project_library], new_parent_library)
props.is_editing_project_library = False
bpy.ops.bim.refresh_library()
@@ -810,9 +809,12 @@ class AddProjectLibrary(bpy.types.Operator):
props = tool.Project.get_project_props()
library_file = IfcStore.library_file
assert library_file
root_context = library_file.by_type("IfcProject")[0]
root_context = tool.Project.get_root_context(library_file)
project_library = ifcopenshell.api.root.create_entity(library_file, "IfcProjectLibrary")
ifcopenshell.api.project.assign_declaration(library_file, [project_library], root_context)
if root_context.is_a("IfcProject"):
ifcopenshell.api.project.assign_declaration(library_file, [project_library], root_context)
else:
ifcopenshell.api.nest.assign_object(library_file, [project_library], root_context)
ProjectLibraryData.load() # Update enum.
props.selected_project_library = str(project_library.id())
props.is_editing_project_library = True
@@ -1299,10 +1301,6 @@ class LoadProjectElements(bpy.types.Operator):
tool.Project.set_default_modeling_dimensions()
tool.Root.reload_grid_decorator()
bonsai.bim.handler.refresh_ui_data()
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == "VIEW_3D":
bonsai.bim.handler.viewport_shading_changed_callback(area)
return {"FINISHED"}
def get_decomposition_elements(self) -> set[ifcopenshell.entity_instance]:
@@ -1580,13 +1578,10 @@ class LoadLink(bpy.types.Operator, tool.Ifc.Operator):
json_filepath = self.filepath_.with_suffix(".ifc.cache.json")
def should_clear_cache() -> bool:
# Nothing to clear if the cache file was never created (e.g. a
# fresh link). Check this first so os.remove below is never
# called on a non-existent path, regardless of use_cache.
if not blend_filepath.exists():
return False
if not self.use_cache:
return True
if not blend_filepath.exists():
return False
data = json.loads(json_filepath.read_text())
# Empty 'query' - model loaded without custom query.
# Missing 'query' - model was loaded before custom queries were introduced in Bonsai.
+2 -17
View File
@@ -54,7 +54,7 @@ class Data:
ifc_file = tool.Ifc.get()
results = []
psetqtos = ifcopenshell.util.element.get_psets(
element, psets_only=psets_only, qtos_only=qtos_only, should_inherit=False, verbose=True
element, psets_only=psets_only, qtos_only=qtos_only, should_inherit=False
)
for name, data in sorted(psetqtos.items()):
pset = ifc_file.by_id(data["id"])
@@ -69,28 +69,13 @@ class Data:
"id": data["id"],
"Name": name,
"is_expanded": is_expanded.get(data["id"], True),
"Properties": [
cls.property_display_data(ifc_file, k, v) for k, v in sorted(data.items()) if k != "id"
],
"Properties": [{"Name": k, "NominalValue": v} for k, v in sorted(data.items()) if k != "id"],
"shared_pset_uses": len(pset_uses),
"has_template": has_template,
}
)
return sorted(results, key=lambda v: v["Name"])
@classmethod
def property_display_data(cls, ifc_file: ifcopenshell.file, name: str, verbose_value: Any) -> dict[str, Any]:
# Predefined property sets (e.g. IfcDoorPanelProperties) expose plain
# attribute values even in verbose mode, since they're typed IFC
# attributes rather than IfcProperty entities with their own id/Unit.
if not isinstance(verbose_value, dict):
return {"Name": name, "NominalValue": verbose_value, "UnitSymbol": ""}
unit_symbol = ""
if (prop_id := verbose_value.get("id")) and (prop_entity := ifc_file.by_id(prop_id)):
unit_symbol = tool.Pset.get_unit_symbol_for_prop(prop_entity, ifc_file)
return {"Name": name, "NominalValue": verbose_value["value"], "UnitSymbol": unit_symbol}
@classmethod
def format_pset_enum(cls, psets):
enum_items = []
+9 -24
View File
@@ -120,20 +120,13 @@ class EditPset(bpy.types.Operator, tool.Ifc.Operator):
properties = json.loads(self.properties)
else:
for prop in props.properties:
metadata = prop.metadata
if prop.value_type == "IfcPropertySingleValue":
value = metadata.get_value()
properties[prop.metadata.name] = prop.metadata.get_value()
elif prop.value_type == "IfcPropertyEnumeratedValue":
value_name = metadata.get_value_name()
value = [e[value_name] for e in prop.enumerated_value.enumerated_values if e.is_selected]
else:
continue
# None (a purge/skip-creation signal, handled by edit_pset/edit_qto before any
# unit wrapping is unpacked) must stay bare -- only wrap real values.
if value is not None and tool.Pset.is_measurable_special_type(metadata.special_type):
unit = self.file.by_id(metadata.unit_id) if metadata.unit_id else None
value = {"NominalValue": value, "Unit": unit}
properties[metadata.name] = value
value_name = prop.metadata.get_value_name()
properties[prop.metadata.name] = [
e[value_name] for e in prop.enumerated_value.enumerated_values if e.is_selected
]
if pset.is_a() in ("IfcPropertySet", "IfcMaterialProperties", "IfcProfileProperties"):
ifcopenshell.api.pset.edit_pset(
@@ -147,18 +140,10 @@ class EditPset(bpy.types.Operator, tool.Ifc.Operator):
for key, value in properties.items():
if value is None:
continue
is_wrapped = isinstance(value, dict) and "Unit" in value
raw = value["NominalValue"] if is_wrapped else value
if raw is None:
continue
if isinstance(raw, float):
raw = round(raw, 4)
elif not isinstance(raw, int):
raw = 0
if is_wrapped:
value["NominalValue"] = raw
else:
properties[key] = raw
if isinstance(value, float):
properties[key] = round(value, 4)
elif not isinstance(value, int):
properties[key] = 0
ifcopenshell.api.pset.edit_qto(
self.file,
qto=pset,
+3 -8
View File
@@ -67,10 +67,6 @@ def draw_single_property(prop: IfcProperty, layout: bpy.types.UILayout, copy_ope
if prop.metadata.special_type == "URI":
op = layout.operator("bim.select_uri_attribute", text="", icon="FILE_FOLDER")
op.attribute_data_path = tool.Blender.get_full_data_path(prop.metadata)
if tool.Pset.is_measurable_special_type(prop.metadata.special_type):
unit_row = layout.row(align=True)
unit_row.scale_x = 0.5
prop_with_search(unit_row, prop.metadata, "unit_id_enum", text="")
if prop.metadata.is_optional:
layout.prop(prop.metadata, "is_null", icon="RADIOBUT_OFF" if prop.metadata.is_null else "RADIOBUT_ON", text="")
if copy_operator:
@@ -207,10 +203,9 @@ def draw_psetqto_ui(
row = box.row(align=True)
row.scale_y = 0.8
row.label(text=prop["Name"])
display_value = get_display_value(nominal_value)
if unit_symbol := prop["UnitSymbol"]:
display_value = f"{display_value} {unit_symbol}"
op = row.operator("bim.select_similar", text=display_value, icon="NONE", emboss=False)
op = row.operator(
"bim.select_similar", text=get_display_value(nominal_value), icon="NONE", emboss=False
)
op.key = '"' + pset["Name"].replace('"', '\\"') + '"."' + prop["Name"].replace('"', '\\"') + '"'
# calculate sum of all selected objects
if active_operator:
+2 -2
View File
@@ -151,7 +151,7 @@ class CalculateSingleQuantity(bpy.types.Operator, tool.Ifc.Operator):
ifc_file = tool.Ifc.get()
with Profiler("Quantify function time:"):
results = ifc5d.qto.quantify(ifc_file, elements, rules)
ifc5d.qto.edit_qtos(ifc_file, results, target_units=tool.Qto.get_target_units(), rules=rules)
ifc5d.qto.edit_qtos(ifc_file, results)
not_quantified_elements = elements - set(results.keys())
not_quantified_message = tool.Qto.get_not_quantified_elements_message(not_quantified_elements)
@@ -194,7 +194,7 @@ class PerformQuantityTakeOff(bpy.types.Operator, tool.Ifc.Operator):
ifc_file = tool.Ifc.get()
with Profiler("Quantify function time:"):
results = ifc5d.qto.quantify(ifc_file, elements, rules)
ifc5d.qto.edit_qtos(ifc_file, results, target_units=tool.Qto.get_target_units(), rules=rules)
ifc5d.qto.edit_qtos(ifc_file, results)
not_quantified_elements = elements - set(results.keys())
return not_quantified_elements
-28
View File
@@ -27,28 +27,10 @@ from bpy.props import (
)
from bpy.types import PropertyGroup
import bonsai.bim.prop
import bonsai.tool as tool
CALCULATOR_FUNCTION_ENUM_ITEMS: list[Union[tuple[str, str, str], None]] = []
# Measure class (matching ifc5d.qto's Function.measure / SI2ProjectUnitConverter.project_units'
# keys) -> (BIMQtoProperties field name, tool.Pset special_type, UI label).
MEASURE_TO_TARGET_UNIT_FIELD: dict[str, tuple[str, str, str]] = {
"IfcLengthMeasure": ("target_unit_length", "LENGTH", "Length"),
"IfcAreaMeasure": ("target_unit_area", "AREA", "Area"),
"IfcVolumeMeasure": ("target_unit_volume", "VOLUME", "Volume"),
"IfcMassMeasure": ("target_unit_mass", "MASS", "Mass"),
"IfcTimeMeasure": ("target_unit_time", "TIME", "Time"),
}
def _target_unit_items(special_type: str):
def getter(self: "BIMQtoProperties", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
return bonsai.bim.prop.get_unit_enum_items_for_special_type(special_type, tool.Ifc.get())
return getter
def get_qto_rule(self: "BIMQtoProperties", context: bpy.types.Context) -> list[tuple[str, str, str]]:
results: list[tuple[str, str, str]] = []
@@ -110,11 +92,6 @@ class BIMQtoProperties(PropertyGroup):
),
default=False,
)
target_unit_length: EnumProperty(items=_target_unit_items("LENGTH"), name="Length Unit")
target_unit_area: EnumProperty(items=_target_unit_items("AREA"), name="Area Unit")
target_unit_volume: EnumProperty(items=_target_unit_items("VOLUME"), name="Volume Unit")
target_unit_mass: EnumProperty(items=_target_unit_items("MASS"), name="Mass Unit")
target_unit_time: EnumProperty(items=_target_unit_items("TIME"), name="Time Unit")
if TYPE_CHECKING:
qto_rule: str
@@ -124,8 +101,3 @@ class BIMQtoProperties(PropertyGroup):
qto_name: str
prop_name: str
fallback: bool
target_unit_length: str
target_unit_area: str
target_unit_volume: str
target_unit_mass: str
target_unit_time: str
-20
View File
@@ -17,12 +17,9 @@
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import bpy
import ifc5d.qto
import bonsai.tool as tool
from bonsai.bim.helper import prop_with_search
from bonsai.bim.module.qto.data import QtoData
from bonsai.bim.module.qto.prop import MEASURE_TO_TARGET_UNIT_FIELD
class BIM_PT_qto(bpy.types.Panel):
@@ -47,14 +44,6 @@ class BIM_PT_qto(bpy.types.Panel):
row = layout.row()
row.prop(props, "qto_rule", text="")
row.prop(props, "fallback", text="", icon="RADIOBUT_ON" if props.fallback else "RADIOBUT_OFF")
box = layout.box()
box.label(text="Target Units (optional, otherwise project default)")
for field_name, _special_type, label in MEASURE_TO_TARGET_UNIT_FIELD.values():
row = box.row(align=True)
row.label(text=label)
prop_with_search(row, props, field_name, text="")
row = layout.row()
row.operator("bim.perform_quantity_take_off")
@@ -77,15 +66,6 @@ class BIM_PT_qto_manual(bpy.types.Panel):
row = layout.row()
row.prop(props, "calculator_function", text="Function")
calculator = ifc5d.qto.calculators.get(props.calculator)
function = calculator.functions.get(props.calculator_function) if calculator else None
target_unit_field = MEASURE_TO_TARGET_UNIT_FIELD.get(function.measure) if function else None
if target_unit_field:
field_name, _special_type, label = target_unit_field
row = layout.row(align=True)
row.label(text=f"{label} Unit")
prop_with_search(row, props, field_name, text="")
row = layout.row(align=True)
row.prop(props, "qto_name", text="")
row.prop(props, "prop_name", text="")
+1 -8
View File
@@ -132,12 +132,5 @@ class SelectSimilarData:
if pset.endswith("Common"):
keys.extend([f'/.*Common/."{name}"' for name in properties.keys() if name != "id"])
else:
pset_part = f'"{pset}"' if " " in pset else pset
keys.extend(
[
f'{pset_part}."{name}"' if " " in name else f"{pset_part}.{name}"
for name in properties.keys()
if name != "id"
]
)
keys.extend([f"{pset}.{name}" for name in properties.keys() if name != "id"])
return [(k, k, "") for k in keys]
@@ -45,9 +45,7 @@ classes = (
operator.SelectByStyle,
operator.SelectStyleInStylesUI,
operator.SetAssetMaterialToExternalStyle,
operator.SuggestShadeFromExternalStyle,
operator.UnlinkStyle,
operator.TogglePreferIfcShading,
operator.UpdateCurrentStyle,
operator.UpdateStyleColours,
operator.UpdateStyleTextures,
+10 -229
View File
@@ -16,7 +16,6 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import colorsys
import os
from pathlib import Path
from typing import Any, Union
@@ -239,15 +238,13 @@ class UpdateCurrentStyle(bpy.types.Operator):
if not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve)):
continue
for mat in obj.data.materials:
if not mat:
continue
msprops_ = tool.Style.get_material_style_props(mat)
if msprops_.ifc_definition_id == 0:
continue
if mat in updated_materials:
continue
msprops_.active_style_type = current_style_type
updated_materials.add(mat)
if (
mat
and mat not in updated_materials
and (msprops_ := tool.Style.get_material_style_props(mat)).ifc_definition_id != 0
):
msprops_.active_style_type = current_style_type
updated_materials.add(mat)
return {"FINISHED"}
@@ -460,14 +457,10 @@ class ActivateExternalStyle(bpy.types.Operator):
self.report({"ERROR"}, f"Error loading external style for \"{material.name}\" - {db['msg']}")
return {"CANCELLED"}
ext_mat = db["data_block"]
self.copy_material_attributes(ext_mat, material)
self.copy_material_attributes(db["data_block"], material)
if tool.Style.get_use_nodes(material):
if material.get("bim_dual_branch"):
tool.Style.update_external_branch(material, ext_mat)
else:
tool.Style.setup_dual_branch(material, ext_mat)
bpy.data.materials.remove(ext_mat)
tool.Blender.copy_node_graph(material, db["data_block"])
bpy.data.materials.remove(db["data_block"])
return {"FINISHED"}
def copy_material_attributes(self, source, target):
@@ -510,218 +503,6 @@ class ActivateExternalStyle(bpy.types.Operator):
set_prop(prop_name)
class TogglePreferIfcShading(bpy.types.Operator):
bl_idname = "bim.toggle_prefer_ifc_shading"
bl_label = "Toggle Flat/Pretty"
bl_description = (
"Toggle between Flat (IFC-native shading) and Pretty (external .blend style) for ALL styles.\n\n"
"SHIFT+CLICK to apply to this style only"
)
bl_options = {"REGISTER", "UNDO"}
material_name: bpy.props.StringProperty(name="Material Name", default="", options={"SKIP_SAVE"})
single_only: bpy.props.BoolProperty(name="Single Only", default=False, options={"SKIP_SAVE"})
def invoke(self, context, event):
if event.shift:
self.single_only = True
return self.execute(context)
def execute(self, context):
wm = context.window_manager
space = tool.Blender.get_view3d_space()
is_solid = space and space.shading.type == "SOLID"
if is_solid:
if space.shading.color_type == "TEXTURE":
space.shading.color_type = "MATERIAL"
else:
meshes_needing_uv = []
for obj in bpy.context.scene.objects:
if not isinstance(obj.data, bpy.types.Mesh):
continue
for slot in obj.material_slots:
mat = slot.material
if not mat or not tool.Blender.get_ifc_definition_id(mat):
continue
style_elements = tool.Style.get_style_elements(mat)
if style_elements.get("IfcSurfaceStyleWithTextures") and not obj.data.uv_layers:
meshes_needing_uv.append(obj.data)
break
wm.progress_begin(0, max(len(meshes_needing_uv), 1))
try:
for i, mesh in enumerate(meshes_needing_uv):
tool.Loader.load_generated_uv_map(mesh)
wm.progress_update(i)
finally:
wm.progress_end()
space.shading.color_type = "TEXTURE"
return {"FINISHED"}
if self.single_only:
mat = bpy.data.materials.get(self.material_name)
if not mat:
return {"CANCELLED"}
msprops = tool.Style.get_material_style_props(mat)
msprops.prefer_ifc_shading = not msprops.prefer_ifc_shading
else:
# Default: apply to all IFC materials
source_mat = bpy.data.materials.get(self.material_name)
new_value = not tool.Style.get_material_style_props(source_mat).prefer_ifc_shading if source_mat else True
ifc_mats = [m for m in bpy.data.materials if tool.Blender.get_ifc_definition_id(m)]
for mat in ifc_mats:
tool.Style.get_material_style_props(mat).prefer_ifc_shading = new_value
return {"FINISHED"}
class SuggestShadeFromExternalStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.suggest_shade_from_external_style"
bl_label = "Suggest Shade from External Style"
bl_description = (
"Generate a Shade style (Surface Colour + Transparency) from the external .blend style.\n\n"
"ALT+CLICK to apply to all styles with an external .blend style"
)
bl_options = {"REGISTER", "UNDO"}
material_name: bpy.props.StringProperty(name="Material Name", default="", options={"SKIP_SAVE"})
all_styles: bpy.props.BoolProperty(name="All Styles", default=False, options={"SKIP_SAVE"})
value_offset: bpy.props.FloatProperty(
name="Value",
description="Offset added to the colour's value (-1 = fully dark, 0 = unchanged, +1 = fully light)",
default=0.0,
min=-1.0,
max=1.0,
step=1,
precision=2,
options={"SKIP_SAVE"},
)
saturation_factor: bpy.props.FloatProperty(
name="Saturation",
description="Scale applied to the colour's saturation (0 = greyscale, 1 = unchanged, >1 = more saturated)",
default=1.0,
min=0.0,
max=2.0,
step=1,
precision=2,
options={"SKIP_SAVE"},
)
def invoke(self, context, event):
if event.alt:
self.all_styles = True
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
layout = self.layout
layout.prop(self, "value_offset", slider=True)
layout.prop(self, "saturation_factor", slider=True)
if self.all_styles:
layout.label(text="Will apply to all external styles", icon="INFO")
def _execute(self, context):
if self.all_styles:
candidates = [
(mat, tool.Style.get_style_elements(mat))
for mat in bpy.data.materials
if tool.Blender.get_ifc_definition_id(mat)
]
candidates = [(mat, se) for mat, se in candidates if tool.Style.has_blender_external_style(se)]
wm = context.window_manager
wm.progress_begin(0, max(len(candidates), 1))
count = 0
color_cache: dict[tuple[str, str, str], tuple | None] = {}
try:
for i, (mat, style_elements) in enumerate(candidates):
wm.progress_update(i)
if self._apply_to_material(
mat, style_elements, self.value_offset, self.saturation_factor, color_cache
):
count += 1
finally:
wm.progress_end()
self.report({"INFO"}, f"Shade style generated for {count} style(s).")
else:
mat = bpy.data.materials.get(self.material_name)
if not mat:
return {"CANCELLED"}
style_elements = tool.Style.get_style_elements(mat)
if not tool.Style.has_blender_external_style(style_elements):
self.report({"ERROR"}, "No external .blend style assigned. Please assign an external style first.")
return {"CANCELLED"}
self._apply_to_material(mat, style_elements, self.value_offset, self.saturation_factor)
props = tool.Style.get_style_props()
if props.is_editing:
core.load_styles(tool.Style, style_type=props.style_type)
def _apply_to_material(
self,
material: bpy.types.Material,
style_elements: dict,
value_offset: float = 0.0,
saturation_factor: float = 1.0,
color_cache: "dict[tuple[str, str, str], tuple | None] | None" = None,
) -> bool:
external_style = style_elements["IfcExternallyDefinedSurfaceStyle"]
style_path = Path(tool.Ifc.resolve_uri(external_style.Location))
data_block_type, data_block = external_style.Identification.split("/")
cache_key = (str(style_path), data_block_type, data_block)
if color_cache is not None and cache_key in color_cache:
cached = color_cache[cache_key]
if cached is None:
return False # previously failed for this path
surface_colour, transparency = cached
else:
try:
db = tool.Blender.append_data_block(str(style_path), data_block_type, data_block)
except OSError as e:
self.report({"WARNING"}, f'Could not open blend file for "{material.name}": {e}')
if color_cache is not None:
color_cache[cache_key] = None
return False
if not db["data_block"]:
self.report({"WARNING"}, f'Could not load external style for "{material.name}": {db["msg"]}')
if color_cache is not None:
color_cache[cache_key] = None
return False
ext_mat = db["data_block"]
surface_colour, transparency = tool.Style.get_representative_material_color(ext_mat)
bpy.data.materials.remove(ext_mat)
if color_cache is not None:
color_cache[cache_key] = (surface_colour, transparency)
if value_offset != 0.0 or saturation_factor != 1.0:
h, s, v = colorsys.rgb_to_hsv(*surface_colour)
v = max(0.0, min(1.0, v + value_offset))
s = max(0.0, min(1.0, s * saturation_factor))
surface_colour = colorsys.hsv_to_rgb(h, s, v)
ifc_style = tool.Ifc.get_entity(material)
attributes: dict = {
"SurfaceColour": {
"Name": None,
"Red": surface_colour[0],
"Green": surface_colour[1],
"Blue": surface_colour[2],
},
}
if tool.Ifc.get_schema() != "IFC2X3":
attributes["Transparency"] = transparency
shading_style = style_elements.get("IfcSurfaceStyleShading")
if shading_style:
tool.Ifc.run("style.edit_surface_style", style=shading_style, attributes=attributes)
else:
tool.Ifc.run(
"style.add_surface_style",
style=ifc_style,
ifc_class="IfcSurfaceStyleShading",
attributes=attributes,
)
material.diffuse_color = (*surface_colour, 1.0 - transparency)
tool.Style.sync_flat_branch_shading(material, surface_colour, transparency)
return True
class DisableEditingStyles(bpy.types.Operator):
bl_idname = "bim.disable_editing_styles"
bl_options = {"REGISTER", "UNDO"}
@@ -372,16 +372,6 @@ def update_shading_style(self: "BIMStyleProperties", context: bpy.types.Context)
tool.Style.switch_shading(blender_material, self.active_style_type)
def update_prefer_ifc_shading(self: "BIMStyleProperties", context: bpy.types.Context) -> None:
style_elements = tool.Style.get_style_elements(self.id_data)
has_external = tool.Style.has_blender_external_style(style_elements)
if self.prefer_ifc_shading or not has_external:
self.active_style_type = "Shading"
else:
self.active_style_type = "External"
self.id_data.update_tag()
class BIMStyleProperties(PropertyGroup):
ifc_definition_id: IntProperty(name="IFC Definition ID")
active_style_type: EnumProperty(
@@ -391,19 +381,9 @@ class BIMStyleProperties(PropertyGroup):
default="Shading",
update=update_shading_style,
)
prefer_ifc_shading: BoolProperty(
name="Flat / Pretty",
description=(
"Toggle between Flat (IFC-native shading) and Pretty (external .blend style). "
"When set to Flat, viewport switches to Material Preview or Rendered will not activate the external style."
),
default=False,
update=update_prefer_ifc_shading,
)
is_renaming: BoolProperty(description="Used to prevent triggering handler callback.", default=False)
if TYPE_CHECKING:
ifc_definition_id: int
active_style_type: tool.Style.StyleType
prefer_ifc_shading: bool
is_renaming: bool
-65
View File
@@ -110,11 +110,6 @@ class BIM_PT_styles(Panel):
op = row.operator("bim.update_current_style", icon="FILE_REFRESH", text="")
op.style_id = style.ifc_definition_id
if active_style and self.props.style_type == "IfcSurfaceStyle":
if material := style.blender_material:
msprops = tool.Style.get_material_style_props(material)
self.draw_style_status_row(material, msprops)
if self.props.style_type == "IfcSurfaceStyle":
self.layout.label(text="Surface Style Element:")
col = self.layout.column(align=True)
@@ -166,66 +161,6 @@ class BIM_PT_styles(Panel):
edit_label = "Save Lighting Style"
self.draw_edit_ui(edit_label)
def draw_style_status_row(self, material: bpy.types.Material, msprops) -> None:
space = tool.Blender.get_view3d_space()
box = self.layout.box()
obj = bpy.context.active_object
parts = []
if space:
shading_type = space.shading.type
shading_labels = {
"SOLID": "Solid",
"MATERIAL": "Material Preview",
"RENDERED": "Rendered",
"WIREFRAME": "Wireframe",
}
parts.append(f"Viewport: {shading_labels.get(shading_type, shading_type)}")
else:
parts.append("No 3D viewport")
shading_type = None
if obj:
obj_has_uv = isinstance(obj.data, bpy.types.Mesh) and bool(obj.data.uv_layers)
uv_label = "UV \u2713" if obj_has_uv else "UV \u2717"
parts.append(f"Selected Object: {obj.name} {uv_label}")
else:
parts.append("Selected Object: None")
if shading_type == "SOLID":
is_flat = space.shading.color_type != "TEXTURE"
mode_label = "Flat"
dep_label = "Shade"
if not is_flat:
mode_label = "Pretty"
dep_label = "Texture \u2192 Shade"
elif shading_type in ("MATERIAL", "RENDERED"):
is_flat = msprops.prefer_ifc_shading
mode_label = "Flat"
dep_label = "Render+Texture \u2192 Render \u2192 Shade"
if not is_flat:
mode_label = "Pretty"
dep_label = "External \u2192 Render+Texture \u2192 Render \u2192 Shade"
else:
is_flat = False
mode_label = ""
dep_label = ""
row1 = box.row(align=True)
row1.label(text=" | ".join(parts))
if mode_label:
row2 = box.row(align=True)
row2.label(text=f"Current Mode: {mode_label} \u2014 {dep_label}")
row3 = box.row(align=True)
row3.alignment = "RIGHT"
op = row3.operator("bim.suggest_shade_from_external_style", text="", icon="BRUSHES_ALL")
op.material_name = material.name
op = row3.operator("bim.toggle_prefer_ifc_shading", text="", icon="UV_SYNC_SELECT")
op.material_name = material.name
def draw_surface_style_shading(self):
row = self.layout.row()
row.prop(self.props, "surface_colour")
+37 -79
View File
@@ -21,6 +21,7 @@ import os
from typing import TYPE_CHECKING, Any, Literal, Union, assert_never, get_args
import bpy
import ifcopenshell.util.unit
from bpy.props import (
BoolProperty,
CollectionProperty,
@@ -33,8 +34,6 @@ from bpy.props import (
)
from bpy.types import PropertyGroup
import ifcopenshell.util.unit
import bonsai.bim
import bonsai.bim.handler
import bonsai.tool as tool
@@ -123,57 +122,6 @@ def get_attribute_enum_values(prop: "Attribute", context: bpy.types.Context) ->
return items
def get_unit_enum_items_for_special_type(
special_type: str, ifc_file: Union[ifcopenshell.file, None]
) -> tool.Blender.BLENDER_ENUM_ITEMS:
"""Items for a unit-override picker: "Default (<symbol>)" plus every candidate unit
matching `special_type`, filtered per-caller since candidates depend on the measure type
in question (unlike the globally-shared lists in `bonsai.bim.ui.EnumData`).
"""
if not ifc_file or not tool.Pset.is_measurable_special_type(special_type):
return [(cache_string("0"), cache_string("Default"), "")]
default_symbol = tool.Pset.get_unit_symbol_for_special_type(special_type, ifc_file)
items: list[tuple[str, str, str]] = [
(cache_string("0"), cache_string(f"Default ({default_symbol})" if default_symbol else "Default"), "")
]
for unit in tool.Pset.get_candidate_units_for_special_type(special_type, ifc_file):
name = getattr(unit, "Name", None) or unit.is_a()
symbol = ifcopenshell.util.unit.get_unit_symbol(unit)
label = f"{name} ({symbol})" if symbol else name
items.append((cache_string(str(unit.id())), cache_string(label), ""))
return items
def get_attribute_unit_enum_items(prop: "Attribute", context: bpy.types.Context) -> tool.Blender.BLENDER_ENUM_ITEMS:
"""Items for `Attribute.unit_id_enum`. Wraps `get_unit_enum_items_for_special_type` with a
defensive addition: real-world files sometimes carry a Unit that doesn't cleanly match our
candidate-matching logic (e.g. a mismatched UnitType). Always keep the attribute's own
current override selectable/representable, however unusual, so setting unit_id_enum to
match an already-seeded unit_id can never raise "enum not found".
"""
ifc_file = tool.Ifc.get()
items = get_unit_enum_items_for_special_type(prop.special_type, ifc_file)
if prop.unit_id and prop.unit_id not in {int(i[0]) for i in items}:
own_unit = ifc_file.by_id(prop.unit_id)
name = getattr(own_unit, "Name", None) or own_unit.is_a()
symbol = ifcopenshell.util.unit.get_unit_symbol(own_unit)
label = f"{name} ({symbol})" if symbol else name
items.append((cache_string(str(prop.unit_id)), cache_string(label), ""))
return items
def update_attribute_unit_id(self: "Attribute", context: bpy.types.Context) -> None:
new_unit_id = int(tool.Blender.get_enum_safe(self, "unit_id_enum") or "0")
if ifc_file := tool.Ifc.get():
# Must run before self.unit_id is overwritten: convert_attribute_unit needs the OLD
# unit_id to know what unit the current value is expressed in.
tool.Pset.convert_attribute_unit(self, new_unit_id, ifc_file)
self.unit_id = new_unit_id
def update_schema_dir(self: "BIMProperties", context: bpy.types.Context) -> None:
import bonsai.bim.schema
@@ -302,33 +250,44 @@ def set_numerical_value(self: "Attribute", value_name: str, new_value: Union[flo
self[value_name] = new_value
def get_length_value(self: "Attribute") -> float:
si_conversion = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
return self.float_value * si_conversion
def set_length_value(self: "Attribute", value: float) -> None:
si_conversion = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
self.float_value = value / si_conversion
def get_display_name(self: "Attribute") -> str:
DISPLAY_UNIT_TYPES = ("AREA", "VOLUME", "FORCE")
name = self.name
if not self.unit_symbol:
if not self.special_type or self.special_type not in DISPLAY_UNIT_TYPES:
return name
return f"{name}, {self.unit_symbol}"
unit_type = f"{self.special_type}UNIT"
project_unit = ifcopenshell.util.unit.get_project_unit(tool.Ifc.get(), unit_type)
if not project_unit:
return name
def get_unit_symbol(self: "Attribute") -> str:
"""The symbol for whatever unit the value is currently expressed in: this property's own
override (`unit_id`) if set, else the project default for `special_type`. Computed fresh on
every access (rather than cached at import time) so it stays correct immediately after the
unit picker changes `unit_id`, and after the project's own default units are edited.
"""
if not tool.Pset.is_measurable_special_type(self.special_type):
return ""
if not (ifc_file := tool.Ifc.get()):
return ""
unit = tool.Pset.resolve_effective_unit(self.special_type, self.unit_id, ifc_file)
return ifcopenshell.util.unit.get_unit_symbol(unit) if unit else ""
unit_symbol = ifcopenshell.util.unit.get_unit_symbol(project_unit)
return f"{name}, {unit_symbol}"
AttributeDataType = Literal["string", "integer", "float", "boolean", "enum", "file", "list[string]"]
# Either "", "DATE", "DATETIME", "LOGICAL", "URI", "DURATION", or an
# IfcUnitEnum/IfcDerivedUnitEnum value with the "UNIT" suffix stripped (e.g.
# "LENGTH", "PRESSURE", "MODULUSOFELASTICITY") as returned by
# tool.Pset.get_special_type_for_prop().
AttributeSpecialType = str
AttributeSpecialType = Literal[
"",
"DATE",
"DATETIME",
"LENGTH",
"AREA",
"VOLUME",
"FORCE",
"LOGICAL",
"URI",
"DURATION",
]
class Attribute(PropertyGroup):
@@ -359,6 +318,9 @@ class Attribute(PropertyGroup):
get=lambda self: float(self.get("float_value", 0.0)),
set=set_float_value,
)
length_value: FloatProperty(
name="Value", description=tooltip, get=get_length_value, set=set_length_value, unit="LENGTH"
)
enum_items: StringProperty(name="Value")
"""Json serialized mapping of enum items:
Typically a dictionary of string identifiers to item names.
@@ -380,10 +342,6 @@ class Attribute(PropertyGroup):
value_max: FloatProperty(description="This is used to validate int_value and float_value")
value_max_constraint: BoolProperty(default=False, description="True if the numerical value has an upper bound")
special_type: StringProperty(name="Special Value Type", default="")
unit_symbol: StringProperty(name="Unit Symbol", get=get_unit_symbol)
unit_id: IntProperty(name="Unit Override", default=0)
"""STEP id of this property/quantity's own Unit override. 0 means "use the project default"."""
unit_id_enum: EnumProperty(items=get_attribute_unit_enum_items, name="Unit", update=update_attribute_unit_id)
use_explorer_ui: BoolProperty()
metadata: StringProperty(name="Metadata", description="For storing some additional information about the attribute")
update: StringProperty(name="Update", description="Custom update function to be executed")
@@ -399,6 +357,7 @@ class Attribute(PropertyGroup):
bool_value: bool
int_value: int
float_value: float
length_value: float
enum_items: str
enum_items_dynamic: str
enum_descriptions: bpy.types.bpy_prop_collection_idprop[StrProperty]
@@ -414,9 +373,6 @@ class Attribute(PropertyGroup):
value_min_constraint: bool
value_max: float
value_max_constraint: bool
unit_symbol: str
unit_id: int
unit_id_enum: str
use_explorer_ui: bool
metadata: str
update: str
@@ -474,6 +430,8 @@ class Attribute(PropertyGroup):
elif data_type == "integer":
return "int_value"
elif data_type == "float":
if display_only and self.special_type == "LENGTH":
return "length_value"
return "float_value"
elif data_type == "enum":
return "enum_value"
+1
View File
@@ -222,6 +222,7 @@ def generate_space(
if element and element.is_a("IfcSpace"):
spatial.set_space_representation_from_polygon(active_obj, element, space_polygon, h, polygon_is_si=True)
spatial.translate_obj_to_z_location(active_obj, z)
else:
if relating_type:
name = model.generate_occurrence_name(relating_type, "IfcSpace")
-34
View File
@@ -803,40 +803,6 @@ class Blender(bonsai.core.tool.Blender):
# restore shader editor settings
shader_editor.pin = previous_pin_setting
@classmethod
def copy_node_graph_additive(
cls, material_to: bpy.types.Material, material_from: bpy.types.Material
) -> bpy.types.ShaderNodeOutputMaterial | None:
"""Paste nodes from material_from alongside the existing nodes in material_to.
Unlike copy_node_graph this does NOT clear the existing node tree first.
Returns the OUTPUT_MATERIAL node that was added from material_from, or None.
"""
temp_override = cls.get_shader_editor_context()
shader_editor = temp_override["space"]
before_names = {n.name for n in material_to.node_tree.nodes}
previous_pin_setting = shader_editor.pin
shader_editor.pin = True
shader_editor.node_tree = material_from.node_tree
for node in material_from.node_tree.nodes:
node.select = True
with bpy.context.temp_override(**temp_override):
bpy.ops.node.clipboard_copy()
shader_editor.node_tree = material_to.node_tree
with bpy.context.temp_override(**temp_override):
bpy.ops.node.clipboard_paste(offset=(0, 0))
shader_editor.pin = previous_pin_setting
for node in material_to.node_tree.nodes:
if node.name not in before_names and node.type == "OUTPUT_MATERIAL":
return node
return None
@classmethod
def get_material_node(
cls, blender_material: bpy.types.Material, node_type: str, kwargs: Optional[dict] = {}
+1
View File
@@ -138,6 +138,7 @@ class Bsdd(bonsai.core.tool.Bsdd):
def get_dictionaries(cls) -> list[bsdd.DictionaryContractV1]:
prefs = tool.Blender.get_addon_preferences()
baseurl = getattr(prefs, "bsdd_baseurl", "https://api.bsdd.buildingsmart.org/api/")
cls.client = bsdd.Client()
if hasattr(cls.client, "baseurl"):
cls.client.baseurl = baseurl
response = cls.client.get_dictionary(include_test_dictionaries=prefs.bsdd_load_test_dictionaries)
-11
View File
@@ -1270,17 +1270,6 @@ class ClipBox:
def on_depsgraph_update_caps(cls, scene, depsgraph) -> None:
"""Depsgraph entry-point — guard, then delegate to the
modal-aware debounce in :meth:`_handle_cap_tick`."""
# Same file-load danger window as on_depsgraph_update: a real
# depsgraph tick during load (between load_pre and the new file's
# first paint) must not re-arm a cap-rebuild timer. _on_load_pre
# already cancels any in-flight timer via _cancel_pending_cap_rebuild;
# without this gate, a depsgraph_update_post event firing later in
# the same load (Blender fires these while building the new file's
# scene) would immediately reschedule one via _handle_cap_tick,
# undoing that cancellation and re-arming against regions whose GPU
# state is not yet wired.
if cls._file_loading:
return
if getattr(bpy.context, "screen", None) is None:
return
if cls._active_scene_props(scene) is None:
+3 -3
View File
@@ -168,12 +168,12 @@ class Polyline(bonsai.core.tool.Polyline):
distance = (mouse_vector - last_point).length
if distance < 0:
return
angle, orientation_angle = None, None
angle_round_threshold = 1000 # Avoids rounding when distance is too big
angle, orientation_angle, angle_round_threshold = None, None, None
if distance > 0:
angle = tool.Cad.angle_3_vectors(
second_to_last_point, last_point, mouse_vector, new_angle=None, degrees=True
)
angle_round_threshold = 1000 # Avoids rounding when distance is too big
# Round angle to the nearest 0.05
angle = round(angle / 0.05) * 0.05 if distance < angle_round_threshold else angle
@@ -189,7 +189,7 @@ class Polyline(bonsai.core.tool.Polyline):
angle = 0
orientation_angle = 0
if input_ui:
assert angle is not None and orientation_angle is not None
assert angle is not None and orientation_angle is not None and angle_round_threshold is not None
if should_round:
angle_snap = tool.Snap.get_angle_snap_value(context)
angle = angle_snap * round(angle / angle_snap) if distance < angle_round_threshold else angle
+17 -2
View File
@@ -391,14 +391,29 @@ class Project(bonsai.core.tool.Project):
def get_parent_library(
cls, project_library: ifcopenshell.entity_instance
) -> Union[ifcopenshell.entity_instance, None]:
"""Return the IfcContext that declares or nests ``project_library``, or ``None``
if neither relationship is present."""
"""Return the IfcContext that declares or nests ``project_library``.
Returns ``None`` when ``project_library`` is itself the root of a
library-only file (no IfcRelNests, no IfcRelDeclares).
"""
if nests := project_library.Nests:
return nests[0].RelatingObject
if has_context := project_library.HasContext:
return has_context[0].RelatingContext
return None
@classmethod
def get_root_context(cls, ifc_file: ifcopenshell.file) -> ifcopenshell.entity_instance:
"""Return the file's root IfcContext.
Prefers IfcProject if present, otherwise falls back to IfcProjectLibrary
library-only files are valid per IFC4+ and contain no IfcProject. Caller is
responsible for the IFC2X3 guard; IfcContext does not exist in that schema.
"""
if projects := ifc_file.by_type("IfcProject"):
return projects[0]
return ifc_file.by_type("IfcProjectLibrary")[0]
@classmethod
def get_project_hierarchy(cls, ifc_file: ifcopenshell.file) -> HiearchyDict:
"""Get project hierarchy in the following form:
+33 -147
View File
@@ -26,7 +26,6 @@ import ifcopenshell
import ifcopenshell.api.pset
import ifcopenshell.util.attribute
import ifcopenshell.util.element
import ifcopenshell.util.unit
import bonsai.bim.helper
import bonsai.bim.schema
@@ -169,144 +168,42 @@ class Pset(bonsai.core.tool.Pset):
pset_id=0, pset_name=cls.get_pset_name(obj, obj_type), pset_type="PSET", obj=obj, obj_type=obj_type
)
# Templates for quantities can specify their kind via TemplateType (e.g.
# "Q_LENGTH") instead of PrimaryMeasureType. IfcQuantityCount has no
# associated measure/unit, so it is intentionally absent here.
QUANTITY_TEMPLATE_TYPE_TO_SPECIAL_TYPE = {
"Q_LENGTH": "LENGTH",
"Q_AREA": "AREA",
"Q_VOLUME": "VOLUME",
"Q_WEIGHT": "MASS",
"Q_TIME": "TIME",
}
@classmethod
def get_special_type_for_measure_class(cls, measure_class: str) -> str:
"""Get the ``special_type`` (an IfcUnitEnum value with "UNIT" stripped) for an IFC measure class.
:param measure_class: An IFC measure class name, e.g. "IfcLengthMeasure".
:return: E.g. "LENGTH", or "" if the class has no associated unit type.
"""
if not measure_class.endswith("Measure"):
return ""
unit_type = ifcopenshell.util.unit.get_measure_unit_type(measure_class)
return unit_type[: -len("UNIT")] if unit_type.endswith("UNIT") else ""
@classmethod
def get_special_type_for_unit(cls, unit: ifcopenshell.entity_instance) -> str:
"""Get the ``special_type`` (an IfcUnitEnum value with "UNIT" stripped) directly from
a Unit entity, for properties whose NominalValue is a generic numeric type (e.g.
IfcReal) rather than a proper measure class, but which still carry a real Unit.
"""
unit_type = getattr(unit, "UnitType", None)
if unit_type and unit_type != "USERDEFINED":
return unit_type[: -len("UNIT")] if unit_type.endswith("UNIT") else ""
dimension_type = ifcopenshell.util.unit.identify_unit_dimensions(unit)
return dimension_type[: -len("UNIT")] if dimension_type else ""
@classmethod
def get_special_type_for_prop(cls, prop_or_prop_template: ifcopenshell.entity_instance) -> str:
"""Classify a property/quantity/template by its measure type.
:return: An IfcUnitEnum value with the "UNIT" suffix stripped (e.g.
"LENGTH", "PRESSURE"), "URI" for IfcURIReference, or "" if the
value has no associated unit type.
"""
def get_special_type_for_prop(
cls, prop_or_prop_template: ifcopenshell.entity_instance
) -> Literal["LENGTH"] | Literal["AREA"] | Literal["VOLUME"] | Literal["URI"] | Literal[""]:
special_type = ""
if prop_or_prop_template.is_a("IfcPropertyTemplate"):
primary_measure_type = prop_or_prop_template.PrimaryMeasureType
if primary_measure_type == "IfcURIReference":
return "URI"
if primary_measure_type:
return cls.get_special_type_for_measure_class(primary_measure_type)
return cls.QUANTITY_TEMPLATE_TYPE_TO_SPECIAL_TYPE.get(prop_or_prop_template.TemplateType, "")
elif prop_or_prop_template.is_a("IfcPropertySingleValue"):
value = prop_or_prop_template.NominalValue
if value is not None:
special_type = cls.get_special_type_for_measure_class(value.is_a())
if special_type:
return special_type
# Some property sets declare a generic numeric type (e.g. IfcReal) rather
# than a proper measure class, relying on an explicit Unit attribute alone to
# convey the dimension. Still measurable -- derive special_type from the Unit
# itself rather than (fruitlessly) from NominalValue's declared type.
if value.is_a() in ("IfcReal", "IfcInteger"):
if unit := getattr(prop_or_prop_template, "Unit", None):
return cls.get_special_type_for_unit(unit)
elif prop_or_prop_template.is_a("IfcPhysicalSimpleQuantity"):
entity = prop_or_prop_template.wrapped_data.declaration().as_entity()
measure_class = entity.attribute_by_index(3).type_of_attribute().declared_type().name()
return cls.get_special_type_for_measure_class(measure_class)
return ""
@classmethod
def get_unit_symbol_for_special_type(cls, special_type: str, ifc_file: ifcopenshell.file) -> str:
"""Get the project's default unit symbol for a `special_type` (see `get_special_type_for_prop`).
Used where there's no property instance to check for a `Unit` override
(e.g. a template, or a native IFC entity attribute, neither of which
can carry one).
"""
if not special_type or special_type == "URI":
return ""
unit = ifcopenshell.util.unit.get_project_unit(ifc_file, f"{special_type}UNIT")
return ifcopenshell.util.unit.get_unit_symbol(unit) if unit else ""
@classmethod
def get_unit_symbol_for_prop(cls, prop: ifcopenshell.entity_instance, ifc_file: ifcopenshell.file) -> str:
"""Get the unit symbol for an existing property/quantity, respecting its own `Unit` override.
Gated on the property being classified as measurable (see `get_special_type_for_prop`,
which already accounts for a Unit attached to a generic numeric value) -- this only
excludes a Unit attached to a property whose value has no numeric/measure semantics at
all (e.g. text), where a stray Unit shouldn't be surfaced as a resolved unit.
"""
if not cls.is_measurable_special_type(cls.get_special_type_for_prop(prop)):
return ""
unit = ifcopenshell.util.unit.get_property_unit(prop, ifc_file)
return ifcopenshell.util.unit.get_unit_symbol(unit) if unit else ""
# special_type values that don't denote a real unit-bearing measure (see get_special_type_for_prop).
NON_MEASURABLE_SPECIAL_TYPES = frozenset({"", "DATE", "DATETIME", "LOGICAL", "URI", "DURATION"})
@classmethod
def is_measurable_special_type(cls, special_type: str) -> bool:
"""True if `special_type` (see `get_special_type_for_prop`) denotes a real unit-bearing measure."""
return special_type not in cls.NON_MEASURABLE_SPECIAL_TYPES
@classmethod
def get_candidate_units_for_special_type(
cls, special_type: str, ifc_file: ifcopenshell.file
) -> list[ifcopenshell.entity_instance]:
"""All units in the file usable as an override for a `special_type` (see `get_special_type_for_prop`)."""
if not cls.is_measurable_special_type(special_type):
return []
return ifcopenshell.util.unit.get_candidate_units(ifc_file, f"{special_type}UNIT")
@classmethod
def resolve_effective_unit(
cls, special_type: str, unit_id: int, ifc_file: ifcopenshell.file
) -> Union[ifcopenshell.entity_instance, None]:
"""The unit a value is currently expressed in: its own override (`unit_id`, a STEP id,
0 meaning "no override"), or the project default for `special_type` otherwise."""
if unit_id:
return ifc_file.by_id(unit_id)
return ifcopenshell.util.unit.get_project_unit(ifc_file, f"{special_type}UNIT")
@classmethod
def convert_attribute_unit(cls, metadata: "Attribute", new_unit_id: int, ifc_file: ifcopenshell.file) -> None:
"""Rescale `metadata.float_value` in place so its physical quantity is preserved when
switching from its current effective unit to the unit named by `new_unit_id` (0 = project
default). No-op for non-measurable attributes or when old and new resolve to the same unit.
"""
if not cls.is_measurable_special_type(metadata.special_type):
return
old_unit = cls.resolve_effective_unit(metadata.special_type, metadata.unit_id, ifc_file)
new_unit = cls.resolve_effective_unit(metadata.special_type, new_unit_id, ifc_file)
if old_unit is None or new_unit is None or old_unit == new_unit:
return
old_scale = ifcopenshell.util.unit.get_unit_scale(old_unit)
new_scale = ifcopenshell.util.unit.get_unit_scale(new_unit)
metadata.float_value = metadata.float_value * old_scale / new_scale
template_type = prop_or_prop_template.TemplateType
if primary_measure_type in ("IfcPositiveLengthMeasure", "IfcLengthMeasure") or template_type == "Q_LENGTH":
special_type = "LENGTH"
elif primary_measure_type == "IfcAreaMeasure" or template_type == "Q_AREA":
special_type = "AREA"
elif primary_measure_type == "IfcVolumeMeasure" or template_type == "Q_VOLUME":
special_type = "VOLUME"
elif primary_measure_type == "IfcURIReference":
special_type = "URI"
else:
if prop_or_prop_template.is_a("IfcPropertySingleValue"):
value = prop_or_prop_template.NominalValue
if value is not None:
value_type = value.is_a()
if value_type in ("IfcLengthMeasure", "IfcPositiveLengthMeasure"):
special_type = "LENGTH"
elif value_type == "IfcAreaMeasure":
special_type = "AREA"
elif value_type == "IfcVolumeMeasure":
special_type = "VOLUME"
elif prop_or_prop_template.is_a("IfcPhysicalSimpleQuantity"):
prop_class = prop_or_prop_template.is_a()
if prop_class == "IfcQuantityArea":
special_type = "AREA"
elif prop_class == "IfcQuantityVolume":
special_type = "VOLUME"
elif prop_class == "IfcQuantityLength":
special_type = "LENGTH"
return special_type
@classmethod
def import_pset_from_existing(
@@ -386,15 +283,6 @@ class Pset(bonsai.core.tool.Pset):
metadata.is_null = value is None
metadata.is_optional = True
metadata.special_type = cls.get_special_type_for_prop(prop)
# The prop's OWN Unit override only -- metadata.unit_symbol is computed fresh from
# special_type/unit_id on every access (see Attribute.get_unit_symbol), so it
# already accounts for the project-default fallback once unit_id is set below.
# Some real-world files (e.g. certain exporters) set Unit on properties that
# aren't actually measures -- ignore it there, since we only ever treat Unit as
# meaningful for measurable special_types (matching the UI picker's own gating).
own_unit = getattr(prop, "Unit", None) if cls.is_measurable_special_type(metadata.special_type) else None
metadata.unit_id = own_unit.id() if own_unit else 0
metadata.unit_id_enum = str(metadata.unit_id)
metadata.set_value(metadata.get_value_default() if metadata.is_null else value)
process_prop_description(metadata)
@@ -521,8 +409,6 @@ class Pset(bonsai.core.tool.Pset):
cls.import_single_value_from_template(pset_template, prop_template, simplified_data, props)
elif prop_template.TemplateType.startswith("Q_"):
if prop_data:
continue # Existing quantity will be added later by import_pset_from_existing.
cls.import_single_value_from_template(pset_template, prop_template, simplified_data, props)
elif prop_template.TemplateType == "P_ENUMERATEDVALUE":
-13
View File
@@ -176,19 +176,6 @@ class Qto(bonsai.core.tool.Qto):
is_ifc4x3 = ifc_file.schema == "IFC4X3"
return {rule_id: rule for rule_id, rule in ifc5d.qto.rules.items() if rule_id.startswith("IFC4X3") == is_ifc4x3}
@classmethod
def get_target_units(cls) -> dict[str, ifcopenshell.entity_instance]:
from bonsai.bim.module.qto.prop import MEASURE_TO_TARGET_UNIT_FIELD
props = cls.get_qto_props()
ifc_file = tool.Ifc.get()
target_units: dict[str, ifcopenshell.entity_instance] = {}
for measure_class, (field_name, _special_type, _label) in MEASURE_TO_TARGET_UNIT_FIELD.items():
unit_id = int(tool.Blender.get_enum_safe(props, field_name) or "0")
if unit_id:
target_units[measure_class] = ifc_file.by_id(unit_id)
return target_units
@classmethod
def get_not_quantified_elements_message(cls, not_quantified_elements: set[ifcopenshell.entity_instance]) -> str:
not_quantified_message = ""
-363
View File
@@ -597,146 +597,6 @@ class Style(bonsai.core.tool.Style):
external_style = style_elements.get("IfcExternallyDefinedSurfaceStyle", None)
return bool(external_style and external_style.Location and external_style.Location.endswith(".blend"))
@classmethod
def _color_from_principled(cls, node: bpy.types.Node) -> tuple[tuple[float, float, float], float]:
color = cls._resolve_color_socket(node.inputs["Base Color"])
alpha_socket = node.inputs["Alpha"]
alpha_source = cls._upstream_color_source(alpha_socket)
if alpha_source and alpha_source[0] == "IMAGE":
pixels = alpha_source[1].pixels[:]
n = len(pixels) // 4
step = max(1, n // 4096)
a_sum = sum(pixels[i * 4 + 3] for i in range(0, n, step))
count = len(range(0, n, step)) or 1
transparency = 1.0 - (a_sum / count)
else:
transparency = 1.0 - alpha_socket.default_value
return color, transparency
@classmethod
def _color_from_shader_socket(
cls, socket: bpy.types.NodeSocket, seen: set[str] | None = None
) -> tuple[tuple[float, float, float], float] | None:
if seen is None:
seen = set()
for link in socket.links:
node = link.from_node
if node.name in seen:
continue
seen.add(node.name)
if node.type == "BSDF_PRINCIPLED":
return cls._color_from_principled(node)
if node.type in ("BSDF_DIFFUSE", "DIFFUSE_BSDF"):
return cls._resolve_color_socket(node.inputs["Color"]), 0.0
if node.type == "BSDF_GLASS":
return cls._resolve_color_socket(node.inputs["Color"]), 0.0
if node.type in ("MIX_SHADER", "ADD_SHADER"):
for inp in node.inputs:
if inp.type == "SHADER" and inp.is_linked:
result = cls._color_from_shader_socket(inp, seen)
if result:
return result
return None
@classmethod
def get_representative_material_color(
cls, material: bpy.types.Material
) -> tuple[tuple[float, float, float], float]:
if material.node_tree:
nodes = material.node_tree.nodes
output_node = next((n for n in nodes if n.type == "OUTPUT_MATERIAL" and n.is_active_output), None) or next(
(n for n in nodes if n.type == "OUTPUT_MATERIAL"), None
)
if output_node:
result = cls._color_from_shader_socket(output_node.inputs["Surface"])
if result:
return result
# Fallback: scan all shader nodes if no output node or graph traversal found nothing
for node in nodes:
if node.type == "BSDF_PRINCIPLED":
return cls._color_from_principled(node)
for node in nodes:
if node.type in ("BSDF_DIFFUSE", "DIFFUSE_BSDF"):
return cls._resolve_color_socket(node.inputs["Color"]), 0.0
for node in nodes:
if node.type == "BSDF_GLASS":
return cls._resolve_color_socket(node.inputs["Color"]), 0.0
color = tuple(material.diffuse_color[:3])
transparency = 1.0 - material.diffuse_color[3]
return color, transparency
@classmethod
def _collect_upstream_sources(cls, socket: bpy.types.NodeSocket, seen: set[str]) -> list[tuple[str, object]]:
"""Recursively collect all upstream colour/image sources reachable from *socket*."""
results = []
for link in socket.links:
node = link.from_node
if node.name in seen:
continue
seen.add(node.name)
if node.type == "TEX_IMAGE":
results.append(("IMAGE", node.image))
elif node.type == "VALTORGB":
results.append(("COLORRAMP", node))
else:
for inp in node.inputs:
if inp.is_linked:
results.extend(cls._collect_upstream_sources(inp, seen))
return results
@classmethod
def _upstream_color_source(
cls, socket: bpy.types.NodeSocket, seen: set[str] | None = None
) -> tuple[str, object] | None:
sources = cls._collect_upstream_sources(socket, set() if seen is None else seen)
# Prefer a concrete image texture over a colour ramp (which may be greyscale/procedural).
for s in sources:
if s[0] == "IMAGE":
return s
for s in sources:
if s[0] == "COLORRAMP":
return s
return None
@classmethod
def _resolve_color_socket(cls, socket: bpy.types.NodeSocket) -> tuple[float, float, float]:
source = cls._upstream_color_source(socket)
if source is None:
return tuple(socket.default_value[:3])
kind, obj = source
if kind == "IMAGE":
return cls._average_image_color(obj)
if kind == "COLORRAMP":
return cls._average_colorramp_color(obj)
return tuple(socket.default_value[:3])
@staticmethod
def _average_image_color(image: bpy.types.Image) -> tuple[float, float, float]:
pixels = image.pixels[:]
n = len(pixels) // 4
if n == 0:
return (0.5, 0.5, 0.5)
step = max(1, n // 4096)
r_sum = g_sum = b_sum = 0.0
count = 0
for i in range(0, n, step):
base = i * 4
r_sum += pixels[base]
g_sum += pixels[base + 1]
b_sum += pixels[base + 2]
count += 1
return (r_sum / count, g_sum / count, b_sum / count)
@staticmethod
def _average_colorramp_color(node: bpy.types.Node) -> tuple[float, float, float]:
elements = node.color_ramp.elements
if not elements:
return (0.5, 0.5, 0.5)
r = sum(e.color[0] for e in elements) / len(elements)
g = sum(e.color[1] for e in elements) / len(elements)
b = sum(e.color[2] for e in elements) / len(elements)
return (r, g, b)
@classmethod
def is_editing_styles(cls) -> bool:
props = cls.get_style_props()
@@ -814,179 +674,9 @@ class Style(bonsai.core.tool.Style):
props = cls.get_material_style_props(blender_material)
props.active_style_type = props.active_style_type
@classmethod
def get_branch_outputs(
cls, material: bpy.types.Material
) -> tuple[bpy.types.ShaderNode | None, bpy.types.ShaderNode | None]:
"""Return (external_output_node, flat_output_node), or (None, None) if not dual-branch."""
if not material.node_tree:
return None, None
ext = material.node_tree.nodes.get("BIM_Output_External")
fast = material.node_tree.nodes.get("BIM_Output_Flat")
return ext, fast
@classmethod
def _remove_external_branch(cls, material: bpy.types.Material) -> None:
"""Remove all nodes reachable from BIM_Output_External (walks links backwards)."""
if not material.node_tree:
return
nodes = material.node_tree.nodes
output = nodes.get("BIM_Output_External")
if not output:
return
to_remove: set[str] = set()
stack = [output]
while stack:
node = stack.pop()
if node.name in to_remove:
continue
to_remove.add(node.name)
for inp in node.inputs:
for link in inp.links:
stack.append(link.from_node)
for name in list(to_remove):
n = nodes.get(name)
if n:
nodes.remove(n)
@classmethod
def _build_flat_branch_nodes(cls, material: bpy.types.Material) -> bpy.types.ShaderNode:
"""Add a Principled BSDF flat-branch to material's existing node tree.
Reads IfcSurfaceStyleRendering or IfcSurfaceStyleShading from the linked IFC entity.
Defaults to a white BSDF when no IFC shading data is available.
Returns the new Material Output node (named BIM_Output_Flat, is_active_output=False).
"""
from mathutils import Vector
style_elements = cls.get_style_elements(material)
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
bsdf.location = Vector((10, -600))
output = nodes.new("ShaderNodeOutputMaterial")
output.name = "BIM_Output_Flat"
output.location = Vector((300, -600))
output.is_active_output = False
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
rendering_style = None
shading_only = None
for surface_style in style_elements.values():
if surface_style.is_a() == "IfcSurfaceStyleShading":
shading_only = surface_style
elif surface_style.is_a("IfcSurfaceStyleRendering"):
rendering_style = surface_style
shading_only = None
if rendering_style:
d = tool.Loader.surface_style_to_dict(rendering_style)
if d.get("DiffuseColour"):
ctype, cval = d["DiffuseColour"]
if ctype == "IfcColourRgb":
bsdf.inputs["Base Color"].default_value = cval + (1,)
solid_color = cval
else:
cval = tuple(v * cval for v in d["SurfaceColour"])
bsdf.inputs["Base Color"].default_value = cval + (1,)
solid_color = cval
else:
r, g, b = d["SurfaceColour"]
bsdf.inputs["Base Color"].default_value = (r, g, b, 1.0)
solid_color = (r, g, b)
if d.get("SpecularColour"):
ctype, cval = d["SpecularColour"]
if ctype == "IfcNormalisedRatioMeasure":
bsdf.inputs["Metallic"].default_value = cval
if d.get("SpecularHighlight"):
bsdf.inputs["Roughness"].default_value = d["SpecularHighlight"]
transparency = d.get("Transparency") or 0.0
bsdf.inputs["Alpha"].default_value = 1 - transparency
if transparency > 0:
material.blend_method = "BLEND"
material.diffuse_color = solid_color + (1.0 - transparency,)
elif shading_only:
d = tool.Loader.surface_style_to_dict(shading_only)
r, g, b = d["SurfaceColour"]
alpha = 1 - (d.get("Transparency") or 0.0)
bsdf.inputs["Base Color"].default_value = (r, g, b, 1.0)
bsdf.inputs["Alpha"].default_value = alpha
if alpha < 1.0:
material.blend_method = "BLEND"
material.diffuse_color = (r, g, b, alpha)
# else: leave default white Principled BSDF
return output
@classmethod
def setup_dual_branch(cls, material: bpy.types.Material, ext_material: bpy.types.Material) -> bool:
"""Build a dual-branch node tree: flat branch from IFC data + external branch from ext_material.
Clears any existing nodes and builds both branches from scratch.
External branch output (BIM_Output_External) is set active Pretty mode.
Flat branch output (BIM_Output_Flat) is inactive Flat mode.
Returns True on success; False if no shader editor is available (falls back to single-branch).
"""
cls.set_use_nodes(material, True)
for n in material.node_tree.nodes[:]:
material.node_tree.nodes.remove(n)
cls._build_flat_branch_nodes(material)
ext_output = tool.Blender.copy_node_graph_additive(material, ext_material)
if not ext_output:
# No shader editor available: fall back to single-branch
tool.Blender.copy_node_graph(material, ext_material)
return False
ext_output.name = "BIM_Output_External"
ext_output.is_active_output = True
material["bim_dual_branch"] = True
return True
@classmethod
def update_external_branch(cls, material: bpy.types.Material, ext_material: bpy.types.Material) -> None:
"""Replace the external-branch nodes of an already dual-branch material."""
cls._remove_external_branch(material)
ext_output = tool.Blender.copy_node_graph_additive(material, ext_material)
if ext_output:
ext_output.name = "BIM_Output_External"
ext_output.is_active_output = True
fast = material.node_tree.nodes.get("BIM_Output_Flat")
if fast:
fast.is_active_output = False
@classmethod
def sync_flat_branch_shading(
cls, material: bpy.types.Material, surface_colour: tuple[float, float, float], transparency: float
) -> None:
"""Update the flat-branch Principled BSDF with new shading values.
Call this after creating or editing IfcSurfaceStyleShading so the flat branch
stays in sync without requiring a full setup_dual_branch rebuild.
"""
if not material.node_tree:
return
fast_output = material.node_tree.nodes.get("BIM_Output_Flat")
if not fast_output:
return
for link in fast_output.inputs["Surface"].links:
if link.from_node.type == "BSDF_PRINCIPLED":
bsdf = link.from_node
r, g, b = surface_colour
bsdf.inputs["Base Color"].default_value = (r, g, b, 1.0)
bsdf.inputs["Alpha"].default_value = 1.0 - transparency
break
@classmethod
def switch_shading(cls, blender_material: bpy.types.Material, style_type: StyleType) -> None:
if style_type == "External":
ext, fast = cls.get_branch_outputs(blender_material)
if ext and fast:
ext.is_active_output = True
fast.is_active_output = False
blender_material.update_tag()
return
try:
bpy.ops.bim.activate_external_style(material_name=blender_material.name)
except RuntimeError as error:
@@ -994,41 +684,21 @@ class Style(bonsai.core.tool.Style):
return
raise error
elif style_type == "Shading":
ext, fast = cls.get_branch_outputs(blender_material)
if ext and fast:
fast.is_active_output = True
ext.is_active_output = False
blender_material.update_tag()
return
style_elements = tool.Style.get_style_elements(blender_material)
rendering_style = None
texture_style = None
shading_only_style = None
for surface_style in style_elements.values():
if surface_style.is_a() == "IfcSurfaceStyleShading":
shading_only_style = surface_style
tool.Loader.create_surface_style_shading(blender_material, surface_style)
elif surface_style.is_a("IfcSurfaceStyleRendering"):
rendering_style = surface_style
shading_only_style = None # rendering overrides shading-only path
tool.Loader.create_surface_style_rendering(blender_material, surface_style)
elif surface_style.is_a("IfcSurfaceStyleWithTextures"):
texture_style = surface_style
if rendering_style and texture_style:
tool.Loader.create_surface_style_with_textures(blender_material, rendering_style, texture_style)
elif shading_only_style and not rendering_style:
# create a minimal Principled BSDF so Material Preview/Rendered shows the colour instead of white.
tool.Style.set_use_nodes(blender_material, True)
tool.Loader.restart_material_node_tree(blender_material)
bsdf = tool.Blender.get_material_node(blender_material, "BSDF_PRINCIPLED")
if bsdf:
r, g, b, a = blender_material.diffuse_color
bsdf.inputs["Base Color"].default_value = (r, g, b, 1)
bsdf.inputs["Alpha"].default_value = a
if a < 1.0:
blender_material.blend_method = "BLEND"
else:
assert False, f"Invalid style type found: {style_type}"
@@ -1074,36 +744,3 @@ class Style(bonsai.core.tool.Style):
elements = ifcopenshell.util.element.get_elements_by_style(tool.Ifc.get(), style)
objects = [tool.Ifc.get_object(e) for e in elements]
tool.Geometry.reload_representation(objects)
_last_shading_type: str | None = None
@classmethod
def restore_material_style_types(cls, shading_type: str) -> None:
"""Set each IFC material's active_style_type to the richest available for the given viewport mode.
In SOLID mode all materials use "Shading".
In MATERIAL_PREVIEW / RENDERED, materials with an external .blend style use "External"
unless prefer_ifc_shading is set on that material.
"""
if cls._last_shading_type == shading_type:
return
cls._last_shading_type = shading_type
for material in bpy.data.materials:
if not tool.Blender.get_ifc_definition_id(material):
continue
props = cls.get_material_style_props(material)
style_elements = cls.get_style_elements(material)
if shading_type == "SOLID":
props.active_style_type = "Shading"
shading = style_elements.get("IfcSurfaceStyleRendering") or style_elements.get("IfcSurfaceStyleShading")
if shading:
d = tool.Loader.surface_style_to_dict(shading)
alpha = 1.0 - (d.get("Transparency") or 0.0)
material.diffuse_color = d["SurfaceColour"] + (alpha,)
else: # MATERIAL_PREVIEW or RENDERED
if cls.has_blender_external_style(style_elements) and not props.prefer_ifc_shading:
props.active_style_type = "External"
else:
props.active_style_type = "Shading"
material.update_tag()
+6 -12
View File
@@ -12,19 +12,16 @@ Scenario: Ensure added booleans are marked as manual
And I click "OK"
And the object "IfcFurniture/Unnamed" exists
And I toggle edit mode
And the variable "extrusion" is "{ifc}.by_type('IfcExtrudedAreaSolid')[0].id()"
And the object "Item/IfcExtrudedAreaSolid/{extrusion}" exists
And the object "Item/IfcExtrudedAreaSolid/73" exists
And I open the "Add Item" menu
When I click "Half Space Solid"
And the variable "half_space" is "{ifc}.by_type('IfcHalfSpaceSolid')[0].id()"
And the variable "boolean" is "{ifc}.by_type('IfcBooleanResult')[0].id()"
And the object "Item/IfcHalfSpaceSolid/{half_space}" exists
And the object "Item/IfcHalfSpaceSolid/90" exists
And I deselect all objects
And I toggle edit mode
And I select the object "IfcFurniture/Unnamed"
And I look at the "Property Sets" panel
Then I see "BBIM_Boolean"
And I see "[{boolean}]"
And I see "[91]"
Scenario: Ensure removed booleans are unmarked as manual
Given an empty IFC project
@@ -36,20 +33,17 @@ Scenario: Ensure removed booleans are unmarked as manual
And I click "OK"
And the object "IfcFurniture/Unnamed" exists
And I toggle edit mode
And the variable "extrusion" is "{ifc}.by_type('IfcExtrudedAreaSolid')[0].id()"
And the object "Item/IfcExtrudedAreaSolid/{extrusion}" exists
And the object "Item/IfcExtrudedAreaSolid/73" exists
And I open the "Add Item" menu
And I click "Half Space Solid"
And the variable "half_space" is "{ifc}.by_type('IfcHalfSpaceSolid')[0].id()"
And the variable "boolean" is "{ifc}.by_type('IfcBooleanResult')[0].id()"
And I deselect all objects
And I toggle edit mode
And I select the object "IfcFurniture/Unnamed"
And I toggle edit mode
And I select the object "Item/IfcHalfSpaceSolid/{half_space}"
And I select the object "Item/IfcHalfSpaceSolid/90"
When I delete the selected objects
And I toggle edit mode
And I select the object "IfcFurniture/Unnamed"
And I look at the "Property Sets" panel
Then I don't see "BBIM_Boolean"
And I don't see "[{boolean}]"
And I don't see "[91]"
+15 -1
View File
@@ -361,22 +361,31 @@ Scenario: Edit pset length property
Given an empty IFC project
And I press "mesh.add_stair"
And the variable "pset" is "tool.Pset.get_element_pset(tool.Ifc.get_entity(bpy.context.active_object), 'Pset_StairFlightCommon').id()"
And the variable "si_conversion" is "ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())"
And I press "bim.enable_pset_editing(pset_id={pset}, obj='IfcStairFlight/StairFlight', obj_type='Object')"
# Testing IfcPositiveLengthMeasure type of prop
Then "active_object.PsetProperties.properties['TreadLength'].metadata.special_type" is "LENGTH"
And "active_object.PsetProperties.properties['TreadLength'].metadata.float_value" is "250"
And "active_object.PsetProperties.properties['TreadLength'].metadata.length_value" is roughly "0.25"
When I set "active_object.PsetProperties.properties['TreadLength'].metadata.float_value" to "350"
Then "active_object.PsetProperties.properties['TreadLength'].metadata.float_value" is roughly "350"
When I set "active_object.PsetProperties.properties['TreadLength'].metadata.length_value" to "0.45"
Then "active_object.PsetProperties.properties['TreadLength'].metadata.float_value" is roughly "450"
# Testing IfcLengthMeasure type of prop
Then "active_object.PsetProperties.properties['NosingLength'].metadata.special_type" is "LENGTH"
And "active_object.PsetProperties.properties['NosingLength'].metadata.float_value" is "0.0"
And "active_object.PsetProperties.properties['NosingLength'].metadata.length_value" is roughly "0.0"
When I set "active_object.PsetProperties.properties['NosingLength'].metadata.float_value" to "350"
Then "active_object.PsetProperties.properties['NosingLength'].metadata.float_value" is roughly "350"
When I set "active_object.PsetProperties.properties['NosingLength'].metadata.length_value" to "0.45"
Then "active_object.PsetProperties.properties['NosingLength'].metadata.float_value" is roughly "450"
When I press "bim.edit_pset(obj='IfcStairFlight/StairFlight', obj_type='Object')"
Then nothing happens
@@ -385,14 +394,19 @@ Scenario: Edit qset length property
And I press "mesh.add_stair"
And I press "bim.perform_quantity_take_off"
And the variable "pset" is "tool.Pset.get_element_pset(tool.Ifc.get_entity(bpy.context.active_object), 'Qto_StairFlightBaseQuantities').id()"
And the variable "si_conversion" is "ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())"
And I press "bim.enable_pset_editing(pset_id={pset}, obj='IfcStairFlight/StairFlight', obj_type='Object')"
# Testing Q_LENGTH type of prop
Then "active_object.PsetProperties.properties['Length'].metadata.special_type" is "LENGTH"
And "active_object.PsetProperties.properties['Length'].metadata.float_value" is roughly "2156.485"
And "active_object.PsetProperties.properties['Length'].metadata.length_value" is roughly "2.156"
When I set "active_object.PsetProperties.properties['Length'].metadata.float_value" to "350"
Then "active_object.PsetProperties.properties['Length'].metadata.float_value" is roughly "350"
Then "active_object.PsetProperties.properties['Length'].metadata.length_value" is roughly "0.35"
When I set "active_object.PsetProperties.properties['Length'].metadata.length_value" to "0.45"
Then "active_object.PsetProperties.properties['Length'].metadata.float_value" is roughly "450"
When I press "bim.edit_pset(obj='IfcStairFlight/StairFlight', obj_type='Object')"
Then nothing happens
@@ -32,91 +32,64 @@ from test.bim.bootstrap import NewIfc
pytestmark = pytest.mark.project
def _make_library_file(*, with_child: bool = False) -> ifcopenshell.file:
"""Build a spec-valid IFC4 library file: IfcProject + IfcProjectLibrary declared to it.
def _make_library_only_file(*, with_child: bool = False) -> ifcopenshell.file:
"""Build a minimal IFC4 file containing only an IfcProjectLibrary (no IfcProject).
Per the IFC Project Context concept template, every project data set (library
files included) shall contain exactly one IfcProject, and IfcProjectLibrary
instances are assigned to it via IfcRelDeclares. This matches how every library
file shipped in bonsai/bim/data/libraries is actually authored. ``with_child=True``
also nests a sub-library under the root via IfcRelNests.
Per IFC4+, a file must contain at least one IfcContext; IfcProjectLibrary is a
valid root on its own. ``with_child=True`` nests a sub-library under the root via
IfcRelNests, mirroring real authored library files.
"""
library_file = ifcopenshell.api.project.create_file(version="IFC4")
project = ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProject", name="Demo Project")
root = ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProjectLibrary", name="RootLib")
ifcopenshell.api.project.assign_declaration(library_file, definitions=[root], relating_context=project)
if with_child:
child = ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProjectLibrary", name="ChildLib")
ifcopenshell.api.nest.assign_object(library_file, [child], root)
return library_file
class TestLibraryFile(NewIfc):
"""Project-library UI code operating on a spec-valid model (IfcProject root).
class TestLibraryOnlyFile(NewIfc):
def test_get_root_context_returns_project_library_when_no_project(self):
library_file = _make_library_only_file()
assert not library_file.by_type("IfcProject")
A file containing only IfcProjectLibrary and no IfcProject is not valid IFC and
is not supported; see test_parent_libraries_enum_raises_for_a_file_without_a_project.
"""
root = tool.Project.get_root_context(library_file)
def test_parent_libraries_enum_raises_for_a_file_without_a_project(self):
library_file = ifcopenshell.api.project.create_file(version="IFC4")
ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProjectLibrary", name="RootLib")
IfcStore.library_file = library_file
try:
with pytest.raises(IndexError):
ProjectLibraryData.parent_libraries_enum()
finally:
IfcStore.library_file = None
assert root.is_a("IfcProjectLibrary")
assert root.Name == "RootLib"
def test_get_parent_library_returns_project_for_declared_root_library(self):
library_file = _make_library_file()
project = library_file.by_type("IfcProject")[0]
def test_get_parent_library_returns_none_for_root_library(self):
library_file = _make_library_only_file()
root = library_file.by_type("IfcProjectLibrary")[0]
assert tool.Project.get_parent_library(root) == project
assert tool.Project.get_parent_library(root) is None
def test_get_parent_library_returns_the_library_for_a_nested_sub_library(self):
library_file = _make_library_file(with_child=True)
root = next(lib for lib in library_file.by_type("IfcProjectLibrary") if lib.Name == "RootLib")
child = next(lib for lib in library_file.by_type("IfcProjectLibrary") if lib.Name == "ChildLib")
assert tool.Project.get_parent_library(child) == root
def test_get_parent_library_returns_none_for_an_orphaned_library(self):
library_file = ifcopenshell.api.project.create_file(version="IFC4")
orphan = ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProjectLibrary", name="Orphan")
assert tool.Project.get_parent_library(orphan) is None
def test_get_project_hierarchy_roots_libraries_under_the_project(self):
library_file = _make_library_file(with_child=True)
project = library_file.by_type("IfcProject")[0]
def test_get_project_hierarchy_skips_root_library(self):
library_file = _make_library_only_file(with_child=True)
root = next(lib for lib in library_file.by_type("IfcProjectLibrary") if lib.Name == "RootLib")
child = next(lib for lib in library_file.by_type("IfcProjectLibrary") if lib.Name == "ChildLib")
hierarchy = tool.Project.get_project_hierarchy(library_file)
assert root in hierarchy[project]
assert root in hierarchy
assert child in hierarchy[root]
def test_project_library_data_loads_with_unique_enum_keys(self):
IfcStore.library_file = _make_library_file(with_child=True)
def test_project_library_data_loads_without_crash(self):
IfcStore.library_file = _make_library_only_file()
try:
ProjectLibraryData.is_loaded = False
ProjectLibraryData.load()
assert ProjectLibraryData.is_loaded
enum = ProjectLibraryData.data["parent_libraries_enum"]
keys = [entry[0] for entry in enum]
assert len(keys) == len(set(keys))
assert enum[0][1].startswith("IfcProject ")
assert len(enum) == 1
assert enum[0][1].startswith("IfcProjectLibrary ")
finally:
IfcStore.library_file = None
ProjectLibraryData.is_loaded = False
def test_refresh_library_succeeds(self):
def test_refresh_library_succeeds_on_library_only_file(self):
import bpy
IfcStore.library_file = _make_library_file(with_child=True)
IfcStore.library_file = _make_library_only_file(with_child=True)
try:
result = bpy.ops.bim.refresh_library()
assert result == {"FINISHED"}
@@ -124,65 +97,13 @@ class TestLibraryFile(NewIfc):
IfcStore.library_file = None
ProjectLibraryData.is_loaded = False
def test_edit_project_library_moves_a_project_declared_library_under_another_library(self):
def test_add_project_library_nests_under_root_when_no_project(self):
import bpy
library_file = _make_library_file()
project = library_file.by_type("IfcProject")[0]
root = library_file.by_type("IfcProjectLibrary")[0]
target = ifcopenshell.api.root.create_entity(library_file, ifc_class="IfcProjectLibrary", name="TargetLib")
ifcopenshell.api.project.assign_declaration(library_file, definitions=[target], relating_context=project)
IfcStore.library_file = library_file
try:
props = tool.Project.get_project_props()
props.selected_project_library = str(root.id())
props.is_editing_project_library = True
props.parent_library = str(target.id())
result = bpy.ops.bim.edit_project_library()
assert result == {"FINISHED"}
assert tool.Project.get_parent_library(root) == target
assert root.Nests and root.Nests[0].RelatingObject == target
assert not root.HasContext
finally:
if props.is_editing_project_library:
props.is_editing_project_library = False
IfcStore.library_file = None
ProjectLibraryData.is_loaded = False
def test_edit_project_library_moves_a_nested_library_back_under_the_project(self):
import bpy
library_file = _make_library_file(with_child=True)
project = library_file.by_type("IfcProject")[0]
child = next(lib for lib in library_file.by_type("IfcProjectLibrary") if lib.Name == "ChildLib")
IfcStore.library_file = library_file
try:
props = tool.Project.get_project_props()
props.selected_project_library = str(child.id())
props.is_editing_project_library = True
props.parent_library = str(project.id())
result = bpy.ops.bim.edit_project_library()
assert result == {"FINISHED"}
assert tool.Project.get_parent_library(child) == project
assert child.HasContext and child.HasContext[0].RelatingContext == project
assert not child.Nests
finally:
if props.is_editing_project_library:
props.is_editing_project_library = False
IfcStore.library_file = None
ProjectLibraryData.is_loaded = False
def test_add_project_library_declares_new_library_under_the_project_root(self):
import bpy
IfcStore.library_file = _make_library_file()
IfcStore.library_file = _make_library_only_file()
library_file = IfcStore.library_file
try:
project = library_file.by_type("IfcProject")[0]
root = library_file.by_type("IfcProjectLibrary")[0]
before = set(library_file.by_type("IfcProjectLibrary"))
result = bpy.ops.bim.add_project_library()
@@ -192,9 +113,9 @@ class TestLibraryFile(NewIfc):
new_libraries = after - before
assert len(new_libraries) == 1
new_library = next(iter(new_libraries))
assert new_library.HasContext
assert new_library.HasContext[0].RelatingContext == project
assert not new_library.Nests
assert new_library.Nests
assert new_library.Nests[0].RelatingObject == root
assert not new_library.HasContext
finally:
IfcStore.library_file = None
ProjectLibraryData.is_loaded = False
-4
View File
@@ -21,10 +21,6 @@ from typing import Any, Optional, Union
class bSDDClientStub:
def __init__(self):
# Mirrors bsdd.Client so tool.Bsdd.identifier_url() works against the stub.
self.baseurl = "https://api.bsdd.buildingsmart.org/api/"
def get_dictionary(self, dictionary_uri=None, include_test_dictionaries=False):
dicts = {
"dictionaries": [
+2 -26
View File
@@ -187,14 +187,7 @@ class PanelSpy:
after = ""
if self.spied_labels:
after = self.spied_labels[-1]
spied_operator = {
"operator": operator,
"icon": icon,
"text": text,
"kwargs": {},
"after": after,
"bl_idname": bl_idname,
}
spied_operator = {"operator": operator, "icon": icon, "text": text, "kwargs": {}, "after": after}
self.spied_operators.append(spied_operator)
return OperatorSpy(spied_operator)
elif self.spied_attr == "panel":
@@ -217,14 +210,6 @@ class OperatorSpy:
else:
self.spied_data["kwargs"][name] = value
@property
def bl_rna(self) -> Any:
# Mirror the real `UILayout.operator()` return value (an OperatorProperties
# instance), which exposes `.bl_rna` so panel code such as
# `"module" in op.bl_rna.properties` (bonsai/bim/helper.py) also works when
# drawing is spied on during BDD tests.
return getattr(bpy.types, self.spied_data["bl_idname"]).bl_rna
class TemplateListSpy(PanelSpy):
items: bpy.types.bpy_prop_collection_idprop[bpy.types.PropertyGroup]
@@ -468,7 +453,6 @@ def i_trigger_operator(operator):
@then(parsers.parse('I see "{text}"'))
def i_see_text(text):
assert panel_spy
text = replace_variables(text)
panel_spy.refresh_spy()
assert [l for l in panel_spy.spied_labels if text in l], f"Text {text} not found in {panel_spy.spied_labels}"
@@ -603,7 +587,6 @@ def i_select_the_row_where_i_see_text_in_the_nth_list(text, nth):
@then(parsers.parse('I don\'t see "{text}"'))
def i_dont_see_text(text):
assert panel_spy
text = replace_variables(text)
panel_spy.refresh_spy()
assert not [l for l in panel_spy.spied_labels if text in l], f"Text {text} found in {panel_spy.spied_labels}"
@@ -790,11 +773,7 @@ def i_create_default_mep_types():
with bpy.context.temp_override(active_object=bpy.data.objects["IfcActuatorType/ACTUATOR"]):
bpy.ops.bim.add_port()
# port at cube's left side
# Newly created ports are never given an explicit IFC `.Name` (see
# `core/system.py:create_port_at_cursor` / `tool/system.py`), so
# `tool.Loader.get_name()` falls back to the standard "Unnamed" convention
# used throughout Bonsai for freshly-created, not-yet-named elements.
bpy.data.objects["IfcDistributionPort/Unnamed"].location = (-0.5, 0, 0)
bpy.data.objects["IfcDistributionPort/Port"].location = (-0.5, 0, 0)
bpy.ops.bim.hide_ports()
@@ -1094,7 +1073,6 @@ def then_the_object_name_is_placed_in_the_collection_collection(name: str, colle
@given(parsers.parse('additionally the object "{name}" is selected'))
@when(parsers.parse('additionally the object "{name}" is selected'))
def additionally_the_object_name_is_selected(name):
name = replace_variables(name)
obj = bpy.context.scene.objects.get(name)
if not obj:
total = len(bpy.context.scene.objects)
@@ -1175,7 +1153,6 @@ def nothing_happens():
@when(parsers.parse('the object "{name}" exists'))
@then(parsers.parse('the object "{name}" exists'))
def the_object_name_exists(name: str) -> bpy.types.Object:
name = replace_variables(name)
# Some objects from linked collections may share the same name. This disambiguates them.
if name.startswith("Col:"):
_, collection_name, name = name.split(":")
@@ -1190,7 +1167,6 @@ def the_object_name_exists(name: str) -> bpy.types.Object:
@then(parsers.parse('the object "{name}" does not exist'))
def the_object_name_does_not_exist(name) -> None:
name = replace_variables(name)
obj = bpy.data.objects.get(name)
assert obj is None, f'The object "{name}" exists'
-328
View File
@@ -1,328 +0,0 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import bpy
import ifcopenshell
import ifcopenshell.api.pset
import ifcopenshell.api.root
import ifcopenshell.api.unit
import pytest
import bonsai.bim.prop
import bonsai.tool as tool
from test.bim.bootstrap import NewFile
def import_single_property(ifc, element, prop):
"""Import a single existing IfcProperty into a real, addon-registered
PsetProperties collection, exactly as the property editor does, and
return its `metadata` (an `Attribute`)."""
pset = ifcopenshell.api.pset.add_pset(ifc, product=element, name="Pset_Test")
pset.HasProperties = [prop]
obj = bpy.data.objects.new(prop.Name, None)
tool.Ifc.link(element, obj)
props = obj.PsetProperties
tool.Pset.import_pset_from_existing(pset, props, None)
return props.properties[prop.Name].metadata
class TestGetDisplayName(NewFile):
def test_appends_the_resolved_unit_symbol(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
pressure = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="PRESSUREUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[pressure])
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcPressureMeasure(5.0))
metadata = import_single_property(ifc, element, prop)
assert metadata.display_name == "Foo, Pa"
def test_falls_back_to_the_plain_name_when_no_unit_is_resolvable(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
# No units assigned to the project at all -- nothing to resolve.
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcPressureMeasure(5.0))
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_symbol == ""
assert metadata.display_name == "Foo"
def test_falls_back_to_the_plain_name_for_a_non_measure_property(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcText("Bar"))
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_symbol == ""
assert metadata.display_name == "Foo"
def test_resolves_a_unit_explicitly_attached_to_a_generic_numeric_value(self):
# A generic IfcReal has no unit semantics per its own declared type, but a property
# set may still explicitly attach a real Unit to a specific instance to convey the
# dimension the spec's generic typing doesn't. That explicit Unit is real, deliberate
# data (not incidental/stray), so it should resolve normally.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcReal(150.0), Unit=length_mm)
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_symbol == "mm"
assert metadata.display_name == "Foo, mm"
class TestGetAttributeUnitEnumItems(NewFile):
def test_returns_default_plus_one_per_candidate_for_a_measurable_type(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2.5))
metadata = import_single_property(ifc, element, prop)
items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
identifiers = [i[0] for i in items]
assert identifiers[0] == "0"
assert str(length_mm.id()) in identifiers
assert str(length_m.id()) in identifiers
assert len(items) == 3 # Default + mm + m
def test_returns_just_default_for_non_measurable_types(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcText("Bar"))
metadata = import_single_property(ifc, element, prop)
items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
assert [i[0] for i in items] == ["0"]
class TestGetUnitEnumItemsForSpecialType(NewFile):
def test_matches_the_attribute_wrapper_output(self):
# Regression test for extracting get_unit_enum_items_for_special_type out of
# get_attribute_unit_enum_items: the wrapper must still produce identical items for
# the plain (no own-unit-fallback-needed) case.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2.5))
metadata = import_single_property(ifc, element, prop)
direct_items = bonsai.bim.prop.get_unit_enum_items_for_special_type(metadata.special_type, ifc)
wrapper_items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
assert direct_items == wrapper_items
def test_returns_just_default_when_ifc_file_is_none(self):
assert bonsai.bim.prop.get_unit_enum_items_for_special_type("LENGTH", None) == [("0", "Default", "")]
class TestUnitSymbolWithAreaVolumeDerivedFromLength(NewFile):
"""Regression test: AREAUNIT/VOLUMEUNIT have no IfcDerivedUnitEnum member, so a project
whose area/volume default is an IfcDerivedUnit rather than a literal-UnitType-matching
IfcSIUnit/IfcConversionBasedUnit has no literal UnitType to match on.
ifcopenshell.util.unit.get_project_unit() used to only match by literal UnitType, so the
read-only unit symbol and the edit-mode "Default (<symbol>)" picker entry both silently
fell back to no symbol at all in that case.
"""
def setup_project_with_derived_area_and_volume(self, ifc):
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
area = ifcopenshell.api.unit.add_derived_unit(ifc, "USERDEFINED", "area-ish", {length: 2})
volume = ifcopenshell.api.unit.add_derived_unit(ifc, "USERDEFINED", "volume-ish", {length: 3})
ifcopenshell.api.unit.assign_unit(ifc, units=[length, area, volume])
def test_default_picker_entry_shows_the_resolved_symbol(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
self.setup_project_with_derived_area_and_volume(ifc)
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcAreaMeasure(5.0))
metadata = import_single_property(ifc, element, prop)
items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
assert items[0][1] == "Default (m2)"
def test_read_only_display_resolves_the_symbol(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
self.setup_project_with_derived_area_and_volume(ifc)
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcVolumeMeasure(5.0))
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_symbol == "m3"
assert metadata.display_name == "Foo, m3"
class TestUpdateAttributeUnitId(NewFile):
def test_syncs_unit_id_and_converts_float_value_when_unit_id_enum_changes(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2500.0))
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_id == 0
assert metadata.float_value == 2500.0
assert metadata.unit_symbol == "mm"
assert metadata.display_name == "Foo, mm"
metadata.unit_id_enum = str(length_m.id())
assert metadata.unit_id == length_m.id()
assert metadata.float_value == pytest.approx(2.5) # converted, not just relabeled
# Regression test: unit_symbol/display_name used to be a snapshot taken once at import
# time, so picking a different unit converted the value but left the label showing the
# old unit's symbol.
assert metadata.unit_symbol == "m"
assert metadata.display_name == "Foo, m"
class TestUnitSymbolReflectsLiveProjectState(NewFile):
def test_symbol_updates_after_a_project_default_unit_is_assigned_later(self):
# Regression test: unit_symbol used to be a snapshot computed once at import time, so a
# property/quantity imported before its measure type had a project default unit assigned
# kept showing no symbol even after one was added, unless the panel was closed and
# reopened (re-triggering import). It's now computed fresh on every access.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
# No AREAUNIT assigned yet.
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcAreaMeasure(5.0))
metadata = import_single_property(ifc, element, prop)
assert metadata.unit_symbol == ""
assert metadata.display_name == "Foo"
area = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="AREAUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[area])
assert metadata.unit_symbol == "m2"
assert metadata.display_name == "Foo, m2"
class TestImportPsetFromExistingWithAGenericNumericValueAndAnExplicitUnit(NewFile):
def test_run(self):
# Regression test: some property set specifications declare a property as a generic
# IfcReal rather than a proper measure class, relying on an explicit Unit attribute
# alone to convey the dimension. get_property_unit() already handled this fine for
# display (it checks prop.Unit before looking at NominalValue's type at all), but
# get_special_type_for_prop() only looked at NominalValue's class ending in "Measure"
# -- so special_type came back "", the picker never appeared, and the real Unit
# override never got seeded into unit_id even though it was legitimately set.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcReal(150.0), Unit=length_mm
)
metadata = import_single_property(ifc, element, prop)
assert metadata.special_type == "LENGTH"
assert tool.Pset.is_measurable_special_type(metadata.special_type)
assert metadata.unit_symbol == "mm"
assert metadata.unit_id == length_mm.id()
assert metadata.unit_id_enum == str(length_mm.id())
items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
assert str(length_mm.id()) in [i[0] for i in items]
class TestImportPsetFromExistingWithAStrayUnitOnANonMeasureProperty(NewFile):
def test_run(self):
# Regression test: some real-world exporters set a Unit on a property whose
# NominalValue isn't actually a measure (e.g. a text classification), which used
# to crash import_pset_from_existing with "enum '<id>' not found in ('0')" -- unit_id
# was seeded from prop.Unit unconditionally, before the special_type gate that decides
# whether Unit is even meaningful for this property.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcLabel("Bar"), Unit=length_m
)
metadata = import_single_property(ifc, element, prop) # must not raise
assert metadata.special_type == ""
assert metadata.unit_id == 0
assert metadata.unit_id_enum == "0"
class TestGetAttributeUnitEnumItemsWithAMismatchedUnit(NewFile):
def test_own_unit_is_always_representable_even_if_not_a_normal_candidate(self):
# Regression test: a property's own Unit might not satisfy
# get_candidate_units_for_special_type's matching (e.g. mismatched UnitType in messy
# real-world data). Seeding must never crash trying to select it, and it should still
# show up in the picker so the user can see/change it.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
# A LENGTHUNIT attached to a PRESSURE-typed property -- a real mismatch, not a candidate
# get_candidate_units_for_special_type("PRESSURE", ...) would ever return.
mismatched_unit = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcPressureMeasure(5.0), Unit=mismatched_unit
)
metadata = import_single_property(ifc, element, prop) # must not raise
assert metadata.special_type == "PRESSURE"
assert metadata.unit_id == mismatched_unit.id()
assert metadata.unit_id_enum == str(mismatched_unit.id())
items = bonsai.bim.prop.get_attribute_unit_enum_items(metadata, bpy.context)
assert str(mismatched_unit.id()) in [i[0] for i in items]
-4
View File
@@ -497,8 +497,6 @@ class TestGitMergetool:
with tempfile.TemporaryDirectory() as tmpdir:
ifc_path = os.path.join(tmpdir, "model.ifc")
mock_repo = mock.MagicMock()
# A clean mergetool resolution leaves no unmerged blobs in the index.
mock_repo.index.unmerged_blobs.return_value = {}
IfcGitRepo.repo = mock_repo
result = IfcGit.git_mergetool("ifcmerge", ifc_path)
assert result is None
@@ -513,8 +511,6 @@ class TestGitMergetool:
report_path = ifc_path + ".ifcmerge"
open(report_path, "w").close()
mock_repo = mock.MagicMock()
# A clean mergetool resolution leaves no unmerged blobs in the index.
mock_repo.index.unmerged_blobs.return_value = {}
IfcGitRepo.repo = mock_repo
result = IfcGit.git_mergetool("ifcmerge", ifc_path)
assert result is None
-28
View File
@@ -56,31 +56,3 @@ class TestValidateInput(NewFile):
# Angle.
assert subject.validate_input("25", "A") == (True, "25.0")
class TestCalculateDistanceAndAngle(NewFile):
def test_it_does_not_crash_when_distance_is_zero_and_should_round(self, monkeypatch):
# Regression test for #8597: right after placing the first polyline
# point, the initial mouse sample can equal the last placed point
# (distance == 0), e.g. entering the viewport on a YZ plane wall.
# angle_round_threshold used to only be assigned in the
# `distance > 0` branch, crashing when should_round reads it here.
# get_increment_snap_value requires a real 3D viewport rv3d, which
# is unrelated to this bug, so it's stubbed out for a headless run.
monkeypatch.setattr(tool.Snap, "get_increment_snap_value", classmethod(lambda cls, context: 1.0))
polyline_props = tool.Model.get_polyline_props()
mouse_point = polyline_props.snap_mouse_point.add()
mouse_point.x, mouse_point.y, mouse_point.z = 0, 0, 0
tool_state = subject.create_tool_state()
tool_state.is_input_on = False
tool_state.use_default_container = False
tool_state.plane_method = "YZ"
input_ui = subject.create_input_ui(input_options=["D", "A", "X", "Y", "Z"])
subject.calculate_distance_and_angle(bpy.context, input_ui, tool_state, should_round=True)
assert input_ui.get_number_value("D") == 0
assert input_ui.get_number_value("A") == 0
-340
View File
@@ -20,9 +20,6 @@ import bpy
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.api.pset
import ifcopenshell.api.root
import ifcopenshell.api.unit
import pytest
import bonsai.core.tool
import bonsai.tool as tool
@@ -55,340 +52,3 @@ class TestIsPsetEmpty(NewFile):
assert subject.is_pset_empty(pset) is False
ifcopenshell.api.pset.edit_pset(ifc, pset=pset, properties={"Foo": None})
assert subject.is_pset_empty(pset) is True
class TestEditingAnOverriddenUnitPropertyRoundTrips(NewFile):
def test_run(self):
# Project default is mm, but this property is authored directly in m.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
pset = ifcopenshell.api.pset.add_pset(ifc, product=element, name="Pset_Test")
prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2.5), Unit=length_m
)
pset.HasProperties = [prop]
obj = bpy.data.objects.new("Wall", None)
tool.Ifc.link(element, obj)
blender_props = obj.PsetProperties
subject.import_pset_from_existing(pset, blender_props, None)
metadata = blender_props.properties["Foo"].metadata
assert metadata.unit_symbol == "m"
assert metadata.float_value == 2.5 # raw stored value, not rescaled to the project's mm
# Simulate a user edit in the property editor.
metadata.float_value = 3.5
# Simulate what EditPset.execute() does: collect the raw value straight
# off the metadata and write it back, with no rescaling step.
properties = {"Foo": metadata.get_value()}
ifcopenshell.api.pset.edit_pset(ifc, pset=pset, properties=properties)
assert prop.NominalValue.wrappedValue == 3.5 # not rescaled to 3500mm
assert prop.Unit == length_m # override preserved
class TestImportingATemplatedQuantityRespectsItsOwnUnitOverride(NewFile):
def test_run(self):
# Regression test: import_pset_from_template's Q_ branch used to
# unconditionally re-template existing quantities, which shadowed
# their own Unit override with the project default -- edit mode
# showed "m" while the read-only panel correctly showed "mm".
# Project default is m, but this quantity is authored directly in mm.
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_m])
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
element = ifc.createIfcBeam()
qto = ifcopenshell.api.pset.add_qto(ifc, product=element, name="Qto_Test")
quantity = ifc.createIfcQuantityLength(Name="Foo", Unit=length_mm, LengthValue=2500.0)
qto.Quantities = [quantity]
pset_template = ifc.createIfcPropertySetTemplate(
Name="Qto_Test",
TemplateType="PSET_TYPEDRIVENOVERRIDE",
ApplicableEntity="IfcBeam",
HasPropertyTemplates=[ifc.createIfcSimplePropertyTemplate(Name="Foo", TemplateType="Q_LENGTH")],
)
obj = bpy.data.objects.new("Beam", None)
tool.Ifc.link(element, obj)
blender_props = obj.PsetProperties
# Mirrors core/pset.py's enable_pset_editing: template pass, then existing-data pass.
subject.import_pset_from_template(pset_template, qto, blender_props)
subject.import_pset_from_existing(qto, blender_props, pset_template)
assert len(blender_props.properties) == 1 # not duplicated by the template pass
metadata = blender_props.properties["Foo"].metadata
assert metadata.unit_symbol == "mm" # the quantity's own override, not the project default "m"
assert metadata.float_value == 2500.0 # raw stored value, not rescaled
class TestIsMeasurableSpecialType(NewFile):
def test_run(self):
for special_type in ("", "DATE", "DATETIME", "LOGICAL", "URI", "DURATION"):
assert subject.is_measurable_special_type(special_type) is False
assert subject.is_measurable_special_type("LENGTH") is True
assert subject.is_measurable_special_type("PRESSURE") is True
class TestGetCandidateUnitsForSpecialType(NewFile):
def test_returns_candidates_matching_the_special_type(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
ifcopenshell.api.unit.add_si_unit(ifc, unit_type="AREAUNIT")
assert set(subject.get_candidate_units_for_special_type("LENGTH", ifc)) == {length_mm, length_m}
def test_gating_returns_empty_for_non_measurable_special_types(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
assert subject.get_candidate_units_for_special_type("", ifc) == []
assert subject.get_candidate_units_for_special_type("URI", ifc) == []
class TestResolveEffectiveUnit(NewFile):
def test_own_override_takes_precedence_over_project_default(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
assert subject.resolve_effective_unit("LENGTH", length_m.id(), ifc) == length_m
def test_falls_back_to_project_default_when_unit_id_is_zero(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
assert subject.resolve_effective_unit("LENGTH", 0, ifc) == length_mm
class TestConvertAttributeUnit(NewFile):
def _new_metadata(self, ifc: ifcopenshell.file):
element = ifc.createIfcWall()
obj = bpy.data.objects.new("Wall", None)
tool.Ifc.link(element, obj)
props = obj.PsetProperties
new_prop = props.properties.add()
new_prop.name = "Foo"
return new_prop.metadata
def test_converts_value_between_two_explicit_units(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
metadata = self._new_metadata(ifc)
metadata.special_type = "LENGTH"
metadata.unit_id = length_mm.id()
metadata.float_value = 2500.0
subject.convert_attribute_unit(metadata, length_m.id(), ifc)
assert metadata.float_value == pytest.approx(2.5)
def test_converts_value_when_switching_to_and_from_the_project_default(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_m])
length_ft = ifcopenshell.api.unit.add_conversion_based_unit(ifc, name="foot")
metadata = self._new_metadata(ifc)
metadata.special_type = "LENGTH"
metadata.unit_id = length_ft.id()
metadata.float_value = 10.0 # 10 ft
subject.convert_attribute_unit(metadata, 0, ifc) # 0 = switch to project default (m)
assert metadata.float_value == pytest.approx(3.048)
def test_noop_when_old_and_new_resolve_to_the_same_unit(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_m])
metadata = self._new_metadata(ifc)
metadata.special_type = "LENGTH"
metadata.unit_id = 0 # already resolves to length_m (the project default)
metadata.float_value = 5.0
subject.convert_attribute_unit(metadata, length_m.id(), ifc)
assert metadata.float_value == 5.0
def test_noop_for_a_non_measurable_special_type(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
metadata = self._new_metadata(ifc)
metadata.special_type = ""
metadata.unit_id = 0
metadata.float_value = 5.0
subject.convert_attribute_unit(metadata, length_m.id(), ifc)
assert metadata.float_value == 5.0
def _build_wrapped_properties_from_ui(blender_props) -> dict:
"""Mirrors EditPset._execute()'s properties-building loop (operator.py)."""
properties = {}
for entry in blender_props.properties:
metadata = entry.metadata
value = metadata.get_value()
if value is not None and subject.is_measurable_special_type(metadata.special_type):
unit = tool.Ifc.get().by_id(metadata.unit_id) if metadata.unit_id else None
value = {"NominalValue": value, "Unit": unit}
properties[metadata.name] = value
return properties
class TestEditPsetWithUnitOverridePicker(NewFile):
def test_picking_a_different_unit_converts_the_displayed_value_and_writes_it_back(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
pset = ifcopenshell.api.pset.add_pset(ifc, product=element, name="Pset_Test")
prop = ifc.createIfcPropertySingleValue(Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2500.0))
pset.HasProperties = [prop]
obj = bpy.data.objects.new("Wall", None)
tool.Ifc.link(element, obj)
blender_props = obj.PsetProperties
subject.import_pset_from_existing(pset, blender_props, None)
metadata = blender_props.properties["Foo"].metadata
assert metadata.unit_id == 0
assert metadata.float_value == 2500.0
# Simulate the user picking "m" in the unit picker dropdown.
metadata.unit_id_enum = str(length_m.id())
assert metadata.float_value == pytest.approx(2.5) # converted live, not just relabeled
assert metadata.unit_id == length_m.id()
properties = _build_wrapped_properties_from_ui(blender_props)
ifcopenshell.api.pset.edit_pset(ifc, pset=pset, properties=properties)
assert prop.NominalValue.wrappedValue == pytest.approx(2.5)
assert prop.Unit == length_m
def test_picking_default_after_an_override_converts_back_and_clears_the_unit(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_mm = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_mm])
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
element = ifc.createIfcWall()
pset = ifcopenshell.api.pset.add_pset(ifc, product=element, name="Pset_Test")
prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcLengthMeasure(2.5), Unit=length_m
)
pset.HasProperties = [prop]
obj = bpy.data.objects.new("Wall", None)
tool.Ifc.link(element, obj)
blender_props = obj.PsetProperties
subject.import_pset_from_existing(pset, blender_props, None)
metadata = blender_props.properties["Foo"].metadata
assert metadata.unit_id == length_m.id()
assert metadata.float_value == 2.5
# Simulate picking "Default" (mm).
metadata.unit_id_enum = "0"
assert metadata.float_value == pytest.approx(2500.0)
assert metadata.unit_id == 0
properties = _build_wrapped_properties_from_ui(blender_props)
ifcopenshell.api.pset.edit_pset(ifc, pset=pset, properties=properties)
assert prop.Unit is None
assert prop.NominalValue.wrappedValue == pytest.approx(2500.0)
def test_editing_an_unrelated_sibling_property_does_not_disturb_this_ones_override(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject")
length_m = ifcopenshell.api.unit.add_si_unit(ifc, unit_type="LENGTHUNIT")
ifcopenshell.api.unit.assign_unit(ifc, units=[length_m])
length_ft = ifcopenshell.api.unit.add_conversion_based_unit(ifc, name="foot")
element = ifc.createIfcWall()
pset = ifcopenshell.api.pset.add_pset(ifc, product=element, name="Pset_Test")
overridden_prop = ifc.createIfcPropertySingleValue(
Name="Foo", NominalValue=ifc.createIfcLengthMeasure(10.0), Unit=length_ft
)
untouched_prop = ifc.createIfcPropertySingleValue(Name="Bar", NominalValue=ifc.createIfcLengthMeasure(3.0))
pset.HasProperties = [overridden_prop, untouched_prop]
obj = bpy.data.objects.new("Wall", None)
tool.Ifc.link(element, obj)
blender_props = obj.PsetProperties
subject.import_pset_from_existing(pset, blender_props, None)
# Edit only "Bar", never touching "Foo"'s unit dropdown.
blender_props.properties["Bar"].metadata.float_value = 4.0
properties = _build_wrapped_properties_from_ui(blender_props)
ifcopenshell.api.pset.edit_pset(ifc, pset=pset, properties=properties)
assert overridden_prop.Unit == length_ft # untouched override survives
assert overridden_prop.NominalValue.wrappedValue == 10.0
assert untouched_prop.NominalValue.wrappedValue == 4.0
class TestEditQtoRoundingLoopPreservesUnitWrappedValues(NewFile):
def test_run(self):
# Regression test for EditPset._execute()'s qto post-processing loop: it must reach
# into {"Unit": ..., "NominalValue": ...}-wrapped values to round them, rather than
# treating the whole dict as a bare float/int (which would zero it out).
properties = {
"Foo": {"NominalValue": 2.123456, "Unit": None},
"Bar": 3,
}
for key, value in properties.items():
if value is None:
continue
is_wrapped = isinstance(value, dict) and "Unit" in value
raw = value["NominalValue"] if is_wrapped else value
if raw is None:
continue
if isinstance(raw, float):
raw = round(raw, 4)
elif not isinstance(raw, int):
raw = 0
if is_wrapped:
value["NominalValue"] = raw
else:
properties[key] = raw
assert properties["Foo"]["NominalValue"] == 2.1235
assert properties["Foo"]["Unit"] is None
assert properties["Bar"] == 3
-36
View File
@@ -181,42 +181,6 @@ class TestGetCalculatedObjectQuantities(test.bim.bootstrap.NewFile):
assert quantities["NetVolume"] == 282.517
class TestGetTargetUnits(test.bim.bootstrap.NewFile):
def setup_file(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcProject", name="Test")
return ifc
def test_default_scene_state_returns_nothing(self):
self.setup_file()
assert subject.get_target_units() == {}
def test_setting_a_field_maps_it_to_its_measure_class(self):
ifc = self.setup_file()
metre = ifc.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
millimetre = ifc.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
ifcopenshell.api.unit.assign_unit(ifc, units=[metre])
props = tool.Qto.get_qto_props()
props.target_unit_length = str(millimetre.id())
assert subject.get_target_units() == {"IfcLengthMeasure": millimetre}
def test_untouched_fields_are_excluded(self):
ifc = self.setup_file()
metre = ifc.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
millimetre = ifc.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
gram = ifc.createIfcSIUnit(None, "MASSUNIT", None, "GRAM")
ifcopenshell.api.unit.assign_unit(ifc, units=[metre, gram])
props = tool.Qto.get_qto_props()
props.target_unit_length = str(millimetre.id())
props.target_unit_mass = "0" # explicitly left at "Default"
assert subject.get_target_units() == {"IfcLengthMeasure": millimetre}
class TestGetBaseQto(test.bim.bootstrap.NewFile):
def test_run(self):
ifc = ifcopenshell.file()
-24
View File
@@ -288,27 +288,3 @@ class TestGenerateSpace(NewFile):
)
)
assert np.allclose(TEST_VERTS, sorted([tuple(v.co) for v in mesh.vertices]))
def test_regenerate_space_preserves_z_location(self):
bpy.ops.bim.create_project()
ifc = tool.Ifc.get()
scene = bpy.context.scene
product = ifcopenshell.api.root.create_entity(ifc, ifc_class="IfcWall")
bpy.ops.mesh.primitive_cube_add(size=10, location=(0, 0, 4))
obj = bpy.data.objects["Cube"]
scene.collection.objects.link(obj)
tool.Ifc.link(product, obj)
scene.cursor.location = (0, 0, 0)
bpy.ops.bim.generate_space()
space = bpy.data.objects["IfcSpace/Space"]
space.location.z = 5
bpy.context.view_layer.update()
bpy.context.view_layer.objects.active = space
space.select_set(True)
obj.select_set(False)
bpy.ops.bim.generate_space()
assert np.isclose(space.location.z, 5), f"Expected z=5, got {space.location.z}"
+2 -17
View File
@@ -26,9 +26,7 @@ import webbrowser
from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict
import requests
from requests.adapters import HTTPAdapter
from typing_extensions import NotRequired
from urllib3.util import Retry
if TYPE_CHECKING:
import ifcopenshell
@@ -519,25 +517,12 @@ class Client:
self.auth_endpoint = "https://buildingsmartservices.b2clogin.com/tfp/buildingsmartservices.onmicrosoft.com/b2c_1_signupsignin/oauth2/v2.0/authorize"
self.token_endpoint = "https://buildingsmartservices.b2clogin.com/tfp/buildingsmartservices.onmicrosoft.com/b2c_1_signupsignin/oauth2/v2.0/token"
self.client_id = "4aba821f-d4ff-498b-a462-c2837dbbba70"
# The bSDD API is aggressively rate limited (HTTP 429). Retry transient
# failures with backoff instead of immediately raising, honouring the
# server's `Retry-After` header when present.
self.session = requests.Session()
retries = Retry(
total=5,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
respect_retry_after_header=True,
allowed_methods=["GET", "POST"],
)
self.session.mount("https://", HTTPAdapter(max_retries=retries))
self.session.mount("http://", HTTPAdapter(max_retries=retries))
def get(self, endpoint, params=None, is_auth_required=False):
headers = {"User-Agent": "IfcOpenShell.bSDD.py/0.8.0"}
if is_auth_required:
headers["Authorization"] = "Bearer " + self.get_access_token()
response = self.session.get(f"{self.baseurl}{endpoint}", timeout=10, headers=headers, params=params or None)
response = requests.get(f"{self.baseurl}{endpoint}", timeout=10, headers=headers, params=params or None)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
@@ -554,7 +539,7 @@ class Client:
old_baseurl = "https://bs-dd-api-prototype.azurewebsites.net/"
if is_auth_required:
headers["Authorization"] = "Bearer " + self.get_access_token()
return self.session.get(f"{old_baseurl}{endpoint}", timeout=10, headers=headers, params=params or None).json()
return requests.get(f"{old_baseurl}{endpoint}", timeout=10, headers=headers, params=params or None).json()
def post(self):
pass # TODO
+11 -11
View File
@@ -188,9 +188,9 @@
},
"IfcCovering": {
"Qto_CoveringBaseQuantities": {
"GrossArea": "gross_get_covering_area",
"NetArea": "net_get_covering_area",
"Width": "gross_get_covering_width"
"GrossArea": "gross_get_max_side_area",
"NetArea": "net_get_max_side_area",
"Width": "gross_get_min_xyz"
}
},
"IfcCurtainWall": {
@@ -529,16 +529,16 @@
"Qto_SpaceBaseQuantities": {
"FinishCeilingHeight": null,
"FinishFloorHeight": null,
"GrossCeilingArea": "gross_get_top_area",
"GrossFloorArea": "gross_get_footprint_area",
"GrossPerimeter": "gross_get_footprint_perimeter",
"GrossVolume": "gross_get_volume",
"GrossCeilingArea": null,
"GrossFloorArea": null,
"GrossPerimeter": null,
"GrossVolume": null,
"GrossWallArea": null,
"Height": "net_get_z",
"NetCeilingArea": "net_get_top_area",
"NetFloorArea": "net_get_footprint_area",
"Height": null,
"NetCeilingArea": null,
"NetFloorArea": null,
"NetPerimeter": null,
"NetVolume": "net_get_volume",
"NetVolume": null,
"NetWallArea": null
}
},
+24 -24
View File
@@ -204,9 +204,9 @@
},
"IfcCovering + IfcCoveringType": {
"Qto_CoveringBaseQuantities": {
"GrossArea": "gross_get_covering_area",
"NetArea": "net_get_covering_area",
"Width": "gross_get_covering_width"
"GrossArea": "gross_get_max_side_area",
"NetArea": "net_get_max_side_area",
"Width": "gross_get_min_xyz"
}
},
"IfcCurtainWall + IfcCurtainWallType": {
@@ -265,21 +265,21 @@
},
"IfcEarthworksCut": {
"Qto_EarthworksCutBaseQuantities": {
"Depth": "net_get_z",
"Length": "net_get_x",
"Depth": null,
"Length": null,
"LooseVolume": null,
"UndisturbedVolume": "net_get_volume",
"UndisturbedVolume": null,
"Weight": null,
"Width": "net_get_y"
"Width": null
}
},
"IfcEarthworksFill": {
"Qto_EarthworksFillBaseQuantities": {
"CompactedVolume": "net_get_volume",
"Depth": "net_get_z",
"Length": "net_get_x",
"CompactedVolume": null,
"Depth": null,
"Length": null,
"LooseVolume": null,
"Width": "net_get_y"
"Width": null
}
},
"IfcElectricAppliance + IfcElectricApplianceType": {
@@ -585,11 +585,11 @@
},
"IfcReinforcedSoil": {
"Qto_ReinforcedSoilBaseQuantities": {
"Area": "net_get_footprint_area",
"Depth": "net_get_z",
"Length": "net_get_x",
"Volume": "net_get_volume",
"Width": "net_get_y"
"Area": null,
"Depth": null,
"Length": null,
"Volume": null,
"Width": null
}
},
"IfcReinforcingElement + IfcReinforcingElementType": {
@@ -665,16 +665,16 @@
"Qto_SpaceBaseQuantities": {
"FinishCeilingHeight": null,
"FinishFloorHeight": null,
"GrossCeilingArea": "gross_get_top_area",
"GrossFloorArea": "gross_get_footprint_area",
"GrossPerimeter": "gross_get_footprint_perimeter",
"GrossVolume": "gross_get_volume",
"GrossCeilingArea": null,
"GrossFloorArea": null,
"GrossPerimeter": null,
"GrossVolume": null,
"GrossWallArea": null,
"Height": "net_get_z",
"NetCeilingArea": "net_get_top_area",
"NetFloorArea": "net_get_footprint_area",
"Height": null,
"NetCeilingArea": null,
"NetFloorArea": null,
"NetPerimeter": null,
"NetVolume": "net_get_volume",
"NetVolume": null,
"NetWallArea": null
}
},
@@ -585,11 +585,11 @@
},
"IfcReinforcedSoil": {
"Qto_ReinforcedSoilBaseQuantities": {
"Area": "get_net_footprint_area",
"Depth": "get_height",
"Length": "get_length",
"Volume": "get_net_volume",
"Width": "get_width"
"Area": null,
"Depth": null,
"Length": null,
"Volume": null,
"Width": null
}
},
"IfcReinforcingElement + IfcReinforcingElementType": {
+38 -99
View File
@@ -386,71 +386,12 @@ class Ifc5Dwriter:
"PredefinedType": cost_schedule.PredefinedType,
}
# Presentation formats (.ods / .xlsx) mirror exactly what the Bonsai cost
# panel shows for a cost item: ID (Identification), Name, Quantity,
# Value (RateSubtotal) and the calculated Total Cost. Everything else
# (internal bookkeeping columns, Description, Unit, per-category cost
# breakdowns) is bonsai/csv2ifc round-trip plumbing and stays out of the
# presentation formats. The .csv format keeps the full column set since
# csv2ifc reads those extra columns back in on import.
PRESENTATION_COLUMNS = ("Identification", "Name", "Quantity", "RateSubtotal", "TotalPrice")
# Header text as shown in presentation formats, matching the Bonsai cost
# panel's own column labels (see BIM_UL_cost_items_trait.draw_header).
PRESENTATION_LABELS = {
"Identification": "ID",
"RateSubtotal": "Value",
"TotalPrice": "Total Cost",
}
def multiply_cells(self, cell1, cell2):
return "={}*{}".format(cell1, cell2)
def sum_cells(self, list_of_cells):
return "=SUM({})".format(",".join(list_of_cells))
def get_visible_headers(self, schedule_id: int) -> list[str]:
"""Internal column keys shown in presentation formats, in panel order."""
headers = self.sheet_data[schedule_id]["headers"]
return [h for h in self.PRESENTATION_COLUMNS if h in headers]
def get_display_label(self, column: str) -> str:
"""Header text to write for a column in presentation formats."""
return self.PRESENTATION_LABELS.get(column, column)
def is_numeric_column(self, column: str) -> bool:
return column in ("Quantity", "RateSubtotal", "TotalPrice") or column.endswith(" Cost")
def get_total_price_formula(self, schedule_id: int, cost_item_index: int, first_data_row: int) -> Union[str, None]:
"""Spreadsheet formula for the TotalPrice cell of a cost item, or None for a plain value.
Sum items get ``=SUM(...)`` over the TotalPrice cells of their direct
children, leaf items with a quantity and a rate get ``=Quantity*RateSubtotal``.
Assumes one cost item per row, in ``cost_items`` order, starting at
``first_data_row`` (1-based).
"""
items = self.sheet_data[schedule_id]["cost_items"]
headers = self.get_visible_headers(schedule_id)
if "TotalPrice" not in headers:
return None
item = items[cost_item_index]
col = lambda name: self.column_indexes[headers.index(name)]
if item["ItemIsASum"]:
prefix = item["Hierarchy"] + "."
child_rows = [
first_data_row + i
for i, other in enumerate(items)
if other["Hierarchy"].startswith(prefix) and "." not in other["Hierarchy"][len(prefix) :]
]
if child_rows:
total_col = col("TotalPrice")
return self.sum_cells(["{}{}".format(total_col, r) for r in child_rows])
return None
if "Quantity" in headers and "RateSubtotal" in headers and item.get("Quantity") and item.get("RateSubtotal"):
row = first_data_row + cost_item_index
return self.multiply_cells("{}{}".format(col("Quantity"), row), "{}{}".format(col("RateSubtotal"), row))
return None
def get_cell_position(self, schedule_id, attribute):
def get_position_in_list(item, item_list):
try:
@@ -541,25 +482,32 @@ class Ifc5DOdsWriter(Ifc5Dwriter):
assert False, type
row.addElement(cell)
first_data_row = 6 # 3 metadata rows, 1 blank row, 1 header row.
def add_cost_item_rows(table, cost_data, cost_item_index):
def add_cost_item_rows(table, cost_data):
row = TableRow()
self.row_count += 1
style = self.colours.get(cost_data["Index"])
for column in self.get_visible_headers(cost_schedule.id()):
value = cost_data.get(column, "")
formula = None
if column == "TotalPrice":
formula = self.get_total_price_formula(cost_schedule.id(), cost_item_index, first_data_row)
if formula:
cell = TableCell(formula=formula, stylename=style)
elif self.is_numeric_column(column) and isinstance(value, (int, float)):
cell = TableCell(valuetype="float", value=value, stylename=style)
for i, column in enumerate(self.sheet_data[cost_schedule.id()]["headers"]):
if column == "Total Price" and cost_data["Quantity"] != 0 and cost_data["Rate Subtotal"]:
cell_quantity = self.get_cell_position(cost_schedule.id(), "Quantity")
cell_subtotal_rate = self.get_cell_position(cost_schedule.id(), "Rate Subtotal")
value = self.multiply_cells(cell_quantity, cell_subtotal_rate)
cell = TableCell(formula=value, stylename=self.colours.get(cost_data["Index"]))
else:
cell = TableCell(valuetype="string", stylename=style)
value = cost_data.get(column, "")
cell = TableCell(valuetype="string", stylename=self.colours.get(cost_data["Index"]))
cell.addElement(P(text=value))
# TODO:FIX QUANTITY AND COST TO SHOW AS NUMBERS AND CURRENCIES
# elif "Cost" in column or "Rate" in column:
# value = cost_data.get(column, "")
# cell = TableCell(valuetype="string", stylename=self.colours.get(cost_data["Index"]))
# cell.addElement(P(text=value))
# # cell.addElement(P(text=u"${}".format(value))) # The current displayed value
# print("Should add rate ", "${}".format(value))
# elif "Quantity" in column:
# value = cost_data.get(column, "")
# cell = TableCell(valuetype="float", stylename=self.colours.get(cost_data["Index"]))
# print("Should add quantity",value)
# cell.addElement(P(text=value))
row.addElement(cell)
table.addElement(row)
@@ -586,22 +534,20 @@ class Ifc5DOdsWriter(Ifc5Dwriter):
table.addElement(new)
header_row = TableRow()
for header in self.get_visible_headers(cost_schedule.id()):
add_cell(type="text", value=self.get_display_label(header), row=header_row, style="fed8b1")
for header in self.sheet_data[cost_schedule.id()]["headers"]:
add_cell(type="text", value=header, row=header_row, style="fed8b1")
table.addElement(header_row)
self.row_count = 5
for i, cost_item_data in enumerate(self.sheet_data[cost_schedule.id()]["cost_items"]):
add_cost_item_rows(table, cost_item_data, i)
for cost_item_data in self.sheet_data[cost_schedule.id()]["cost_items"]:
add_cost_item_rows(table, cost_item_data)
self.doc.spreadsheet.addElement(table)
class Ifc5DXlsxWriter(Ifc5Dwriter):
def write(self) -> None:
# openpyxl rather than xlsxwriter: it is what ifccsv already uses and
# what ships with Bonsai, so XLSX export works out of the box there.
import openpyxl
import xlsxwriter
super().write()
os.makedirs(self.output, exist_ok=True)
@@ -612,31 +558,24 @@ class Ifc5DXlsxWriter(Ifc5Dwriter):
else:
file_name += cost_schedule.Name or ""
self.file_path = os.path.join(self.output, "{}.xlsx".format(file_name))
self.workbook = openpyxl.Workbook()
self.workbook.remove(self.workbook.active)
self.workbook = xlsxwriter.Workbook(self.file_path)
for cost_schedule in self.cost_schedules:
self.write_table(cost_schedule)
self.workbook.save(self.file_path)
self.workbook.close()
def write_table(self, cost_schedule):
import re
worksheet = self.workbook.add_worksheet(self.sheet_data[cost_schedule.id()]["Name"])
headers = self.sheet_data[cost_schedule.id()]["headers"]
for i, header in enumerate(headers):
worksheet.write(0, i, header)
sheet_id = cost_schedule.id()
title = re.sub(r"[\[\]:*?/\\]", "_", self.sheet_data[sheet_id]["Name"])[:31]
worksheet = self.workbook.create_sheet(title)
headers = self.get_visible_headers(sheet_id)
worksheet.append([self.get_display_label(h) for h in headers])
first_data_row = 2 # Row 1 is the header.
for i, cost_item_data in enumerate(self.sheet_data[sheet_id]["cost_items"]):
row = []
row = 1
for cost_item_data in self.sheet_data[cost_schedule.id()]["cost_items"]:
col = 0
for header in headers:
formula = None
if header == "TotalPrice":
formula = self.get_total_price_formula(sheet_id, i, first_data_row)
# openpyxl treats strings starting with "=" as formulas.
row.append(formula if formula else cost_item_data.get(header, None))
worksheet.append(row)
worksheet.write(row, col, cost_item_data.get(header, ""))
col += 1
row += 1
class Ifc5DPdfWriter(Ifc5Dwriter):
+4 -153
View File
@@ -24,7 +24,7 @@ import os
import types
from collections import defaultdict
from collections.abc import Iterable
from typing import Any, Literal, NamedTuple, Optional, Union, get_args
from typing import Any, Literal, NamedTuple, Union, get_args
import ifcopenshell
import ifcopenshell.api.pset
@@ -127,61 +127,8 @@ def quantify(ifc_file: ifcopenshell.file, elements: set[ifcopenshell.entity_inst
return results
def get_quantity_measures(rules: dict) -> dict[str, dict[str, str]]:
"""Statically derive each quantity's measure class from the rule set that defines it,
reading it straight from the calculator's own Function table (the same source the
calculator itself used to compute the value) -- not guessed from the quantity name.
:param rules: A rule set as accepted by :func:`quantify`, e.g. from `ifc5d.qto.rules`.
:return: `qto_name -> quantity_name -> measure class` (e.g. "IfcLengthMeasure"), matching
the keys used by `SI2ProjectUnitConverter.project_units`.
"""
measures: dict[str, dict[str, str]] = {}
for calculator_name, queries in rules.get("calculators", {}).items():
calculator = calculators[calculator_name]
for _entity_or_query, qtos in queries.items():
for qto_name, quantities in qtos.items():
for quantity_name, formula in quantities.items():
if not formula:
continue
function = calculator.functions.get(formula)
if function is None:
continue
measures.setdefault(qto_name, {})[quantity_name] = function.measure
return measures
def _reconvert(ifc_file: ifcopenshell.file, value: float, to_unit: ifcopenshell.entity_instance) -> float:
"""Re-express `value` (as computed by `SI2ProjectUnitConverter` -- the project's default
unit for its dimension, or, if the project has none, raw SI, mirroring `convert()`'s own
fallback below) in `to_unit`, which shares `to_unit`'s dimension (`UnitType`).
"""
unit_type = getattr(to_unit, "UnitType", None)
from_unit = ifcopenshell.util.unit.get_project_unit(ifc_file, unit_type) if unit_type else None
from_scale = ifcopenshell.util.unit.get_unit_scale(from_unit) if from_unit else 1.0 # already SI
return value * from_scale / ifcopenshell.util.unit.get_unit_scale(to_unit)
def edit_qtos(
ifc_file: ifcopenshell.file,
results: ResultsDict,
target_units: Optional[dict[str, ifcopenshell.entity_instance]] = None,
rules: Optional[dict] = None,
) -> None:
"""Apply quantification results as quantity sets.
:param target_units: Optional map of measure class (e.g. "IfcLengthMeasure", matching
`SI2ProjectUnitConverter.project_units`'s keys) to a unit to express *newly created*
quantities of that measure in, instead of the project default. Ignored unless `rules`
is also given (needed to resolve each quantity's measure class -- see
`get_quantity_measures`). Has no effect on quantities that already exist -- those are
always re-expressed in whatever Unit they already carry (see below), regardless of
`target_units`.
:param rules: The rule set used to produce `results` (the same object passed to
`quantify()`), used only to resolve `target_units` via `get_quantity_measures()`.
"""
quantity_measures = get_quantity_measures(rules) if (target_units and rules) else {}
def edit_qtos(ifc_file: ifcopenshell.file, results: ResultsDict) -> None:
"""Apply quantification results as quantity sets."""
for element, qtos in results.items():
for name, quantities in qtos.items():
qto = ifcopenshell.util.element.get_pset(element, name, should_inherit=False)
@@ -189,36 +136,7 @@ def edit_qtos(
qto = ifc_file.by_id(qto["id"])
else:
qto = ifcopenshell.api.pset.add_qto(ifc_file, element, name)
existing_by_name = {q.Name: q for q in (qto.Quantities or ())}
wrapped_quantities: dict[str, Any] = {}
for quantity_name, value in quantities.items():
existing_unit = getattr(existing_by_name.get(quantity_name), "Unit", None)
if existing_unit is not None:
# A quantity that already carries its own Unit override must be
# re-expressed in that unit, not overwritten with a value computed in
# the project default while the stale Unit label stays put.
wrapped_quantities[quantity_name] = {
"NominalValue": _reconvert(ifc_file, value, existing_unit),
"Unit": existing_unit,
}
continue
measure = quantity_measures.get(name, {}).get(quantity_name)
target_unit = target_units.get(measure) if (target_units and measure) else None
if target_unit is not None:
# Brand new quantity, proactively expressed in the chosen target unit.
wrapped_quantities[quantity_name] = {
"NominalValue": _reconvert(ifc_file, value, target_unit),
"Unit": target_unit,
}
continue
wrapped_quantities[quantity_name] = value # unchanged bare-float path
ifcopenshell.api.pset.edit_qto(ifc_file, qto=qto, properties=wrapped_quantities)
ifcopenshell.api.pset.edit_qto(ifc_file, qto=qto, properties=quantities)
class SI2ProjectUnitConverter:
@@ -368,20 +286,8 @@ class IfcOpenShell(QtoCalculator):
"cross section height along the local Y axis. For slab-like footings (PAD_FOOTING, PILE_CAP) "
"and other predefined types it is the thickness along the local Z axis.",
),
"get_covering_width": Function(
"IfcLengthMeasure",
"Covering Width",
"The covering's thickness: the side area axis for AXIS2 (e.g. wall finishes), "
"otherwise the local Z depth (e.g. floor or ceiling finishes)",
),
# IfcAreaMeasure
"get_area": Function("IfcAreaMeasure", "Area", "The total surface area of the element"),
"get_covering_area": Function(
"IfcAreaMeasure",
"Covering Area",
"The covering's side area for AXIS2 (e.g. wall finishes), otherwise its footprint "
"area (e.g. floor or ceiling finishes)",
),
"get_footprint_area": Function(
"IfcAreaMeasure",
"Footprint Area",
@@ -443,8 +349,6 @@ class IfcOpenShell(QtoCalculator):
"get_opening_height",
"get_opening_depth",
"get_opening_area",
"get_covering_width",
"get_covering_area",
) + footing_functions
@classmethod
@@ -517,12 +421,6 @@ class IfcOpenShell(QtoCalculator):
if value is None:
continue
value = cls.unit_converter.convert(value, cls.raw_functions[formula].measure)
elif formula == "get_covering_width":
value = cls.get_covering_width(element, geometry)
value = cls.unit_converter.convert(value, "IfcLengthMeasure")
elif formula == "get_covering_area":
value = cls.get_covering_area(element, geometry)
value = cls.unit_converter.convert(value, "IfcAreaMeasure")
else:
value = formula_functions[formula](geometry)
assert isinstance(value, (float, int))
@@ -688,53 +586,6 @@ class IfcOpenShell(QtoCalculator):
mass += mass_per_length * item.Depth
return mass
@staticmethod
def get_covering_parametric_axis(element: ifcopenshell.entity_instance) -> Union[str, None]:
"""Get an IfcCovering's layer set direction, as authored by Bonsai's covering type.
:param element: IFC element entity.
:return: ``"AXIS2"`` for wall-like coverings, ``"AXIS3"`` for slab-like
coverings (e.g. floors or ceilings), or ``None`` if the covering's
type has no ``EPset_Parametric.LayerSetDirection``.
"""
relating_type = ifcopenshell.util.element.get_type(element)
if not relating_type:
return None
parametric = ifcopenshell.util.element.get_psets(relating_type).get("EPset_Parametric")
if not parametric:
return None
return parametric.get("LayerSetDirection")
@classmethod
def get_covering_area(cls, element: ifcopenshell.entity_instance, geometry: ifcopenshell.geom.ShapeType) -> float:
"""Get a covering's area, following its layer set direction.
AXIS2 (wall-like) coverings report the local Y-facing side area,
while AXIS3 coverings and coverings without a layer set direction
(e.g. freeform profiles) report the projected footprint area. This
mirrors how ``gross_get_side_area``/``net_get_side_area`` are
already used for ``Qto_WallBaseQuantities.*SideArea`` in this same
rule set.
"""
if cls.get_covering_parametric_axis(element) == "AXIS2":
return ifcopenshell.util.shape.get_side_area(geometry)
return ifcopenshell.util.shape.get_footprint_area(geometry)
@classmethod
def get_covering_width(cls, element: ifcopenshell.entity_instance, geometry: ifcopenshell.geom.ShapeType) -> float:
"""Get a covering's width (i.e. thickness), following its layer set direction.
AXIS2 (wall-like) coverings report the local Y depth, while AXIS3
coverings and coverings without a layer set direction report the
local Z depth. This mirrors how ``net_get_y`` is already used for
``Qto_WallBaseQuantities.Width`` in this same rule set, rather than
the ``min(X, Y)`` heuristic used by the Blender-side
:func:`bonsai.bim.module.qto.calculator.get_width`.
"""
if cls.get_covering_parametric_axis(element) == "AXIS2":
return ifcopenshell.util.shape.get_y(geometry)
return ifcopenshell.util.shape.get_z(geometry)
class Blender(QtoCalculator):
"""Calculates geometry based on currently loaded Blender objects."""
+4 -8
View File
@@ -20,14 +20,10 @@ dependencies = [
"typing_extensions",
]
[project.optional-dependencies]
advanced = [
"typst",
]
spreadsheet = [
"odfpy",
"openpyxl",
]
[project.optional-dependencies]
advanced = [
"typst",
]
[project.urls]
Homepage = "http://ifcopenshell.org"
-28
View File
@@ -120,34 +120,6 @@ class TestCsv2Ifc:
assert len(list(Path(temp_csv_dir).glob("*.ods"))) == 1
assert len(list(Path(temp_csv_dir).glob("*.xlsx"))) == 1
def test_xlsx_columns_match_cost_panel(self):
"""ODS/XLSX are presentation formats: they must show exactly what the
Bonsai cost panel shows (ID, Name, Quantity, Value, Total Cost), no
internal bookkeeping columns, no Description/Unit, no per-category
cost breakdown. See #6251."""
import openpyxl
ifc_file = self.setup_ifc_file()
csv_filepath = Path(__file__).parent.parent / "sample_cost_schedule_house_FR.csv"
ifc5d.csv2ifc.Csv2Ifc(str(csv_filepath), ifc_file).execute()
with tempfile.TemporaryDirectory("w") as temp_dir:
writer = ifc5d.ifc5Dspreadsheet.Ifc5DXlsxWriter(ifc_file, temp_dir)
writer.write()
workbook = openpyxl.load_workbook(next(Path(temp_dir).glob("*.xlsx")))
worksheet = workbook.active
headers = [cell.value for cell in next(worksheet.iter_rows())]
assert headers == ["ID", "Name", "Quantity", "Value", "Total Cost"]
# A leaf item (has quantity and value) gets Quantity * Value.
leaf_row = next(row for row in worksheet.iter_rows(min_row=2) if row[0].value == "DB.1.1")
assert leaf_row[4].value == "=C{}*D{}".format(leaf_row[0].row, leaf_row[0].row)
# A parent/sum item gets the sum of its direct children's Total Cost.
parent_row = next(row for row in worksheet.iter_rows(min_row=2) if row[0].value == "DB.1")
assert parent_row[4].value.startswith("=SUM(")
class TestSerialiseCostQuantities:
def test_quantity_name_with_special_characters_round_trips_as_json(self):
-139
View File
@@ -22,7 +22,6 @@ import ifcopenshell
import ifcopenshell.api.context
import ifcopenshell.api.root
import ifcopenshell.api.unit
import ifcopenshell.util.element
import pytest
import ifc5d.qto
@@ -91,141 +90,3 @@ class TestOpeningQuantities:
assert quantities["Depth"] == pytest.approx(0.3)
assert quantities["Area"] == pytest.approx(0.5)
assert quantities["Volume"] == pytest.approx(0.15)
class TestGetQuantityMeasures:
def test_resolves_measures_from_the_calculator_function_table(self):
measures = ifc5d.qto.get_quantity_measures(ifc5d.qto.rules["IFC4X3QtoBaseQuantities"])
assert measures["Qto_WallBaseQuantities"]["Length"] == "IfcLengthMeasure"
assert measures["Qto_WallBaseQuantities"]["NetWeight"] == "IfcMassMeasure"
class TestEditQtos:
def setup_method(self):
self.file = ifcopenshell.file(schema="IFC4X3")
ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcProject", name="Test")
self.wall = ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcWall")
def get_quantity(self, name: str) -> ifcopenshell.entity_instance:
pset = ifcopenshell.util.element.get_pset(self.wall, "Qto_WallBaseQuantities", should_inherit=False)
qto = self.file.by_id(pset["id"])
return next(q for q in qto.Quantities if q.Name == name)
def test_new_quantity_with_no_target_unit_is_a_bare_value(self):
metre = self.file.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
ifcopenshell.api.unit.assign_unit(self.file, units=[metre])
ifc5d.qto.edit_qtos(self.file, {self.wall: {"Qto_WallBaseQuantities": {"Length": 5.0}}})
quantity = self.get_quantity("Length")
assert quantity.LengthValue == pytest.approx(5.0)
assert quantity.Unit is None
def test_existing_manual_unit_override_is_reconverted_not_left_stale(self):
metre = self.file.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
ifcopenshell.api.unit.assign_unit(self.file, units=[metre])
millimetre = self.file.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
ifc5d.qto.edit_qtos(self.file, {self.wall: {"Qto_WallBaseQuantities": {"Length": 5.0}}})
quantity = self.get_quantity("Length")
# Simulate a user picking a millimetre override via the per-property picker.
quantity.Unit = millimetre
quantity.LengthValue = 5000.0
# Re-running take-off recomputes the value in the project default (metres) again --
# this must not leave the recomputed metres value mislabeled as millimetres.
ifc5d.qto.edit_qtos(self.file, {self.wall: {"Qto_WallBaseQuantities": {"Length": 6.0}}})
quantity = self.get_quantity("Length")
assert quantity.Unit == millimetre
assert quantity.LengthValue == pytest.approx(6000.0)
def test_target_unit_applies_only_to_brand_new_quantities(self):
metre = self.file.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
ifcopenshell.api.unit.assign_unit(self.file, units=[metre])
millimetre = self.file.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
rules = {"calculators": {"IfcOpenShell": {"IfcWall": {"Qto_WallBaseQuantities": {"Length": "net_get_x"}}}}}
ifc5d.qto.edit_qtos(
self.file,
{self.wall: {"Qto_WallBaseQuantities": {"Length": 5.0}}},
target_units={"IfcLengthMeasure": millimetre},
rules=rules,
)
quantity = self.get_quantity("Length")
assert quantity.Unit == millimetre
assert quantity.LengthValue == pytest.approx(5000.0)
def test_target_units_are_ignored_without_rules(self):
metre = self.file.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
ifcopenshell.api.unit.assign_unit(self.file, units=[metre])
millimetre = self.file.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
# `rules` is required to resolve a quantity's measure class -- without it, target_units
# has nothing to key off, so brand new quantities fall back to today's bare-float path.
ifc5d.qto.edit_qtos(
self.file,
{self.wall: {"Qto_WallBaseQuantities": {"Length": 5.0}}},
target_units={"IfcLengthMeasure": millimetre},
)
quantity = self.get_quantity("Length")
assert quantity.Unit is None
assert quantity.LengthValue == pytest.approx(5.0)
def test_reconvert_treats_a_missing_project_default_as_raw_si(self):
# No LENGTHUNIT is assigned to the project at all, so SI2ProjectUnitConverter.convert()
# would have left the calculated value as raw SI (metres) -- _reconvert must match.
millimetre = self.file.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
rules = {"calculators": {"IfcOpenShell": {"IfcWall": {"Qto_WallBaseQuantities": {"Length": "net_get_x"}}}}}
ifc5d.qto.edit_qtos(
self.file,
{self.wall: {"Qto_WallBaseQuantities": {"Length": 5.0}}},
target_units={"IfcLengthMeasure": millimetre},
rules=rules,
)
quantity = self.get_quantity("Length")
assert quantity.LengthValue == pytest.approx(5000.0)
class TestEditQtosIntegration:
"""A real quantify() + edit_qtos() round trip, guarding against edit_qto's own
class-inference disagreeing with get_quantity_measures()'s notion of measure.
"""
def test_target_unit_produces_the_correct_quantity_class(self):
file = ifcopenshell.file(schema="IFC4X3")
ifcopenshell.api.root.create_entity(file, ifc_class="IfcProject", name="Test")
metre = file.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
sqm = file.createIfcSIUnit(None, "AREAUNIT", None, "SQUARE_METRE")
cum = file.createIfcSIUnit(None, "VOLUMEUNIT", None, "CUBIC_METRE")
ifcopenshell.api.unit.assign_unit(file, units=[metre, sqm, cum])
model = ifcopenshell.api.context.add_context(file, context_type="Model")
body = ifcopenshell.api.context.add_context(
file, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model
)
wall = ifcopenshell.api.root.create_entity(file, ifc_class="IfcWall")
wall.ObjectPlacement = file.createIfcLocalPlacement(
None, file.createIfcAxis2Placement3D(file.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None)
)
profile = file.createIfcRectangleProfileDef("AREA", None, None, 5.0, 0.2)
position = file.createIfcAxis2Placement3D(file.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None)
solid = file.createIfcExtrudedAreaSolid(profile, position, file.createIfcDirection((0.0, 0.0, 1.0)), 3.0)
rep = file.createIfcShapeRepresentation(body, "Body", "SweptSolid", [solid])
wall.Representation = file.createIfcProductDefinitionShape(None, None, [rep])
millimetre = file.createIfcSIUnit(None, "LENGTHUNIT", "MILLI", "METRE")
rules = ifc5d.qto.rules["IFC4X3QtoBaseQuantities"]
results = ifc5d.qto.quantify(file, {wall}, rules)
ifc5d.qto.edit_qtos(file, results, target_units={"IfcLengthMeasure": millimetre}, rules=rules)
pset = ifcopenshell.util.element.get_pset(wall, "Qto_WallBaseQuantities", should_inherit=False)
qto = file.by_id(pset["id"])
length = next(q for q in qto.Quantities if q.Name == "Length")
assert length.is_a("IfcQuantityLength")
assert length.Unit == millimetre
assert length.LengthValue == pytest.approx(5000.0)
+2 -2
View File
@@ -36,7 +36,7 @@ import ifcopenshell.util.representation
import ifcopenshell.util.selector
import numpy as np
from deepdiff import DeepDiff
from orderly_set import StableSet
from orderly_set import OrderedSet
__version__ = version = "0.0.0"
@@ -257,7 +257,7 @@ class IfcDiff:
def json_dump_default(self, obj):
# result of DeepDiff may contain ordered sets
if isinstance(obj, (StableSet, set)):
if isinstance(obj, (OrderedSet, set)):
return list(obj)
return json.JSONEncoder.default(None, obj)
-28
View File
@@ -16,14 +16,9 @@
# 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 json
import os
import tempfile
import ifcopenshell
import ifcopenshell.api.context
import ifcopenshell.api.geometry
import ifcopenshell.api.pset
import ifcopenshell.api.root
import ifcopenshell.api.unit
import ifcopenshell.util.representation
@@ -99,29 +94,6 @@ class TestIfcDiff:
assert ifc_diff.deleted_elements == set()
assert ifc_diff.change_register == {wall.GlobalId: {"attributes_changed": True}}
def test_property_diff_exports_to_json(self):
# Regression test for #8905: comparing "property" relationships makes
# DeepDiff report a dictionary_item_added as a SetOrdered, which
# json.dump couldn't serialise, crashing export() with no results.
ifc_file = setup_project()
wall = ifcopenshell.api.root.create_entity(ifc_file, ifc_class="IfcWall", name="Foo")
new_file = ifc_file.from_string(ifc_file.to_string())
wall_new = new_file.by_id(wall.id())
pset = ifcopenshell.api.pset.add_pset(new_file, product=wall_new, name="Pset_WallCommon")
ifcopenshell.api.pset.edit_pset(new_file, pset=pset, properties={"FireRating": "2HR"})
ifc_diff = ifcdiff.IfcDiff(ifc_file, new_file, relationships=["property"])
ifc_diff.diff()
assert ifc_diff.change_register[wall.GlobalId]["properties_changed"]
with tempfile.TemporaryDirectory() as tmp_dir:
output = os.path.join(tmp_dir, "diff.json")
ifc_diff.export(output)
with open(output) as f:
results = json.load(f)
assert "Pset_WallCommon" in str(results["changed"][wall.GlobalId]["properties_changed"])
def test_changed_geometry(self):
ifc_file = setup_project()
wall = ifcopenshell.api.root.create_entity(ifc_file, ifc_class="IfcWall", name="Foo")
+2 -8
View File
@@ -94,15 +94,9 @@ def list_functions(module: str) -> list[dict]:
def function_docs(module: str, function: str) -> dict:
"""Show the full documentation for one ifcopenshell.api function.
"""Full documentation for a single API function.
Returns the summary and long description, every parameter with its type,
default and description, and the return type. Read this before calling
``run_api()`` so that parameter names and value types are correct.
:param module: API module name, for example ``'root'``.
:param function: Function name within the module, for example
``'create_entity'``.
Returns a dict with: module, function, description, params (with types/defaults/descriptions), return_type
"""
fn = _get_underlying_function(module, function)
if fn is None:
+3 -14
View File
@@ -14,21 +14,10 @@ def list_rules() -> list[dict[str, str]]:
def run_quantify(model: ifcopenshell.file, rule: str, selector: str | None = None) -> dict[str, Any]:
"""Compute base quantities for elements and write them into the model.
"""Run quantity take-off on the model using the named rule.
This is a write operation: it derives lengths, areas and volumes from
element geometry and adds or updates their ``IfcElementQuantity`` sets.
It does not report a schedule see ``ifcquery.schedule()`` for the
construction programme and ``ifcquery.cost()`` for cost schedules. An
unrecognised ``rule`` is reported as an error listing the rules that are
available.
:param model: The in-memory IFC model. Modified in-place.
:param rule: Quantity take-off rule set, for example
``'IFC4QtoBaseQuantities'`` or ``'IFC4X3QtoBaseQuantities'``.
:param selector: ifcopenshell selector restricting which elements are
measured, e.g. ``'IfcWall'``. Omit to measure every ``IfcElement`` and
``IfcSpace``.
Modifies the model in-place by adding/updating IfcElementQuantity psets.
Returns a summary dict with ok, rule, and elements_quantified.
"""
from ifc5d.qto import edit_qtos, quantify
from ifc5d.qto import rules as rule_sets

Some files were not shown because too many files have changed in this diff Show More