Compare commits

...

93 Commits

Author SHA1 Message Date
Dion Moult 8338cc72db New styles on sequencing gantt chart to show dependency arrows, critical path, task groups, and milestones 2021-06-02 17:31:55 +10:00
Dion Moult 67b636f5fb New API usecase to recalculate schedule times, including:
* Critical path
* Total float
* Early start
* Early finish
* Late start
* Late finish
2021-06-02 17:30:05 +10:00
Jesusbill 3a754c8ecc fix of the fix n add_pset 2021-06-01 16:33:47 +02:00
Dion Moult d64d7cf27a Dumb slabs now roundtrip the Blender solidify modifier 2021-05-31 17:43:42 +10:00
Dion Moult 6ff4c95ac7 Dumb slabs now auto update thickness based on layer thickness and type changes. 2021-05-31 15:27:22 +10:00
Dion Moult 0b6af5f848 Experimental usecase serialisation function, in preparation for client-server systems and version control. 2021-05-31 14:18:24 +10:00
Dion Moult 3ded4dff5f Parametric engine is now registered on load, so you don't need to manually activate it 2021-05-31 14:17:33 +10:00
Dion Moult 452631b997 Updating either a duration, start, or finish date for a task now auto-updates the other attribute 2021-05-31 12:42:02 +10:00
Dion Moult c041dd13ad Fix bug where users saw a scary error message when exporting with no IFC data 2021-05-31 09:19:04 +10:00
Jesusbill 994ccb94f4 fix bug in adding psets for materials 2021-05-30 13:32:59 +02:00
Dion Moult c7ba643ef7 Fix material unassignment greedy purging bug, and auto assign usages of typed layer / profile sets. 2021-05-30 21:03:50 +10:00
Dion Moult 0b6f3113a7 Changing types of a dumb wall now auto updates their wall thicknesses 2021-05-30 21:03:50 +10:00
s-leger 730efcae49 Bugfix Set changed size during iteration (#1506)
Fix for remove  RuntimeError: Set changed size during iteration
Add docstring
2021-05-29 22:03:00 +10:00
Dion Moult 62b297757e Dumb slabs now are marked as parametric and inherit thickness from the slab type 2021-05-29 14:59:02 +10:00
s-leger 0533a00631 Allow global listeners (#1500)
* Allow global listeners

Add "global" listeners when ifc_file is None, listeners are run whatever the file.
This way allow to register listeners before a file exists, and "global" listeners.

Add listener returns the ifc_key
Remove listeners allow optional filtering by usecase_path / ifc_key.usecase_path.

* Update __init__.py

Fix was only removing the first listener found.
2021-05-29 09:06:38 +10:00
Dion Moult 7fe2e93dea Fix #1491. Bug where drawings couldn't have a slash in their names. 2021-05-28 17:26:00 +10:00
Dion Moult acc9bd736f Fix #1048. Switching drawings now works when in local view. 2021-05-28 16:09:42 +10:00
Dion Moult 478612b6ae Fix #976. Bug where project data dir was not very customisable without running into issues. 2021-05-28 15:58:19 +10:00
Dion Moult a24d683613 Fix #1396. New walls are selected when created. 2021-05-28 14:50:36 +10:00
Dion Moult 0b5d7cdbf3 Fix #1455. Bump IfcOpenShell. 2021-05-28 14:36:48 +10:00
Dion Moult b8e20ec1a5 Reimplement raster underlays when generating drawings. See #1153. 2021-05-28 14:33:46 +10:00
Dion Moult 1cd243f13c Fix #1462. Standardise IfcOpenShell API to use Pythonic argument names. 2021-05-28 10:59:39 +10:00
s-leger 0a2adbb632 Implement remove pre / pos / all listeners (#1498)
Remove listeners, passing callback method.
Will not handle file pre_load cleanup / post_load setup here to prevent any blender's dependancy.
2021-05-28 10:07:56 +10:00
Dion Moult 8882c99455 Implement editing IFC header metadata. See #747. 2021-05-28 09:50:55 +10:00
Dion Moult 7890ded698 Fix #1429. MVDs now reflect the full DesignTransferView by default. 2021-05-28 09:49:57 +10:00
bosonprojets 7d2d9b2bcf purging of cost and task inverse relationships in ifcopenshell.api, and amendement to cost item values editing UX in BlenderBIM 2021-05-28 00:24:01 +01:00
s-leger 75ae501ff9 Evaluate coplanar vertex in faces (#1489)
The idea is to only triangulate non co-planar faces when required.

Timings for evaluation with matrix based algo.
IfcRoof/Roof found 3927 of 116178 polygons: 0.366638 sec
IfcWall/Wall.012 found 0 of 6 polygons: 0.000046 sec

So should be acceptable for common use cases
But with single precision in blender we may still be over occ precision with a 1e-6 epsilon.
2021-05-28 08:57:22 +10:00
luz paz 880fbe9533 Fix misc. source comment typos
Found via `codespell`
2021-05-27 09:40:06 +02:00
Dion Moult c2684f4fbf New split wall tool 2021-05-27 16:33:34 +10:00
Dion Moult afdc1e6679 New feature to export point lights (IfcLightSourcePositional) into IFC 2021-05-27 13:55:44 +10:00
Dion Moult 8935a17844 Really barebones UI to list space boundaries. 2021-05-27 13:54:18 +10:00
Dion Moult 93c59e81c6 Minor code review for BCF XML 3.0 implementation with TestPrab 2021-05-26 18:00:21 +10:00
Dion Moult d423274e62 New wall flip tool with hotkey. Wall aligner now allows flipped walls. 2021-05-26 17:20:34 +10:00
Dion Moult 7958dd837b New wall tool with hotkeys for rapid wall editing 2021-05-26 15:45:45 +10:00
Long e42a638220 implement DatePicker, visualisation time demo (#1488) 2021-05-26 14:59:20 +10:00
Dion Moult f5f314a58f Dumb walls now auto update thicknesses if the wall layer thickness changes 2021-05-26 11:36:06 +10:00
Dion Moult 96465bed8f Code review for BCFXML v3 Markup.xsd implementation with TestPrab 2021-05-25 18:44:11 +10:00
Prabhat Singh 41bdeea981 Added Script for V3 bcfxml (#1486)
* Added Module Loader

* Added Project and Version script for v3

* Cleaning the code

* optional fix

* Added markup.xsd in v3 bcfxml

* Completed Vision.xsd and Markup.xsd

Co-authored-by: Dion Moult <dion@thinkmoult.com>
2021-05-25 17:22:01 +10:00
Dion Moult 14e0910e59 Purge old dumb wall. Bye bye! 2021-05-25 13:39:55 +10:00
Dion Moult e0ba1c2183 Total layer set thickness is now calculated and shown in the UI 2021-05-25 13:25:05 +10:00
Dion Moult a13b71abf0 Layer set usages now inherit layer sets from the type. Walls now support material layer set usages. Also minor fixes, thanks s-leger! 2021-05-25 13:10:26 +10:00
Dion Moult 32fb359ee2 Copying objects in Blender now auto copy them in IFC too. See #1360. Thanks s-leger! 2021-05-25 11:07:56 +10:00
s-leger 61661fe6f3 implement missing create curve 2d method (#1484) 2021-05-24 23:14:26 +10:00
Dion Moult 92054b1999 Fix bug where objects created with the same name fail to sync geometry on export 2021-05-24 21:22:50 +10:00
Dion Moult 22d9bce591 Dumb walls now automatically generate wall axis upon update 2021-05-24 20:56:47 +10:00
Dion Moult bfe9213f67 Dumb walls now auto calculate length, width, height, and simple volume quantities when being updated 2021-05-24 19:28:47 +10:00
Dion Moult 1abf854f01 New formwork area calculation feature 2021-05-24 18:56:20 +10:00
Dion Moult 686b2a187d New wall align tool (align exterior, interior, or centerline) 2021-05-24 17:29:32 +10:00
Dion Moult 7c2764c98a General bugfix and stability improvements to WIP wall join tool 2021-05-24 17:03:55 +10:00
Dion Moult f73a3a8f79 Fix bug where you were unable to delete certain objects. See #1483. 2021-05-24 13:51:51 +10:00
s-leger b9723c08e4 Ensure polygons are always coplanar (#1482)
* Ensure polygons are always coplanar

fix #1481
May adopt a bmesh approach instead ?

* Ensure polygons are coplanar

The bmesh version is lot faster than modifier one
2021-05-24 08:19:39 +10:00
Thomas Krijnen 1e80e67df5 #1472 various considerations for handling of non-manifold elements with openings 2021-05-23 16:26:34 +02:00
Thomas Krijnen 3e8c10b775 first rough partial draft of alignment handling in python 2021-05-23 09:48:47 +02:00
Thomas Krijnen fd9f209a19 Additional validity check with log level debug 2021-05-23 09:36:31 +02:00
Dion Moult 6b72f7322b Creating walls from cursor now auto-align perpendicular to the wall the cursor is at 2021-05-23 11:48:20 +10:00
Dion Moult 9b0d9c1f91 Stroke-generated walls now auto-join likely butt joints and t-junctions 2021-05-23 11:09:56 +10:00
Dion Moult 26b699be7c You can now join walls in bulk 2021-05-23 10:56:34 +10:00
Dion Moult 294eba24c4 You can now unjoin walls 2021-05-23 09:32:39 +10:00
Dion Moult 09094c090c New sketch wall tool, and join wall tool (T-junction, butt joint, and mitre joints) 2021-05-22 15:39:28 +10:00
ahladik a0dad0802e Fix to IfcHierarchyHelper.cpp (#1476) 2021-05-21 13:26:40 +02:00
Dion Moult 97244d1919 Revisiting dumb walls - typed dumb walls now auto derive wall thickness from the type material 2021-05-20 12:53:40 +10:00
Dion Moult 1541cbbbb8 Fix bug where sometimes active object edits would not get synced correctly. 2021-05-19 21:05:03 +10:00
Dion Moult 82692bb88d Adding a new type instance (like furniture, walls) now snaps it to the bottom of the storey you're working on. Nice. 2021-05-19 17:59:13 +10:00
Dion Moult 77a97233c5 New authoring panel for adding instances and fix bug where new cube instances were missing a face 2021-05-19 16:24:34 +10:00
Dion Moult 4214a449a8 Only show search UI if an IFC model is loaded. 2021-05-19 14:46:02 +10:00
Dion Moult b650c045f5 Simple support for API listeners for parametric IFC authoring - editing any parameter can now trigger events from a "parametric engine" which synchronises other related geometry and attributes in the IFC dataset. Implement auto box generation as a first demo. 2021-05-19 14:45:47 +10:00
Prabhat Singh 851ab07192 Added Project and Version script for v3 bcfxml.py (#1473)
* Added Project and Version script for v3

* Removed Redundant part

* Optional Element Fixes
2021-05-19 08:40:28 +10:00
civilx64 20a36c39fc finish implementing clothoid transition 2021-05-18 15:46:55 +02:00
civilx64 38544e2ba9 develop calcs for biquadratic parabola and clothoid curves 2021-05-18 15:46:55 +02:00
civilx64 41a88bcd4d create implementation of IfcTransitionCurveSegment2D 2021-05-18 15:46:55 +02:00
Dion Moult 966850c54a Minor fix 2021-05-18 20:02:56 +10:00
Dion Moult 319fe13f9e Minor refactor 2021-05-18 17:48:44 +10:00
Dion Moult 0d5110b7af Fix bug where you were unable to remove a representation 2021-05-18 16:42:41 +10:00
Dion Moult de873461e1 Fix bug where IFC2X3 files did not correctly generate 2D representations 2021-05-18 16:41:55 +10:00
Dion Moult cbce3cbec0 Assigning a representation to a product type now syncs mapped representations of all of its typed products. 2021-05-18 16:41:30 +10:00
Dion Moult 0822d1d377 Fix crash when switching representations for a type products. 2021-05-18 16:29:19 +10:00
Dion Moult e6bf32b832 Fix potential instability when assigning types and synchronising Blender geometry 2021-05-18 14:36:12 +10:00
Dion Moult 30c31d694a Purge OCC dependency and old drawing system. See #1153. 2021-05-18 10:44:33 +10:00
s-leger 65c2f9a038 Add support for rel_void / rel_fill / rel_project relative placement when editing object placements(#1471)
* Add support for rel_void / rel_fill

* Fix relationships, and add support for projection elements

Co-authored-by: Dion Moult <dion@thinkmoult.com>
2021-05-18 09:46:15 +10:00
Dion Moult 2d42846fa3 Basic reimplementation of the 2D representation support without PythonOCC. See #1153. 2021-05-17 21:52:23 +10:00
Dion Moult d3bb895c9d No new functionality. Just throwing all drawing code in the drawing module. See #1153. 2021-05-17 15:15:25 +10:00
Dion Moult aeead1c011 Purge old swept solid system. No longer relevant in the land of native IFC. 2021-05-17 14:24:10 +10:00
Dion Moult ba742d5976 Fix #1465. Bump BCF to new namespace. 2021-05-17 14:02:29 +10:00
s-leger 27750e0caf fix is_native_swept_disk_solid logick (#1469)
* Update import_ifc.py

Ensure that at least a raw representation exists before checking for type.

* Update import_ifc.py
2021-05-17 10:02:41 +10:00
s-leger 5b02d3214d Unlink only from relevant collections (#1467)
Objects may be linked to non ifc related collections, so keep those links whatever.
2021-05-17 09:35:14 +10:00
Prabhat Singh 0f55a98b2f Added Module Loader (#1468) 2021-05-17 09:34:31 +10:00
Laurens Oostwegel 13209b6d03 Create mapping to IFC for all CityJSON object types & semantic surfaces 2021-05-16 18:55:00 +02:00
Laurens Oostwegel 411855495e support for CityJSON MultiSurface, CompositeSurface & interior faces for cityjson2ifc convert 2021-05-16 18:16:59 +02:00
Laurens Oostwegel 79ebbb82ef Minor fix in previous commit regarding writing of ifc file 2021-05-16 15:46:31 +02:00
LaurensJN 647a96a655 Update README.md of ifccityjson 2021-05-16 15:36:58 +02:00
Laurens Oostwegel 66d4665498 Instead of using a template ifc file, ifccityjson now uses ifcopenshell.api to create a new file for conversion 2021-05-16 15:32:35 +02:00
Dion Moult 537efdcb53 Continue refactor, and provide user options to regenerate vector base layer / annotation layer of drawings. See #1153. 2021-05-16 23:13:27 +10:00
Dion Moult f2352e9a17 Old annotation systems now creates IFC elements again. Also text and misc annotations now work again with new system. See #1153. 2021-05-16 18:26:48 +10:00
136 changed files with 7230 additions and 3497 deletions
+2 -2
View File
@@ -280,7 +280,7 @@ ENDIF()
# Use the found libTKernel as a template for all other OCC libraries
# TODO Extract this into macro/function
foreach(lib ${OPENCASCADE_LIBRARY_NAMES})
# Make sure we'll handle the Windows/MSVC debug postfix convetion too.
# Make sure we'll handle the Windows/MSVC debug postfix convention too.
string(REPLACE TKerneld "${lib}" lib_path "${libTKernel}")
string(REPLACE TKernel "${lib}" lib_path "${lib_path}")
list(APPEND OPENCASCADE_LIBRARIES "${lib_path}")
@@ -355,7 +355,7 @@ IF(COLLADA_SUPPORT AND BUILD_CONVERT)
# Use the found OpenCOLLADAFramework as a template for all other OpenCOLLADA libraries
foreach(lib ${OPENCOLLADA_LIBRARY_NAMES})
# Make sure we'll handle the Windows/MSVC debug postfix convetion too.
# Make sure we'll handle the Windows/MSVC debug postfix convention too.
string(REPLACE OpenCOLLADAFrameworkd "${lib}" lib_path "${OpenCOLLADAFramework}")
string(REPLACE OpenCOLLADAFramework "${lib}" lib_path "${lib_path}")
list(APPEND OPENCOLLADA_LIBRARIES "${lib_path}")
+4 -4
View File
@@ -11,16 +11,16 @@ Currently supports BCF version 2.1.
The `bcfxml` module lets you interact with the BCF-XML standard.
```
from bcf.bcfxml import BcfXml
from bcf import bcfxml
bcfxml = BcfXml()
# Load a project
project = bcfxml.get_project("/path/to/file.bcf")
bcfxml = bcfxml.load("/path/to/file.bcf")
# The project is also stored in the module
# project == bcfxml.project
project=bcfxml.get_project()
print(project.name)
# To edit a project, just modify the object directly
+39
View File
@@ -0,0 +1,39 @@
import os.path
import zipfile
import tempfile
from xml.dom import minidom
def load(filepath):
filepath = extract_project(filepath)
if os.path.isfile(os.path.join(filepath, "bcf.version")):
version_path = os.path.join(filepath, "bcf.version")
version_id = get_version(version_path)
if version_id == "2.1":
from bcf.v2.bcfxml import BcfXml
bcfxml = BcfXml()
bcfxml.filepath = filepath
return bcfxml
else:
from bcf.v3.bcfxml import BcfXml
bcfxml = BcfXml()
bcfxml.filepath = filepath
return bcfxml
def get_version(version_path):
xmlparse = minidom.parse(version_path)
version_el = xmlparse.getElementsByTagName("Version")[0]
version = version_el.getAttribute("VersionId")
return version
def extract_project(filepath):
if not filepath:
return
zip_file = zipfile.ZipFile(filepath)
filepath = tempfile.mkdtemp()
zip_file.extractall(filepath)
return filepath
+39 -33
View File
@@ -4,7 +4,7 @@ import shutil
import zipfile
import logging
import tempfile
import bcf.data
import bcf.v2.data
from datetime import datetime
from xml.dom import minidom
from xmlschema import XMLSchema
@@ -30,7 +30,7 @@ class BcfXml:
self.filepath = None
self.logger = logging.getLogger("bcfxml")
self.author = "john@doe.com"
self.project = bcf.data.Project()
self.project = bcf.v2.data.Project()
self.version = "2.1"
self.topics = {}
@@ -47,9 +47,6 @@ class BcfXml:
def get_project(self, filepath=None):
if not filepath:
return self.project
zip_file = zipfile.ZipFile(filepath)
self.filepath = tempfile.mkdtemp()
zip_file.extractall(self.filepath)
if os.path.isfile(os.path.join(self.filepath, "project.bcfp")):
data = self._read_xml("project.bcfp", "project.xsd")
self.project.extension_schema = data["ExtensionSchema"]
@@ -95,6 +92,12 @@ class BcfXml:
subdirs = dirnames
break
for subdir in subdirs:
try:
uuid.UUID(subdir)
except ValueError:
continue
if not os.path.exists(os.path.join(self.filepath, subdir, "markup.bcf")):
continue
self.topics[subdir] = self.get_topic(subdir)
return self.topics
@@ -102,9 +105,9 @@ class BcfXml:
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
if "Header" not in data:
return
header = bcf.data.Header()
header = bcf.v2.data.Header()
for item in data["Header"]["File"]:
header_file = bcf.data.HeaderFile()
header_file = bcf.v2.data.HeaderFile()
optional_keys = {
"filename": "Filename",
"date": "Date",
@@ -124,7 +127,7 @@ class BcfXml:
if guid in self.topics:
return self.topics[guid]
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
topic = bcf.data.Topic()
topic = bcf.v2.data.Topic()
self.topics[guid] = topic
mandatory_keys = {
@@ -155,7 +158,7 @@ class BcfXml:
setattr(topic, key, data["Topic"][value])
if "BimSnippet" in data["Topic"]:
bim_snippet = bcf.data.BimSnippet()
bim_snippet = bcf.v2.data.BimSnippet()
keys = {
"snippet_type": "@SnippetType",
"is_external": "@IsExternal",
@@ -169,7 +172,7 @@ class BcfXml:
if "DocumentReference" in data["Topic"]:
for item in data["Topic"]["DocumentReference"]:
document_reference = bcf.data.DocumentReference()
document_reference = bcf.v2.data.DocumentReference()
keys = {
"referenced_document": "ReferencedDocument",
"is_external": "@IsExternal",
@@ -183,14 +186,14 @@ class BcfXml:
if "RelatedTopic" in data["Topic"]:
for item in data["Topic"]["RelatedTopic"]:
related_topic = bcf.data.RelatedTopic()
related_topic = bcf.v2.data.RelatedTopic()
related_topic.guid = item["@Guid"]
topic.related_topics.append(related_topic)
return topic
def add_topic(self, topic=None):
if topic is None:
topic = bcf.data.Topic()
topic = bcf.v2.data.Topic()
if not topic.guid:
topic.guid = str(uuid.uuid4())
if not topic.title:
@@ -288,9 +291,12 @@ class BcfXml:
"isExternal": f.is_external,
},
)
self._create_element(file_el, "Filename", text=f.filename)
self._create_element(file_el, "Date", text=f.date)
self._create_element(file_el, "Reference", text=f.reference)
if f.filename:
self._create_element(file_el, "Filename", text=f.filename)
if f.date:
self._create_element(file_el, "Date", text=f.date)
if f.reference:
self._create_element(file_el, "Reference", text=f.reference)
def write_comments(self, comments, root):
for comment in comments.values():
@@ -310,7 +316,7 @@ class BcfXml:
def add_comment(self, topic, comment=None):
if comment is None:
comment = bcf.data.Comment()
comment = bcf.v2.data.Comment()
if not comment.guid:
comment.guid = str(uuid.uuid4())
if not comment.comment:
@@ -444,7 +450,7 @@ class BcfXml:
for bitmap in viewpoint.bitmaps:
bitmap_el = self._create_element(parent, "Bitmap")
text_map = {"Bitmap": bitmap.bitmap_type, "Reference": bitmap.reference}
text_map = {"Bitmap": bitmap.bitmap_format, "Reference": bitmap.reference}
for key, value in text_map.items():
self._create_element(bitmap_el, key, text=value)
@@ -471,7 +477,7 @@ class BcfXml:
def add_viewpoint(self, topic, viewpoint=None):
if not viewpoint:
viewpoint = bcf.data.Viewpoint()
viewpoint = bcf.v2.data.Viewpoint()
if not viewpoint.guid:
viewpoint.guid = str(uuid.uuid4())
if not viewpoint.viewpoint:
@@ -572,7 +578,7 @@ class BcfXml:
header_file.is_external = False
header_file.date = datetime.utcnow().isoformat()
if not topic.header:
topic.header = bcf.data.Header()
topic.header = bcf.v2.data.Header()
topic.header.files.append(header_file)
self.edit_topic(topic)
@@ -582,7 +588,7 @@ class BcfXml:
if "Comment" not in data:
return comments
for item in data["Comment"]:
comment = bcf.data.Comment()
comment = bcf.v2.data.Comment()
mandatory_keys = {"guid": "@Guid", "date": "Date", "author": "Author", "comment": "Comment"}
for key, value in mandatory_keys.items():
setattr(comment, key, item[value])
@@ -591,7 +597,7 @@ class BcfXml:
if value in item:
setattr(comment, key, item[value])
if "Viewpoint" in item:
viewpoint = bcf.data.Viewpoint()
viewpoint = bcf.v2.data.Viewpoint()
viewpoint.guid = item["Viewpoint"]["@Guid"]
comment.viewpoint = viewpoint
comments[comment.guid] = comment
@@ -610,7 +616,7 @@ class BcfXml:
return viewpoints
def get_viewpoint(self, data, topic_guid):
viewpoint = bcf.data.Viewpoint()
viewpoint = bcf.v2.data.Viewpoint()
viewpoint.guid = data["@Guid"]
optional_keys = {"viewpoint": "Viewpoint", "snapshot": "Snapshot", "index": "Index"}
for key, value in optional_keys.items():
@@ -628,10 +634,10 @@ class BcfXml:
def get_viewpoint_components(self, visinfo):
if "Components" not in visinfo:
return None
components = bcf.data.Components()
components = bcf.v2.data.Components()
data = visinfo["Components"]
if "ViewSetupHints" in data:
view_setup_hints = bcf.data.ViewSetupHints()
view_setup_hints = bcf.v2.data.ViewSetupHints()
optional_keys = {
"spaces_visible": "@SpacesVisible",
"space_boundaries_visible": "@SpaceBoundariesVisible",
@@ -645,7 +651,7 @@ class BcfXml:
for item in data["Selection"]["Component"]:
components.selection.append(self.get_component(item))
if "Visibility" in data:
component_visibility = bcf.data.ComponentVisibility()
component_visibility = bcf.v2.data.ComponentVisibility()
if "@DefaultVisibility" in data["Visibility"]:
component_visibility.default_visibility = data["Visibility"]["@DefaultVisibility"]
if "Exceptions" in data["Visibility"] and "Component" in data["Visibility"]["Exceptions"]:
@@ -654,7 +660,7 @@ class BcfXml:
components.visibility = component_visibility
if "Coloring" in data and "Color" in data["Coloring"]:
for item in data["Coloring"]["Color"]:
color = bcf.data.Color()
color = bcf.v2.data.Color()
color.color = item["@Color"]
for item2 in item["Component"]:
color.components.append(self.get_component(item2))
@@ -664,7 +670,7 @@ class BcfXml:
def get_viewpoint_orthogonal_camera(self, visinfo):
if "OrthogonalCamera" not in visinfo:
return None
camera = bcf.data.OrthogonalCamera()
camera = bcf.v2.data.OrthogonalCamera()
data = visinfo["OrthogonalCamera"]
self.set_vector(camera.camera_view_point, data["CameraViewPoint"])
self.set_vector(camera.camera_direction, data["CameraDirection"])
@@ -675,7 +681,7 @@ class BcfXml:
def get_viewpoint_perspective_camera(self, visinfo):
if "PerspectiveCamera" not in visinfo:
return None
camera = bcf.data.PerspectiveCamera()
camera = bcf.v2.data.PerspectiveCamera()
data = visinfo["PerspectiveCamera"]
self.set_vector(camera.camera_view_point, data["CameraViewPoint"])
self.set_vector(camera.camera_direction, data["CameraDirection"])
@@ -688,7 +694,7 @@ class BcfXml:
return []
lines = []
for item in visinfo["Lines"]["Line"]:
line = bcf.data.Line()
line = bcf.v2.data.Line()
self.set_vector(line.start_point, item["StartPoint"])
self.set_vector(line.end_point, item["EndPoint"])
lines.append(line)
@@ -699,7 +705,7 @@ class BcfXml:
return []
planes = []
for item in visinfo["ClippingPlanes"]["ClippingPlane"]:
plane = bcf.data.ClippingPlane()
plane = bcf.v2.data.ClippingPlane()
self.set_vector(plane.location, item["Location"])
self.set_vector(plane.direction, item["Direction"])
planes.append(plane)
@@ -710,9 +716,9 @@ class BcfXml:
return []
bitmaps = []
for item in visinfo["Bitmap"]:
bitmap = bcf.data.Bitmap()
bitmap = bcf.v2.data.Bitmap()
bitmap.reference = item["Reference"]
bitmap.bitmap_type = item["Bitmap"].upper()
bitmap.bitmap_format = item["Bitmap"].upper()
self.set_vector(bitmap.location, item["Location"])
self.set_vector(bitmap.normal, item["Normal"])
self.set_vector(bitmap.up, item["Up"])
@@ -726,7 +732,7 @@ class BcfXml:
to_obj.z = from_xml["Z"]
def get_component(self, data):
component = bcf.data.Component()
component = bcf.v2.data.Component()
optional_keys = {
"originating_system": "OriginatingSystem",
"authoring_tool_id": "AuthoringToolId",
+1 -1
View File
@@ -157,7 +157,7 @@ class Bitmap:
def __init__(self):
self.reference = "" # Only in BCF-XML
self.bitmap_data = None # Only in BCF-API
self.bitmap_type = "PNG" # Enum of png or jpg
self.bitmap_format = "PNG" # Enum of png or jpg
self.location = Point()
self.normal = Direction()
self.up = Direction()
View File
+827
View File
@@ -0,0 +1,827 @@
import os
import uuid
import shutil
import zipfile
import logging
import tempfile
import bcf.v3.data
from datetime import datetime
from xml.dom import minidom
from xmlschema import XMLSchema
from contextlib import contextmanager
from shutil import copyfile
cwd = os.path.dirname(os.path.realpath(__file__))
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
class BcfXml:
def __init__(self):
self.filepath = None
self.logger = logging.getLogger("bcfxml")
self.author = "john@doe.com"
self.project = bcf.v3.data.Project()
self.version = "3.0"
self.topics = {}
def new_project(self):
self.project.project_id = str(uuid.uuid4())
self.project.name = "New Project"
self.topics = {}
if self.filepath:
self.close_project()
self.filepath = tempfile.mkdtemp()
self.edit_project()
self.edit_version()
def get_project(self, filepath=None):
if os.path.isfile(os.path.join(self.filepath, "project.bcfp")):
data = self._read_xml("project.bcfp", "project.xsd")
self.project.project_id = data["Project"]["@ProjectId"]
self.project.name = data["Project"].get("Name")
return self.project
def edit_project(self):
self.document = minidom.Document()
root = self._create_element(self.document, "ProjectInfo")
project = self._create_element(root, "Project", {"ProjectId": self.project.project_id})
if self.project.name:
self._create_element(project, "Name", text=self.project.name)
with open(os.path.join(self.filepath, "project.bcfp"), "wb") as f:
f.write(self.document.toprettyxml(encoding="utf-8"))
def save_project(self, filepath):
with cd(self.filepath):
zip_file = zipfile.ZipFile(filepath, "w", zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk("./"):
for file in files:
zip_file.write(os.path.join(root, file))
zip_file.close()
def get_version(self):
data = self._read_xml("bcf.version", "version.xsd")
self.version = data["@VersionId"]
return self.version
def edit_version(self):
self.document = minidom.Document()
root = self._create_element(self.document, "Version", {"VersionId": self.version})
with open(os.path.join(self.filepath, "bcf.version"), "wb") as f:
f.write(self.document.toprettyxml(encoding="utf-8"))
def get_topics(self):
self.topics = {}
topics = []
subdirs = []
for (dirpath, dirnames, filenames) in os.walk(self.filepath):
subdirs = dirnames
break
for subdir in subdirs:
try:
uuid.UUID(subdir)
except ValueError:
continue
if not os.path.exists(os.path.join(self.filepath, subdir, "markup.bcf")):
continue
self.topics[subdir] = self.get_topic(subdir)
return self.topics
def get_header(self, guid):
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
if "Header" not in data:
return
header = bcf.v3.data.Header()
if data["Header"].get("Files"):
for item in data["Header"]["Files"].get("File", []):
header_file = bcf.v3.data.HeaderFile()
optional_keys = {
"filename": "Filename",
"date": "Date",
"reference": "Reference",
"ifc_project": "@IfcProject",
"ifc_spatial_structure_element": "@IfcSpatialStructureElement",
"is_external": "@IsExternal",
}
for key, value in optional_keys.items():
if value in item:
setattr(header_file, key, item[value])
header.files.append(header_file)
self.topics[guid].header = header
return header
def get_topic(self, guid):
if guid in self.topics:
return self.topics[guid]
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
topic = bcf.v3.data.Topic()
self.topics[guid] = topic
mandatory_keys = {
"guid": "@Guid",
"title": "Title",
"creation_date": "CreationDate",
"creation_author": "CreationAuthor",
"topic_status": "@TopicStatus",
"topic_type": "@TopicType",
}
for key, value in mandatory_keys.items():
setattr(topic, key, data["Topic"][value])
optional_keys = {
"priority": "Priority",
"index": "Index",
"modified_date": "ModifiedDate",
"modified_author": "ModifiedAuthor",
"due_date": "DueDate",
"assigned_to": "AssignedTo",
"stage": "Stage",
"description": "Description",
"server_assigned_id": "@ServerAssignedId",
}
for key, value in optional_keys.items():
if value in data["Topic"]:
setattr(topic, key, data["Topic"][value])
if "ReferenceLinks" in data["Topic"]:
topic.reference_links.extend(data["Topic"]["ReferenceLinks"].get("ReferenceLink", []))
if "Labels" in data["Topic"]:
topic.labels.extend(data["Topic"]["Labels"].get("Label", []))
if "BimSnippet" in data["Topic"]:
bim_snippet = bcf.v3.data.BimSnippet()
keys = {
"snippet_type": "@SnippetType",
"is_external": "@IsExternal",
"reference": "Reference",
"reference_schema": "ReferenceSchema",
}
for key, value in keys.items():
if value in data["Topic"]["BimSnippet"]:
setattr(bim_snippet, key, data["Topic"]["BimSnippet"][value])
topic.bim_snippet = bim_snippet
if data["Topic"].get("DocumentReferences"):
for item in data["Topic"]["DocumentReferences"].get("DocumentReference", []):
document_reference = bcf.v3.data.DocumentReference()
keys = {
"document_guid": "DocumentGuid",
"url": "Url",
"guid": "@Guid",
"description": "Description",
}
for key, value in keys.items():
if value in item:
setattr(document_reference, key, item[value])
topic.document_references.append(document_reference)
if data["Topic"].get("RelatedTopics"):
for item in data["Topic"]["RelatedTopics"].get("RelatedTopic", []):
related_topic = bcf.v3.data.RelatedTopic()
related_topic.guid = item["@Guid"]
topic.related_topics.append(related_topic)
return topic
def add_topic(self, topic=None):
if topic is None:
topic = bcf.v3.data.Topic()
if not topic.guid:
topic.guid = str(uuid.uuid4())
if not topic.title:
topic.title = "New Topic"
os.mkdir(os.path.join(self.filepath, topic.guid))
self.edit_topic(topic)
return topic
def edit_topic(self, topic):
if not topic.creation_date:
topic.creation_date = datetime.utcnow().isoformat()
topic.creation_author = self.author
else:
topic.modified_date = datetime.utcnow().isoformat()
topic.modified_author = self.author
self.document = minidom.Document()
root = self._create_element(self.document, "Markup")
if topic.header:
self.write_header(topic.header, root)
topic_el = self._create_element(
root,
"Topic",
{
"Guid": topic.guid,
"ServerAssignedId": topic.server_assigned_id,
"TopicType": topic.topic_type,
"TopicStatus": topic.topic_status,
},
)
if topic.reference_links:
reference_Links_el = self._create_element(topic_el, "ReferenceLinks")
for reference_link in topic.reference_links:
self._create_element(reference_Links_el, "ReferenceLink", text=reference_link)
text_map = {
"Title": topic.title,
"Priority": topic.priority,
"Index": topic.index,
}
for key, value in text_map.items():
if value:
self._create_element(topic_el, key, text=value)
if topic.labels:
label_el = self._create_element(topic_el, "Labels")
for label in topic.labels:
self._create_element(label_el, "Label", text=label)
text_map = {
"CreationDate": topic.creation_date,
"CreationAuthor": topic.creation_author,
"ModifiedDate": topic.modified_date,
"ModifiedAuthor": topic.modified_author,
"DueDate": topic.due_date,
"AssignedTo": topic.assigned_to,
"Stage": topic.stage,
"Description": topic.description,
}
for key, value in text_map.items():
if value:
self._create_element(topic_el, key, text=value)
if topic.bim_snippet:
bim_snippet = self._create_element(
topic_el,
"BimSnippet",
{
"SnippetType": topic.bim_snippet.snippet_type,
"IsExternal": topic.bim_snippet.is_external,
},
)
self._create_element(bim_snippet, "Reference", text=topic.bim_snippet.reference)
self._create_element(
bim_snippet,
"ReferenceSchema",
text=topic.bim_snippet.reference_schema,
)
if topic.document_references:
reference_el = self._create_element(topic_el, "DocumentReferences")
self.write_document_references(topic.document_references, reference_el)
if topic.related_topics:
related_topic_el = self._create_element(topic_el, "RelatedTopics")
for related_topic in topic.related_topics:
self._create_element(related_topic_el, "RelatedTopic", {"Guid": related_topic.guid})
if topic.comments:
comment_el = self._create_element(topic_el, "Comments")
self.write_comments(topic.comments, comment_el)
if topic.viewpoints:
viewpoint_el = self._create_element(topic_el, "Viewpoints")
self.write_viewpoints(topic.viewpoints, viewpoint_el, topic)
with open(os.path.join(self.filepath, topic.guid, "markup.bcf"), "wb") as f:
f.write(self.document.toprettyxml(encoding="utf-8"))
def write_document_references(self, references, root):
for reference in references:
document_reference_el = self._create_element(root, "DocumentReference", {"Guid": reference.guid})
if reference.document_guid:
self._create_element(document_reference_el, "DocumentGuid", text=reference.document_guid)
elif reference.url:
self._create_element(document_reference_el, "Url", text=reference.url)
if reference.description:
self._create_element(document_reference_el, "Description", text=reference.description)
def write_header(self, header, root):
if not header or not header.files:
return
header_el = self._create_element(root, "Header")
files_el = self._create_element(header_el, "Files")
for f in header.files:
file_el = self._create_element(
files_el,
"File",
{
"IfcProject": f.ifc_project,
"IfcSpatialStructureElement": f.ifc_spatial_structure_element,
"IsExternal": f.is_external,
},
)
if f.filename:
self._create_element(file_el, "Filename", text=f.filename)
if f.date:
self._create_element(file_el, "Date", text=f.date)
if f.reference:
self._create_element(file_el, "Reference", text=f.reference)
def write_comments(self, comments, root):
for comment in comments.values():
comment_el = self._create_element(root, "Comment", {"Guid": comment.guid})
text_map = {
"Date": comment.date,
"Author": comment.author,
"Comment": comment.comment,
"ModifiedDate": comment.modified_date,
"ModifiedAuthor": comment.modified_author,
}
for key, value in text_map.items():
if value:
self._create_element(comment_el, key, text=value)
if comment.viewpoint:
self._create_element(comment_el, "Viewpoint", {"Guid": comment.viewpoint.guid})
def add_comment(self, topic, comment=None):
if comment is None:
comment = bcf.v3.data.Comment()
if not comment.guid:
comment.guid = str(uuid.uuid4())
if not comment.comment:
comment.comment = "'Free software' is a matter of liberty, not price. To understand the concept, you should think of 'free' as in 'free speech,' not as in 'free beer'."
topic.comments[comment.guid] = comment
self.edit_comment(comment, topic)
def edit_comment(self, comment, topic):
if not comment.date:
comment.date = datetime.utcnow().isoformat()
comment.author = self.author
else:
comment.modified_date = datetime.utcnow().isoformat()
comment.modified_author = self.author
self.edit_topic(topic)
def delete_comment(self, guid, topic):
if guid in topic.comments:
del topic.comments[guid]
self.edit_topic(topic)
def delete_topic(self, guid):
if guid in self.topics:
del self.topics[guid]
shutil.rmtree(os.path.join(self.filepath, guid))
def write_viewpoints(self, viewpoints, root, topic):
for viewpoint in viewpoints.values():
viewpoint_el = self._create_element(root, "ViewPoint", {"Guid": viewpoint.guid})
text_map = {
"Viewpoint": viewpoint.viewpoint,
"Snapshot": viewpoint.snapshot,
"Index": viewpoint.index,
}
for key, value in text_map.items():
if value:
self._create_element(viewpoint_el, key, text=value)
self.write_viewpoint(viewpoint, topic)
def write_viewpoint(self, viewpoint, topic):
document = minidom.Document()
root = self._create_element(document, "VisualizationInfo", {"Guid": viewpoint.guid})
self.write_viewpoint_components(viewpoint, root)
self.write_viewpoint_orthogonal_camera(viewpoint, root)
self.write_viewpoint_perspective_camera(viewpoint, root)
self.write_viewpoint_lines(viewpoint, root)
self.write_viewpoint_clipping_planes(viewpoint, root)
self.write_viewpoint_bitmaps(viewpoint, root)
with open(os.path.join(self.filepath, topic.guid, viewpoint.viewpoint), "wb") as f:
f.write(document.toprettyxml(encoding="utf-8"))
def write_viewpoint_components(self, viewpoint, parent):
if not viewpoint.components:
return
components_el = self._create_element(parent, "Components")
if viewpoint.components.selection:
selection_el = self._create_element(components_el, "Selection")
for selection in viewpoint.components.selection:
self.write_component(selection, selection_el)
if viewpoint.components.visibility:
visibility = self._create_element(
components_el,
"Visibility",
{"DefaultVisibility": viewpoint.components.visibility.default_visibility},
)
if viewpoint.components.visibility.view_setup_hints:
view_setup_hints = self._create_element(
visibility,
"ViewSetupHints",
{
"SpacesVisible": viewpoint.components.visibility.view_setup_hints.spaces_visible,
"SpaceBoundariesVisible": viewpoint.components.visibility.view_setup_hints.space_boundaries_visible,
"OpeningsVisible": viewpoint.components.visibility.view_setup_hints.openings_visible,
},
)
if viewpoint.components.visibility.exceptions:
exceptions_el = self._create_element(visibility, "Exceptions")
for exception in viewpoint.components.visibility.exceptions:
self.write_component(exception, exceptions_el)
if viewpoint.components.coloring:
coloring_el = self._create_element(components_el, "Coloring")
for color in viewpoint.components.coloring:
color_el = self._create_element(coloring_el, "Color", {"Color": color.color})
component_el = self._create_element(color_el, "Components")
for component in color.components:
self.write_component(component, component_el)
def write_viewpoint_orthogonal_camera(self, viewpoint, parent):
if not viewpoint.orthogonal_camera:
return
camera = viewpoint.orthogonal_camera
camera_el = self._create_element(parent, "OrthogonalCamera")
camera_view_point = self._create_element(camera_el, "CameraViewPoint")
self.write_vector(camera_view_point, camera.camera_view_point)
camera_direction = self._create_element(camera_el, "CameraDirection")
self.write_vector(camera_direction, camera.camera_direction)
camera_up_vector = self._create_element(camera_el, "CameraUpVector")
self.write_vector(camera_up_vector, camera.camera_up_vector)
self._create_element(camera_el, "ViewToWorldScale", text=camera.view_to_world_scale)
self._create_element(camera_el, "AspectRatio", text=camera.aspect_ratio)
def write_viewpoint_perspective_camera(self, viewpoint, parent):
if not viewpoint.perspective_camera:
return
camera = viewpoint.perspective_camera
camera_el = self._create_element(parent, "PerspectiveCamera")
camera_view_point = self._create_element(camera_el, "CameraViewPoint")
self.write_vector(camera_view_point, camera.camera_view_point)
camera_direction = self._create_element(camera_el, "CameraDirection")
self.write_vector(camera_direction, camera.camera_direction)
camera_up_vector = self._create_element(camera_el, "CameraUpVector")
self.write_vector(camera_up_vector, camera.camera_up_vector)
self._create_element(camera_el, "FieldOfView", text=camera.field_of_view)
self._create_element(camera_el, "AspectRatio", text=camera.aspect_ratio)
def write_viewpoint_lines(self, viewpoint, parent):
if not viewpoint.lines:
return
lines_el = self._create_element(parent, "Lines")
for line in viewpoint.lines:
line_el = self._create_element(lines_el, "Line")
start_point_el = self._create_element(line_el, "StartPoint")
self.write_vector(start_point_el, line.start_point)
end_point_el = self._create_element(line_el, "EndPoint")
self.write_vector(end_point_el, line.end_point)
def write_viewpoint_clipping_planes(self, viewpoint, parent):
if not viewpoint.clipping_planes:
return
planes_el = self._create_element(parent, "ClippingPlanes")
for plane in viewpoint.clipping_planes:
plane_el = self._create_element(planes_el, "ClippingPlane")
location_el = self._create_element(plane_el, "Location")
self.write_vector(location_el, plane.location)
direction_el = self._create_element(plane_el, "Direction")
self.write_vector(direction_el, plane.direction)
def write_viewpoint_bitmaps(self, viewpoint, parent):
if not viewpoint.bitmaps:
return
bitmaps_el = self._create_element(parent, "Bitmaps")
for bitmap in viewpoint.bitmaps:
bitmap_el = self._create_element(bitmaps_el, "Bitmap")
text_map = {"Format": bitmap.bitmap_format, "Reference": bitmap.reference}
for key, value in text_map.items():
self._create_element(bitmap_el, key, text=value)
location_el = self._create_element(bitmap_el, "Location")
self.write_vector(location_el, bitmap.location)
normal_el = self._create_element(bitmap_el, "Normal")
self.write_vector(normal_el, bitmap.normal)
up_el = self._create_element(bitmap_el, "Up")
self.write_vector(up_el, bitmap.up)
self._create_element(bitmap_el, "Height", text=bitmap.height)
def write_vector(self, parent, from_obj):
self._create_element(parent, "X", text=from_obj.x)
self._create_element(parent, "Y", text=from_obj.y)
self._create_element(parent, "Z", text=from_obj.z)
def write_component(self, data, parent):
component_el = self._create_element(parent, "Component", {"IfcGuid": data.ifc_guid})
text_map = {
"OriginatingSystem": data.originating_system,
"AuthoringToolId": data.authoring_tool_id,
}
for key, value in text_map.items():
if value:
self._create_element(component_el, key, text=value)
def add_viewpoint(self, topic, viewpoint=None):
if not viewpoint:
viewpoint = bcf.v3.data.Viewpoint()
if not viewpoint.guid:
viewpoint.guid = str(uuid.uuid4())
if not viewpoint.viewpoint:
viewpoint.viewpoint = f"{viewpoint.guid}.bcfv"
if viewpoint.snapshot:
topic_filepath = os.path.join(self.filepath, topic.guid)
filepath = os.path.join(topic_filepath, viewpoint.snapshot)
if not os.path.exists(filepath):
filename = viewpoint.guid + os.path.splitext(viewpoint.snapshot)[-1]
copyfile(viewpoint.snapshot, os.path.join(topic_filepath, filename))
viewpoint.snapshot = filename
topic.viewpoints[viewpoint.guid] = viewpoint
self.edit_topic(topic)
def delete_viewpoint(self, guid, topic):
if guid not in topic.viewpoints:
return
viewpoint = topic.viewpoints[guid]
if viewpoint.snapshot:
filepath = os.path.join(self.filepath, topic.guid, viewpoint.snapshot)
if os.path.exists(filepath):
os.remove(filepath)
if viewpoint.viewpoint:
filepath = os.path.join(self.filepath, topic.guid, viewpoint.viewpoint)
if os.path.exists(filepath):
os.remove(filepath)
for bitmap in viewpoint.bitmaps:
if not bitmap.reference:
continue
filepath = os.path.join(self.filepath, topic.guid, bitmap.reference)
if os.path.exists(filepath):
os.remove(filepath)
del topic.viewpoints[guid]
self.edit_topic(topic)
def delete_file(self, topic, index):
if not topic.header:
return
f = topic.header.files.pop(index)
filepath = os.path.join(self.filepath, topic.guid, f.reference)
if not f.is_external and os.path.exists(filepath):
os.remove(filepath)
self.edit_topic(topic)
def delete_bim_snippet(self, topic):
if not topic.bim_snippet:
return
if topic.bim_snippet.reference and not topic.bim_snippet.is_external:
filepath = os.path.join(self.filepath, topic.guid, topic.bim_snippet.reference)
if os.path.exists(filepath):
os.remove(filepath)
topic.bim_snippet = None
self.edit_topic(topic)
def delete_document_reference(self, topic, index):
document_reference = topic.document_references[index]
if document_reference.referenced_document and not document_reference.is_external:
filepath = os.path.join(self.filepath, topic.guid, document_reference.referenced_document)
if os.path.exists(filepath):
os.remove(filepath)
del topic.document_references[index]
self.edit_topic(topic)
def add_document_reference(self, topic, document_reference):
if os.path.exists(document_reference.referenced_document):
topic_filepath = os.path.join(self.filepath, topic.guid)
filename = os.path.basename(document_reference.referenced_document)
copyfile(
document_reference.referenced_document,
os.path.join(topic_filepath, filename),
)
document_reference.referenced_document = filename
document_reference.is_external = False
else:
document_reference.is_external = True
if not document_reference.guid:
document_reference.guid = str(uuid.uuid4())
topic.document_references.append(document_reference)
self.edit_topic(topic)
def add_bim_snippet(self, topic, bim_snippet):
if topic.bim_snippet:
self.delete_bim_snippet(topic)
if os.path.exists(bim_snippet.reference):
topic_filepath = os.path.join(self.filepath, topic.guid)
filename = os.path.basename(bim_snippet.reference)
copyfile(bim_snippet.reference, os.path.join(topic_filepath, filename))
bim_snippet.reference = filename
bim_snippet.is_external = False
else:
bim_snippet.is_external = True
topic.bim_snippet = bim_snippet
self.edit_topic(topic)
def add_file(self, topic, header_file):
if os.path.exists(header_file.reference):
topic_filepath = os.path.join(self.filepath, topic.guid)
header_file.filename = os.path.basename(header_file.reference)
copyfile(
header_file.reference,
os.path.join(topic_filepath, header_file.filename),
)
header_file.reference = header_file.filename
header_file.is_external = False
header_file.date = datetime.utcnow().isoformat()
if not topic.header:
topic.header = bcf.v3.data.Header()
topic.header.files.append(header_file)
self.edit_topic(topic)
def get_comments(self, guid):
comments = {}
if "Comments" not in data["Topics"]:
return comments
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
for item in data["Topic"]["Comments"].get("Comment", []):
comment = bcf.v3.data.Comment()
mandatory_keys = {
"guid": "@Guid",
"date": "Date",
"author": "Author",
}
for key, value in mandatory_keys.items():
setattr(comment, key, item[value])
optional_keys = {
"comment": "Comment",
"modified_date": "ModifiedDate",
"modified_author": "ModifiedAuthor",
}
for key, value in optional_keys.items():
if value in item:
setattr(comment, key, item[value])
if "Viewpoint" in item:
viewpoint = bcf.v3.data.Viewpoint()
viewpoint.guid = item["Viewpoint"]["@Guid"]
comment.viewpoint = viewpoint
comments[comment.guid] = comment
self.topics[guid].comments = comments
return comments
def get_viewpoints(self, guid):
viewpoints = {}
if "Viewpoints" not in data["Topic"]:
return viewpoints
data = self._read_xml(os.path.join(guid, "markup.bcf"), "markup.xsd")
for item in data["Topic"]["Viewpoints"]:
viewpoint = self.get_viewpoint(item, guid)
viewpoints[viewpoint.guid] = viewpoint
self.topics[guid].viewpoints = viewpoints
return viewpoints
def get_viewpoint(self, data, topic_guid):
viewpoint = bcf.v3.data.Viewpoint()
viewpoint.guid = data["@Guid"]
optional_keys = {
"viewpoint": "Viewpoint",
"snapshot": "Snapshot",
"index": "Index",
}
for key, value in optional_keys.items():
if value in data:
setattr(viewpoint, key, data[value])
visinfo = self._read_xml(os.path.join(topic_guid, viewpoint.viewpoint), "visinfo.xsd")
viewpoint.components = self.get_viewpoint_components(visinfo)
viewpoint.orthogonal_camera = self.get_viewpoint_orthogonal_camera(visinfo)
viewpoint.perspective_camera = self.get_viewpoint_perspective_camera(visinfo)
viewpoint.lines = self.get_viewpoint_lines(visinfo)
viewpoint.clipping_planes = self.get_viewpoint_clipping_planes(visinfo)
viewpoint.bitmaps = self.get_viewpoint_bitmaps(visinfo)
return viewpoint
def get_viewpoint_components(self, visinfo):
if "Components" not in visinfo:
return None
components = bcf.v3.data.Components()
data = visinfo["Components"]
if "Selection" in data and "Component" in data["Selection"]:
for item in data["Selection"].get("Component", []):
components.selection.append(self.get_component(item))
if "Visibility" in data:
component_visibility = bcf.v3.data.ComponentVisibility()
if "@DefaultVisibility" in data["Visibility"]:
component_visibility.default_visibility = data["Visibility"]["@DefaultVisibility"]
if "Exceptions" in data["Visibility"] and "Component" in data["Visibility"]["Exceptions"]:
for item in data["Visibility"]["Exceptions"]["Component"]:
component_visibility.exceptions.append(self.get_component(item))
if "ViewSetupHints" in data["Visibility"]:
view_setup_hints = bcf.v3.data.ViewSetupHints()
optional_keys = {
"spaces_visible": "@SpacesVisible",
"space_boundaries_visible": "@SpaceBoundariesVisible",
"openings_visible": "@OpeningsVisible",
}
for key, value in optional_keys.items():
if value in data["Visibility"]["ViewSetupHints"]:
setattr(view_setup_hints, key, data["Visibility"]["ViewSetupHints"][value])
component_visibility.view_setup_hints = view_setup_hints
components.visibility = component_visibility
if "Coloring" in data and "Color" in data["Coloring"]:
for item in data["Coloring"]["Color"]:
color = bcf.v3.data.Color()
color.color = item["@Color"]
for item2 in item["Components"]["Component"]:
color.components.append(self.get_component(item2))
components.coloring.append(color)
return components
def get_viewpoint_orthogonal_camera(self, visinfo):
if "OrthogonalCamera" not in visinfo:
return None
camera = bcf.v3.data.OrthogonalCamera()
data = visinfo["OrthogonalCamera"]
self.set_vector(camera.camera_view_point, data["CameraViewPoint"])
self.set_vector(camera.camera_direction, data["CameraDirection"])
self.set_vector(camera.camera_up_vector, data["CameraUpVector"])
camera.view_to_world_scale = data["ViewToWorldScale"]
camera.aspect_ratio = data["AspectRatio"]
return camera
def get_viewpoint_perspective_camera(self, visinfo):
if "PerspectiveCamera" not in visinfo:
return None
camera = bcf.v3.data.PerspectiveCamera()
data = visinfo["PerspectiveCamera"]
self.set_vector(camera.camera_view_point, data["CameraViewPoint"])
self.set_vector(camera.camera_direction, data["CameraDirection"])
self.set_vector(camera.camera_up_vector, data["CameraUpVector"])
camera.field_of_view = data["FieldOfView"]
camera.aspect_ratio = data["AspectRatio"]
return camera
def get_viewpoint_lines(self, visinfo):
if "Lines" not in visinfo:
return []
lines = []
for item in visinfo["Lines"].get("Line", []):
line = bcf.v3.data.Line()
self.set_vector(line.start_point, item["StartPoint"])
self.set_vector(line.end_point, item["EndPoint"])
lines.append(line)
return lines
def get_viewpoint_clipping_planes(self, visinfo):
if "ClippingPlanes" not in visinfo:
return []
planes = []
for item in visinfo["ClippingPlanes"]["ClippingPlane"]:
plane = bcf.v3.data.ClippingPlane()
self.set_vector(plane.location, item["Location"])
self.set_vector(plane.direction, item["Direction"])
planes.append(plane)
return planes
def get_viewpoint_bitmaps(self, visinfo):
if "Bitmaps" not in visinfo:
return []
bitmaps = []
for item in visinfo["Bitmaps"].get("Bitmap"):
bitmap = bcf.v3.data.Bitmap()
bitmap.reference = item["Reference"]
bitmap.bitmap_format = item["Format"].upper()
self.set_vector(bitmap.location, item["Location"])
self.set_vector(bitmap.normal, item["Normal"])
self.set_vector(bitmap.up, item["Up"])
bitmap.height = item["Height"]
bitmaps.append(bitmap)
return bitmaps
def set_vector(self, to_obj, from_xml):
to_obj.x = from_xml["X"]
to_obj.y = from_xml["Y"]
to_obj.z = from_xml["Z"]
def get_component(self, data):
component = bcf.v3.data.Component()
optional_keys = {
"originating_system": "OriginatingSystem",
"authoring_tool_id": "AuthoringToolId",
"ifc_guid": "@IfcGuid",
}
for key, value in optional_keys.items():
if value in data:
setattr(component, key, data[value])
return component
def close_project(self):
shutil.rmtree(self.filepath)
def _read_xml(self, filename, xsd):
schema = XMLSchema(os.path.join(cwd, "xsd", xsd))
filepath = os.path.join(self.filepath, filename)
(data, errors) = schema.to_dict(filepath, validation="lax")
for error in errors:
self.logger.error(error)
return data
def _create_element(self, parent, name, attributes={}, text=None):
element = self.document.createElement(name)
for key, value in attributes.items():
if isinstance(value, bool):
element.setAttribute(key, str(value).lower())
elif value:
element.setAttribute(key, value)
if text is not None:
text = self.document.createTextNode(str(text))
element.appendChild(text)
parent.appendChild(element)
return element
def __del__(self):
self.close_project()
+181
View File
@@ -0,0 +1,181 @@
class Project:
def __init__(self):
self.project_id = ""
self.name = ""
class BimSnippet:
def __init__(self):
self.snippet_type = None
self.is_external = False
self.reference = None
self.reference_schema = None
class DocumentReference:
def __init__(self):
self.description = None
self.document_guid = None
self.url = None
self.guid = None
class RelatedTopic:
def __init__(self):
self.guid = None
class HeaderFile:
def __init__(self):
self.file_name = ""
self.date = None
self.reference = ""
self.ifc_project = None
self.ifc_spatial_structure_element = None
self.is_external = True
class Header:
def __init__(self):
self.files = []
class Topic:
def __init__(self):
self.reference_links = []
self.title = ""
self.priority = None
self.index = None # Deprecated, stored, but ignored
self.labels = []
self.creation_date = None
self.creation_author = None
self.modified_date = None
self.modified_author = None
self.due_date = None
self.assigned_to = None
self.stage = None
self.description = None
self.bim_snippet = None
self.document_references = []
self.related_topics = []
self.topic_status = None
self.topic_type = None
self.guid = None
self.header = None
self.comments = {}
self.viewpoints = {}
self.server_assigned_id = ""
class Comment:
def __init__(self):
self.guid = None
self.date = None
self.author = ""
self.comment = ""
self.viewpoint = None
self.modified_date = None
self.modified_author = ""
class ViewSetupHints:
def __init__(self):
self.spaces_visible = False
self.space_boundaries_visible = False
self.openings_visible = False
class Component:
def __init__(self):
self.originating_system = None
self.authoring_tool_id = None
self.ifc_guid = None
class ComponentVisibility:
def __init__(self):
self.exceptions = []
self.default_visibility = False
self.view_setup_hints = None
class Color:
def __init__(self):
self.color = None
self.components = []
class Components:
def __init__(self):
self.selection = []
self.visibility = None
self.coloring = []
class Point:
def __init__(self):
self.x = 0
self.y = 0
self.z = 0
class Direction(Point):
pass
class OrthogonalCamera:
def __init__(self):
self.camera_view_point = Point()
self.camera_direction = Direction()
self.camera_up_vector = Direction()
self.view_to_world_scale = 1.0
self.aspect_ratio = 1.0
class PerspectiveCamera:
def __init__(self):
self.camera_view_point = Point()
self.camera_direction = Direction()
self.camera_up_vector = Direction()
self.field_of_view = 60.0
self.aspect_ratio = 1.0
class Line:
def __init__(self):
self.start_point = Point()
self.end_point = Point()
class ClippingPlane:
def __init__(self):
self.location = Point()
self.direction = Direction()
class Bitmap:
def __init__(self):
self.reference = "" # Only in BCF-XML
self.bitmap_data = None # Only in BCF-API
self.bitmap_format = "PNG" # Enum of png or jpg
self.location = Point()
self.normal = Direction()
self.up = Direction()
self.height = 1.0
class Viewpoint:
def __init__(self):
self.guid = None
self.viewpoint = None
self.snapshot = None
self.index = None
self.components = None # It's not a list, despite the plural name
self.orthogonal_camera = None
self.perspective_camera = None
self.lines = []
self.clipping_planes = []
self.bitmaps = []
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="shared-types.xsd"/>
<xs:element name="DocumentInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Documents" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Document" type="Document" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Document">
<xs:sequence>
<!-- Filename of the document with the file extension. Not used to store the file in the BCF -->
<xs:element name="Filename" type="NonEmptyOrBlankString"/>
<!-- Human readable description of the document -->
<xs:element name="Description" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attributeGroup ref="DocumentAttributes"/>
</xs:complexType>
<xs:attributeGroup name="DocumentAttributes">
<!-- Guid of the document. Must match the filename in the BCF -->
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:attributeGroup>
</xs:schema>
+60
View File
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="shared-types.xsd"/>
<xs:element name="Extensions">
<xs:complexType>
<xs:sequence>
<xs:element name="TopicTypes" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="TopicType" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="TopicStatuses" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="TopicStatus" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Priorities" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Priority" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="TopicLabels" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="TopicLabel" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Users" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="User" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SnippetTypes" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="SnippetType" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Stages" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Stage" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
+174
View File
@@ -0,0 +1,174 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="shared-types.xsd"/>
<xs:element name="Markup">
<xs:complexType>
<xs:sequence>
<xs:element name="Header" type="Header" minOccurs="0"/>
<xs:element name="Topic" type="Topic"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Header">
<xs:sequence>
<xs:element name="Files" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="File" type="File" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<!-- ISG Jira issue BCF-9. Add support for several viewpoints and snapshots per issue -->
<xs:complexType name="ViewPoint">
<xs:sequence>
<!-- viewpoint file (xml) -->
<xs:element name="Viewpoint" type="NonEmptyOrBlankString" minOccurs="0"/>
<!-- the snapshot png -->
<xs:element name="Snapshot" type="NonEmptyOrBlankString" minOccurs="0"/>
<!-- the viewpoint index (sort order) -->
<xs:element name="Index" type="xs:int" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="Guid" type="Guid" use="required"/>
<!-- Guid of the viewpoint -->
</xs:complexType>
<!-- BimSnippet -->
<xs:complexType name="BimSnippet">
<xs:sequence>
<!--
Name of the file in the topic folder containing the snippet or a URL.
E.G.- Expresscode containing p.e Issue, Request
// Maybe some header infos ?? // IfcEntites // Geometry
-->
<!-- Reference (name) to the snippet file -->
<xs:element name="Reference" type="NonEmptyOrBlankString"/>
<xs:element name="ReferenceSchema" type="NonEmptyOrBlankString"/>
</xs:sequence>
<xs:attribute name="SnippetType" type="NonEmptyOrBlankString" use="required"/>
<xs:attribute name="IsExternal" type="xs:boolean" default="false"/>
<!-- This flag is true when the reference is a URL pointing outside of the BCF file-->
</xs:complexType>
<xs:complexType name="Topic">
<xs:sequence>
<xs:element name="ReferenceLinks" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="ReferenceLink" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Title" type="NonEmptyOrBlankString"/>
<xs:element name="Priority" type="NonEmptyOrBlankString" minOccurs="0"/>
<!-- ISG Jira issue BCF-8 Add a way save order the topics -->
<!-- This property is deprecated and will be removed in a future release -->
<xs:element name="Index" type="xs:int" minOccurs="0"/>
<xs:element name="Labels" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Label" type="NonEmptyOrBlankString" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="CreationDate" type="xs:dateTime"/>
<xs:element name="CreationAuthor" type="NonEmptyOrBlankString"/>
<xs:element name="ModifiedDate" type="xs:dateTime" minOccurs="0"/>
<xs:element name="ModifiedAuthor" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="DueDate" type="xs:dateTime" minOccurs="0"/>
<xs:element name="AssignedTo" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="Stage" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="Description" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="BimSnippet" type="BimSnippet" minOccurs="0"/>
<xs:element name="DocumentReferences" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="DocumentReference" type="DocumentReference" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="RelatedTopics" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="RelatedTopic" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Comments" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Comment" type="Comment" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- ISG Jira issue BCF-9. Add support for several viewpoints and snapshots per issue -->
<xs:element name="Viewpoints" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="ViewPoint" type="ViewPoint" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="Guid" type="Guid" use="required"/>
<xs:attribute name="ServerAssignedId" type="NonEmptyOrBlankString" use="optional"/>
<xs:attribute name="TopicType" type="NonEmptyOrBlankString" use="required"/>
<xs:attribute name="TopicStatus" type="NonEmptyOrBlankString" use="required"/>
</xs:complexType>
<xs:complexType name="File">
<xs:sequence>
<xs:element name="Filename" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="Date" type="xs:dateTime" minOccurs="0"/>
<!-- Reference (URL) of the file -->
<xs:element name="Reference" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attributeGroup ref="FileAttributes"/>
</xs:complexType>
<xs:attributeGroup name="FileAttributes">
<xs:attribute name="IfcProject" type="IfcGuid" use="optional"/>
<xs:attribute name="IfcSpatialStructureElement" type="IfcGuid" use="optional"/>
<xs:attribute name="IsExternal" type="xs:boolean" default="true"/>
</xs:attributeGroup>
<!-- Reference to a document inside of the topic folder or a url pointing to the web -->
<xs:complexType name="DocumentReference">
<xs:sequence>
<xs:choice>
<!-- Guid of the document: If pointing to an internal document -->
<xs:element name="DocumentGuid" type="Guid" minOccurs="0"/>
<!-- Url of the reference. If pointing to an external document -->
<xs:element name="Url" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:choice>
<!-- Human readable description of the document reference -->
<xs:element name="Description" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attributeGroup ref="DocumentReferenceAttributes"/>
</xs:complexType>
<xs:attributeGroup name="DocumentReferenceAttributes">
<!-- Guid of the document reference -->
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:attributeGroup>
<xs:complexType name="Comment">
<xs:sequence>
<xs:element name="Date" type="xs:dateTime"/>
<xs:element name="Author" type="NonEmptyOrBlankString"/>
<xs:element name="Comment" minOccurs="0" type="NonEmptyOrBlankString"/>
<xs:element name="Viewpoint" minOccurs="0">
<xs:complexType>
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:complexType>
</xs:element>
<xs:element name="ModifiedDate" type="xs:dateTime" minOccurs="0"/>
<xs:element name="ModifiedAuthor" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:complexType>
<xs:simpleType name="IfcGuid">
<xs:restriction base="xs:string">
<xs:length value="22"/>
<xs:pattern value="[0-9A-Za-z_$]*"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="shared-types.xsd"/>
<xs:element name="ProjectInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Project" type="Project"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Project">
<xs:sequence>
<xs:element name="Name" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="ProjectId" type="NonEmptyOrBlankString" use="required"/>
</xs:complexType>
</xs:schema>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="Guid">
<xs:restriction base="xs:string">
<xs:pattern value="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="NonEmptyOrBlankString">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:whiteSpace value="collapse"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Version">
<xs:complexType>
<xs:attribute name="VersionId" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
+220
View File
@@ -0,0 +1,220 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:include schemaLocation="shared-types.xsd"/>
<xs:element name="VisualizationInfo">
<xs:annotation>
<xs:documentation>VisualizationInfo documentation</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<!--
Although plural, 'Components' is not a collection
-->
<xs:element name="Components" type="Components" minOccurs="0"/>
<xs:choice>
<xs:element name="OrthogonalCamera" type="OrthogonalCamera"/>
<xs:element name="PerspectiveCamera" type="PerspectiveCamera"/>
</xs:choice>
<xs:element name="Lines" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Line" type="Line" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ClippingPlanes" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="ClippingPlane" type="ClippingPlane" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Bitmaps" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Bitmap" type="Bitmap" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<!-- Guid of the viewpoint -->
<xs:attribute name="Guid" type="Guid" use="required"/>
</xs:complexType>
</xs:element>
<xs:complexType name="OrthogonalCamera">
<xs:sequence>
<xs:element name="CameraViewPoint" type="Point"/>
<xs:element name="CameraDirection" type="Direction"/>
<xs:element name="CameraUpVector" type="Direction"/>
<xs:element name="ViewToWorldScale" type="xs:double">
<xs:annotation>
<xs:documentation>view's visible vertical size in meters</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="AspectRatio" type="PositiveDouble">
<xs:annotation>
<xs:documentation>
Proportional relationship between the width and the height of the view (w/h).
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="PerspectiveCamera">
<xs:sequence>
<xs:element name="CameraViewPoint" type="Point"/>
<xs:element name="CameraDirection" type="Direction"/>
<xs:element name="CameraUpVector" type="Direction"/>
<xs:element name="FieldOfView" type="FieldOfView">
<xs:annotation>
<xs:documentation>
Vertical field of view, in degrees.
It is currently limited to a value between 45 and 60 degrees.
This limitation will be dropped in the next release and viewers
should be expect values outside this range in current implementations.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="AspectRatio" type="PositiveDouble">
<xs:annotation>
<xs:documentation>
Proportional relationship between the width and the height of the view (w/h).
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Point">
<xs:sequence>
<xs:element name="X" type="xs:double"/>
<xs:element name="Y" type="xs:double"/>
<xs:element name="Z" type="xs:double"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Direction">
<xs:sequence>
<xs:element name="X" type="xs:double"/>
<xs:element name="Y" type="xs:double"/>
<xs:element name="Z" type="xs:double"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="PositiveDouble">
<xs:restriction base="xs:double">
<xs:minExclusive value="0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="FieldOfView">
<xs:restriction base="xs:double">
<xs:minExclusive value="0"/>
<xs:maxExclusive value="180"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="Components">
<xs:sequence>
<!-- Components with relevance to the viewpoint. They should be displayed highlighted or selected in a viewer -->
<xs:element name="Selection" type="ComponentSelection" minOccurs="0"/>
<xs:element name="Visibility" type="ComponentVisibility" minOccurs="0"/>
<xs:element name="Coloring" type="ComponentColoring" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ComponentSelection">
<xs:sequence>
<xs:element name="Component" type="Component" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ComponentVisibility">
<xs:sequence>
<xs:element name="ViewSetupHints" type="ViewSetupHints" minOccurs="0"/>
<xs:element name="Exceptions" minOccurs="0">
<!-- List Components that are different than the DefaultVisibility. E.g. if DefaultVisibility = false then list
Components that should be visible -->
<xs:complexType>
<xs:sequence>
<xs:element name="Component" type="Component" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="DefaultVisibility" type="xs:boolean" default="false"/>
</xs:complexType>
<xs:complexType name="ViewSetupHints">
<xs:attribute name="SpacesVisible" type="xs:boolean" default="false"/>
<xs:attribute name="SpaceBoundariesVisible" type="xs:boolean" default="false"/>
<xs:attribute name="OpeningsVisible" type="xs:boolean" default="false"/>
</xs:complexType>
<xs:complexType name="ComponentColoring">
<xs:sequence>
<xs:element name="Color" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<!-- At least one component is required for a Color. -->
<xs:element name="Components">
<xs:complexType>
<xs:sequence>
<xs:element name="Component" type="Component" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute ref="Color" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Component">
<xs:sequence>
<xs:element name="OriginatingSystem" type="NonEmptyOrBlankString" minOccurs="0"/>
<xs:element name="AuthoringToolId" type="NonEmptyOrBlankString" minOccurs="0"/>
</xs:sequence>
<xs:attribute ref="IfcGuid"/>
</xs:complexType>
<xs:attribute name="Color">
<xs:simpleType>
<xs:restriction base="xs:normalizedString">
<!-- Should either match 3 or 4 hex bytes , e.g. "FF00FF" or "FF00FF99" -->
<xs:pattern value="[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="IfcGuid">
<xs:simpleType>
<xs:restriction base="xs:normalizedString">
<xs:length value="22"/>
<xs:pattern value="[0-9A-Za-z_$]*"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:complexType name="Line">
<xs:sequence>
<xs:element name="StartPoint" type="Point"/>
<xs:element name="EndPoint" type="Point"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ClippingPlane">
<xs:sequence>
<xs:element name="Location" type="Point"/>
<xs:element name="Direction" type="Direction"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Bitmap">
<xs:sequence>
<xs:element name="Format" type="BitmapFormat"/>
<!-- Name of the bitmap file in the topic folder -->
<xs:element name="Reference" type="NonEmptyOrBlankString"/>
<!-- Location of the center of the bitmap -->
<xs:element name="Location" type="Point"/>
<!-- Normal of the bitmap -->
<xs:element name="Normal" type="Direction"/>
<!-- Upvector of the bitmap -->
<xs:element name="Up" type="Direction"/>
<!-- Height of the bitmap -->
<xs:element name="Height" type="xs:double"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="BitmapFormat">
<xs:restriction base="xs:string">
<xs:enumeration value="png"/>
<xs:enumeration value="jpg"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
+17 -102
View File
@@ -1,45 +1,6 @@
VERSION:=`date '+%y%m%d'`
PYVERSION:=py37
ifeq ($(PLATFORM), win)
ifeq ($(PYVERSION), py37)
PYTHONOCC_URL:=https://anaconda.org/DLR-SC/pythonocc-core/0.17.3/download/win-64/pythonocc-core-0.17.3-py37he980bc4_10.tar.bz2
OCE_URL:=https://anaconda.org/DLR-SC/oce/0.17.2/download/win-64/oce-0.17.2-he980bc4_14.tar.bz2
TBB_URL:=https://anaconda.org/DLR-SC/tbb/2019.5/download/win-64/tbb-2019.5-he980bc4_0.tar.bz2
endif
ifeq ($(PYVERSION), py39)
PYTHONOCC_URL:=https://anaconda.org/conda-forge/pythonocc-core/7.4.1/download/win-64/pythonocc-core-7.4.1-py39h3d1c7c5_0.tar.bz2
OCE_URL:=https://anaconda.org/conda-forge/occt/7.4.0/download/win-64/occt-7.4.0-h823b557_3.tar.bz2
TBB_URL:=https://anaconda.org/conda-forge/tbb/2020.2/download/win-64/tbb-2020.2-h2d74725_4.tar.bz2
endif
endif
ifeq ($(PLATFORM), macos)
ifeq ($(PYVERSION), py37)
PYTHONOCC_URL:=https://anaconda.org/DLR-SC/pythonocc-core/0.17.3/download/osx-64/pythonocc-core-0.17.3-py37h04f5b5a_10.tar.bz2
OCE_URL:=https://anaconda.org/DLR-SC/oce/0.17.2/download/osx-64/oce-0.17.2-h04f5b5a_12.tar.bz2
TBB_URL:=https://anaconda.org/DLR-SC/tbb/4.3.6/download/osx-64/tbb-4.3.6-0.tar.bz2
endif
ifeq ($(PYVERSION), py39)
PYTHONOCC_URL:=https://anaconda.org/conda-forge/pythonocc-core/7.4.1/download/osx-64/pythonocc-core-7.4.1-py39h4d29fe3_0.tar.bz2
OCE_URL:=https://anaconda.org/conda-forge/occt/7.4.0/download/osx-64/occt-7.4.0-hb9b6dc7_3.tar.bz2
TBB_URL:=https://anaconda.org/conda-forge/tbb/2020.2/download/osx-64/tbb-2020.2-h940c156_4.tar.bz2
endif
endif
ifeq ($(PLATFORM), linux)
ifeq ($(PYVERSION), py37)
PYTHONOCC_URL:=https://anaconda.org/DLR-SC/pythonocc-core/0.17.3/download/linux-64/pythonocc-core-0.17.3-py37h6bb024c_10.tar.bz2
OCE_URL:=https://anaconda.org/DLR-SC/oce/0.17.2/download/linux-64/oce-0.17.2-h6bb024c_14.tar.bz2
TBB_URL:=https://anaconda.org/DLR-SC/tbb/4.3.6/download/linux-64/tbb-4.3.6-0.tar.bz2
endif
ifeq ($(PYVERSION), py39)
PYTHONOCC_URL:=https://anaconda.org/conda-forge/pythonocc-core/7.4.1/download/linux-64/pythonocc-core-7.4.1-py39h465cb30_0.tar.bz2
OCE_URL:=https://anaconda.org/conda-forge/occt/7.4.0/download/linux-64/occt-7.4.0-h9121d39_3.tar.bz2
TBB_URL:=https://anaconda.org/conda-forge/tbb/2020.2/download/linux-64/tbb-2020.2-h4bd325d_4.tar.bz2
endif
endif
.PHONY: dist
dist:
ifndef PLATFORM
@@ -52,10 +13,10 @@ endif
# Provides IfcOpenShell Python functionality
ifeq ($(PYVERSION), py37)
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-37-v0.6.0-ff7219b-$(PLATFORM)64.zip
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-37-v0.6.0-81ad689-$(PLATFORM)64.zip
endif
ifeq ($(PYVERSION), py39)
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-39-v0.6.0-ff7219b-$(PLATFORM)64.zip
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-39-v0.6.0-81ad689-$(PLATFORM)64.zip
endif
cd dist/working && unzip ifcblender*
cp -r dist/working/io_import_scene_ifc/ifcopenshell dist/blenderbim/libs/site/packages/
@@ -67,7 +28,7 @@ endif
# Provides IfcConvert for construction documentation
mkdir dist/working
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/IfcConvert-v0.6.0-517b819-$(PLATFORM)64.zip
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/IfcConvert-v0.6.0-81ad689-$(PLATFORM)64.zip
cd dist/working && unzip IfcConvert*
ifeq ($(PLATFORM), win)
cp -r dist/working/IfcConvert.exe dist/blenderbim/libs/
@@ -76,66 +37,6 @@ else
endif
rm -rf dist/working
# Provides Python OCC functionality for cutting IFC geometry for construction documentation
mkdir dist/working
cd dist/working && wget $(PYTHONOCC_URL)
cd dist/working && tar -xjvf pythonocc-core*
ifeq ($(PLATFORM), win)
cd dist/working && cp -r Lib/site-packages/OCC ../blenderbim/libs/site/packages/
else
ifeq ($(PYVERSION), py37)
cd dist/working && cp -r lib/python3.7/site-packages/OCC ../blenderbim/libs/site/packages/
endif
ifeq ($(PYVERSION), py39)
cd dist/working && cp -r lib/python3.9/site-packages/OCC ../blenderbim/libs/site/packages/
endif
endif
rm -rf dist/working
# Required by Python OCC
mkdir dist/working
cd dist/working && wget $(OCE_URL)
cd dist/working && tar -xjvf oc*
ifeq ($(PLATFORM), win)
ifeq ($(PYVERSION), py37)
cd dist/working && cp -r Library/bin/* ../blenderbim/libs/site/packages/OCC/
endif
ifeq ($(PYVERSION), py39)
cd dist/working && cp -r Library/bin/* ../blenderbim/libs/site/packages/OCC/Core/
endif
else
# Unix Conda builds of PythonOCC expect OCE libs to have a RPATH of ../../../
cd dist/working && cp -r lib/* ../blenderbim/libs/
endif
ifeq ($(PLATFORM), linux)
rm -rf dist/blenderbim/libs/oce-0.17
endif
rm -rf dist/working
# Required by OpenCascade
mkdir dist/working
cd dist/working && wget $(TBB_URL)
cd dist/working && tar -xjvf tbb*
ifeq ($(PLATFORM), win)
ifeq ($(PYVERSION), py37)
cd dist/working && cp -r Library/bin/* ../blenderbim/libs/site/packages/OCC/
endif
ifeq ($(PYVERSION), py39)
cd dist/working && cp -r Library/bin/* ../blenderbim/libs/site/packages/OCC/Core/
endif
else
cd dist/working && cp -r lib/* ../blenderbim/libs/
endif
rm -rf dist/working
ifeq ($(PLATFORM), macos)
mkdir dist/working
cd dist/working && wget https://blenderbim.org/builds/patch-blender28-bim-macos.zip
cd dist/working && unzip patch*
cd dist/working && cp -r *.dylib ../blenderbim/libs/
rm -rf dist/working
endif
# Provides dependencies that are part of IfcOpenShell
mkdir dist/working
cd dist/working && wget https://github.com/IfcOpenShell/IfcOpenShell/archive/v0.6.0.zip
@@ -191,6 +92,20 @@ endif
cp -r dist/working/isodate-0.6.0/src/isodate dist/blenderbim/libs/site/packages/
rm -rf dist/working
# Provides networkx graph analysis for project dependency calculations
mkdir dist/working
cd dist/working && wget https://files.pythonhosted.org/packages/b0/21/adfbf6168631e28577e4af9eb9f26d75fe72b2bb1d33762a5f2c425e6c2a/networkx-2.5.1.tar.gz
cd dist/working && tar -xzvf networkx*
cp -r dist/working/networkx-2.5.1/networkx dist/blenderbim/libs/site/packages/
rm -rf dist/working
# Required by networkx
mkdir dist/working
cd dist/working && wget https://files.pythonhosted.org/packages/4f/51/15a4f6b8154d292e130e5e566c730d8ec6c9802563d58760666f1818ba58/decorator-5.0.9.tar.gz
cd dist/working && tar -xzvf decorator*
cp -r dist/working/decorator-5.0.9/src/decorator.py dist/blenderbim/libs/site/packages/
rm -rf dist/working
# Provides jsgantt-improved supports for web-based construction sequencing gantt charts
mkdir dist/working
cd dist/working && wget https://raw.githubusercontent.com/jsGanttImproved/jsgantt-improved/master/dist/jsgantt.js
+1
View File
@@ -15,6 +15,7 @@ import site
# process *.pth in /libs/site/packages to setup globally importable modules
# 3 levels deep required by occ static ../../ path
# TODO: 3 levels deep is no longer required as we no longer bundle OCC
cwd = os.path.dirname(os.path.realpath(__file__))
site.addsitedir(os.path.join(cwd, "libs", "site", "packages"))
+10 -78
View File
@@ -6,14 +6,16 @@ bpy = sys.modules.get("bpy")
if bpy is not None:
import bpy
import importlib
from . import handler, ui, prop, operator, gizmos
from . import handler, ui, prop, operator
modules = {
"project": None,
"parametric": None,
"search": None,
"bcf": None,
"root": None,
"unit": None,
"model": None,
"georeference": None,
"context": None,
"drawing": None,
@@ -29,10 +31,10 @@ if bpy is not None:
"sequence": None,
"group": None,
"structural": None,
"boundary": None,
"material": None,
"style": None,
"layer": None,
"model": None,
"owner": None,
"pset": None,
"qto": None,
@@ -61,96 +63,34 @@ if bpy is not None:
operator.ExportIFC,
operator.ImportIFC,
operator.SelectExternalMaterialDir,
operator.AddSweptSolid,
operator.RemoveSweptSolid,
operator.AssignSweptSolidOuterCurve,
operator.SelectSweptSolidOuterCurve,
operator.AddSweptSolidInnerCurve,
operator.SelectSweptSolidInnerCurves,
operator.AssignSweptSolidExtrusion,
operator.SelectSweptSolidExtrusion,
operator.FetchExternalMaterial,
operator.FetchObjectPassport,
operator.CutSection,
operator.AddSheet,
operator.OpenSheet,
operator.AddDrawingToSheet,
operator.CreateSheets,
operator.OpenView,
operator.OpenViewCamera,
operator.ActivateView,
operator.OpenUpstream,
operator.AddSectionPlane,
operator.RemoveSectionPlane,
operator.ReloadIfcFile,
operator.AddIfcFile,
operator.RemoveIfcFile,
operator.SelectDocIfcFile,
operator.GenerateReferences,
operator.ResizeText,
operator.AddVariable,
operator.RemoveVariable,
operator.PropagateTextData,
operator.SetOverrideColour,
operator.RemoveDrawing,
operator.AddDrawingStyle,
operator.RemoveDrawingStyle,
operator.SaveDrawingStyle,
operator.ActivateDrawingStyle,
operator.EditVectorStyle,
operator.RemoveSheet,
operator.AddSchedule,
operator.RemoveSchedule,
operator.SelectScheduleFile,
operator.BuildSchedule,
operator.AddScheduleToSheet,
operator.SetViewportShadowFromSun,
operator.AddDrawingStyleAttribute,
operator.RemoveDrawingStyleAttribute,
operator.CopyPropertyToSelection,
operator.CopyAttributeToSelection,
operator.RefreshDrawingList,
operator.CleanWireframes,
operator.LinkIfc,
operator.SnapSpacesTogether,
operator.CopyGrid,
operator.AddSectionsAnnotations,
prop.StrProperty,
prop.Attribute,
prop.Variable,
prop.Drawing,
prop.Schedule,
prop.DrawingStyle,
prop.Sheet,
prop.BIMProperties,
prop.DocProperties,
prop.IfcParameter,
prop.PsetQto,
prop.GlobalId,
prop.RepresentationItem,
prop.BIMObjectProperties,
prop.BIMMaterialProperties,
prop.SweptSolid,
prop.ItemSlotMap,
prop.BIMMeshProperties,
prop.BIMCameraProperties,
prop.BIMTextProperties,
ui.BIM_PT_section_plane,
ui.BIM_PT_drawings,
ui.BIM_PT_schedules,
ui.BIM_PT_sheets,
ui.BIM_PT_text,
ui.BIM_PT_annotation_utilities,
ui.BIM_PT_misc_utilities,
ui.BIM_UL_generic,
ui.BIM_UL_drawinglist,
ui.BIM_UL_topics,
ui.BIM_ADDON_preferences,
gizmos.UglyDotGizmo,
gizmos.DotGizmo,
gizmos.DimensionLabelGizmo,
gizmos.ExtrusionGuidesGizmo,
gizmos.ExtrusionWidget
]
for module in modules.values():
@@ -176,24 +116,21 @@ if bpy is not None:
bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
bpy.types.Scene.BIMProperties = bpy.props.PointerProperty(type=prop.BIMProperties)
bpy.types.Scene.DocProperties = bpy.props.PointerProperty(type=prop.DocProperties)
bpy.types.Object.BIMObjectProperties = bpy.props.PointerProperty(type=prop.BIMObjectProperties)
bpy.types.Material.BIMObjectProperties = bpy.props.PointerProperty(type=prop.BIMObjectProperties)
bpy.types.Collection.BIMObjectProperties = bpy.props.PointerProperty(type=prop.BIMObjectProperties) # Check if we need this
bpy.types.Collection.BIMObjectProperties = bpy.props.PointerProperty(
type=prop.BIMObjectProperties
) # Check if we need this
bpy.types.Material.BIMMaterialProperties = bpy.props.PointerProperty(type=prop.BIMMaterialProperties)
bpy.types.Mesh.BIMMeshProperties = bpy.props.PointerProperty(type=prop.BIMMeshProperties)
bpy.types.Curve.BIMMeshProperties = bpy.props.PointerProperty(type=prop.BIMMeshProperties)
bpy.types.Camera.BIMMeshProperties = bpy.props.PointerProperty(type=prop.BIMMeshProperties)
bpy.types.Camera.BIMCameraProperties = bpy.props.PointerProperty(type=prop.BIMCameraProperties)
bpy.types.TextCurve.BIMTextProperties = bpy.props.PointerProperty(type=prop.BIMTextProperties)
bpy.types.PointLight.BIMMeshProperties = bpy.props.PointerProperty(type=prop.BIMMeshProperties)
bpy.types.SCENE_PT_unit.append(ui.ifc_units)
for module in modules.values():
module.register()
bpy.app.handlers.depsgraph_update_pre.append(operator.depsgraph_update_pre_handler)
bpy.app.handlers.load_post.append(handler.toggleDecorationsOnLoad)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
@@ -203,20 +140,15 @@ if bpy is not None:
bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
del bpy.types.Scene.BIMProperties
del bpy.types.Scene.DocProperties
del bpy.types.Object.BIMObjectProperties
del bpy.types.Material.BIMObjectProperties
del bpy.types.Collection.BIMObjectProperties # Check if we need this
del bpy.types.Collection.BIMObjectProperties # Check if we need this
del bpy.types.Material.BIMMaterialProperties
del bpy.types.Mesh.BIMMeshProperties
del bpy.types.Curve.BIMMeshProperties
del bpy.types.Camera.BIMMeshProperties
del bpy.types.Camera.BIMCameraProperties
del bpy.types.TextCurve.BIMTextProperties
del bpy.types.PointLight.BIMMeshProperties
bpy.types.SCENE_PT_unit.remove(ui.ifc_units)
for module in reversed(list(modules.values())):
module.unregister()
bpy.app.handlers.depsgraph_update_pre.remove(operator.depsgraph_update_pre_handler)
bpy.app.handlers.load_post.remove(handler.toggleDecorationsOnLoad)
-552
View File
@@ -1,552 +0,0 @@
import os
import re
import math
import time
import numpy
import pickle
import multiprocessing
def load_occ():
# Don't import until we really need to, as a temporary step before we can purge OCC
try:
from OCC.Core import (
gp,
Geom,
Bnd,
BRepBndLib,
BRep,
BRepPrimAPI,
BRepAlgoAPI,
BRepBuilderAPI,
TopOpeBRepTool,
TopOpeBRepBuild,
ShapeExtend,
GProp,
BRepGProp,
GC,
ShapeAnalysis,
TopTools,
TopExp,
TopAbs,
HLRAlgo,
HLRBRep,
TopLoc,
Bnd,
BRepBndLib,
BRepTools,
TopoDS,
GeomLProp,
IntCurvesFace,
)
from OCC.Core.TopoDS import topods
except ImportError:
from OCC import (
gp,
Geom,
Bnd,
BRepBndLib,
BRep,
BRepPrimAPI,
BRepAlgoAPI,
BRepBuilderAPI,
TopOpeBRepTool,
TopOpeBRepBuild,
ShapeExtend,
GProp,
BRepGProp,
GC,
ShapeAnalysis,
TopTools,
TopExp,
TopAbs,
HLRAlgo,
HLRBRep,
TopLoc,
Bnd,
BRepBndLib,
BRepTools,
TopoDS,
GeomLProp,
IntCurvesFace,
)
from OCC.TopoDS import topods
import ifcopenshell
import ifcopenshell.geom
import ifcopenshell.util.selector
import ifcopenshell.util.element
cwd = os.path.dirname(os.path.realpath(__file__))
this_file = os.path.join(cwd, "cut_ifc.py")
def get_booleaned_edges(shape):
load_occ()
edges = []
exp = TopExp.TopExp_Explorer(shape, TopAbs.TopAbs_EDGE)
while exp.More():
edges.append(topods.Edge(exp.Current()))
exp.Next()
return edges
def connect_edges_into_wires(unconnected_edges):
load_occ()
edges = TopTools.TopTools_HSequenceOfShape()
edges_handle = TopTools.Handle_TopTools_HSequenceOfShape(edges)
wires = TopTools.TopTools_HSequenceOfShape()
wires_handle = TopTools.Handle_TopTools_HSequenceOfShape(wires)
for edge in unconnected_edges:
edges.Append(edge)
ShapeAnalysis.ShapeAnalysis_FreeBounds.ConnectEdgesToWires(edges_handle, 1e-5, True, wires_handle)
return wires_handle.GetObject()
def do_cut(process_data):
load_occ()
global_id, shape, section, trsf_data = process_data
axis = gp.gp_Ax2(
gp.gp_Pnt(trsf_data["top_left_corner"][0], trsf_data["top_left_corner"][1], trsf_data["top_left_corner"][2]),
gp.gp_Dir(trsf_data["projection"][0], trsf_data["projection"][1], trsf_data["projection"][2]),
gp.gp_Dir(trsf_data["x_axis"][0], trsf_data["x_axis"][1], trsf_data["x_axis"][2]),
)
source = gp.gp_Ax3(axis)
destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1), gp.gp_Dir(1, 0, 0))
transformation = gp.gp_Trsf()
transformation.SetDisplacement(source, destination)
cut_polygons = []
section = BRepAlgoAPI.BRepAlgoAPI_Section(section, shape).Shape()
section_edges = get_booleaned_edges(section)
if len(section_edges) <= 0:
return cut_polygons
wires = connect_edges_into_wires(section_edges)
for i in range(wires.Length()):
wire_shape = wires.Value(i + 1)
transformed_wire = BRepBuilderAPI.BRepBuilderAPI_Transform(wire_shape, transformation)
wire_shape = transformed_wire.Shape()
wire = topods.Wire(wire_shape)
face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire).Face()
points = []
exp = BRepTools.BRepTools_WireExplorer(wire)
while exp.More():
point = BRep.BRep_Tool.Pnt(exp.CurrentVertex())
points.append((point.X(), -point.Y()))
exp.Next()
cut_polygons.append({"global_id": global_id, "metadata": {}, "points": points})
return cut_polygons
class IfcCutter:
def __init__(self):
self.time = None
self.selector = ifcopenshell.util.selector.Selector()
self.product_shapes = []
self.background_elements = []
self.cut_polygons = []
self.template_variables = {}
self.metadata = {}
self.data_dir = ""
self.vector_style = ""
self.ifc_filenames = []
self.ifc_files = {}
self.resolved_pixels = set()
self.text_pickle_file = "text.pickle"
self.metadata_pickle_file = "metadata.pickle"
self.cut_pickle_file = "cut.pickle"
self.should_recut = True
self.should_recut_selected = True
self.cut_objects = ""
self.selected_global_ids = []
self.should_extract = True
self.diagram_name = None
self.background_image = None
self.section_box = {
"projection": (0, 1, 0),
"x_axis": (1, 0, 0),
"y_axis": (0, 0, -1),
"top_left_corner": (-2, 2, 8),
"x": 14,
"y": 9,
"z": 2,
"shape": None,
"face": None,
}
def cut(self):
self.profile_code("Starting cut process")
self.load_ifc_files()
self.profile_code("Load IFC files")
self.get_template_variables()
self.profile_code("Get template variables")
self.get_product_shapes()
self.profile_code("Get product shapes")
self.create_section_box()
self.profile_code("Create section box")
self.get_cut_polygons()
self.profile_code("Get cut polygons")
self.get_annotation()
self.profile_code("Get annotation")
self.get_cut_polygon_metadata()
self.profile_code("Get cut polygon metadata")
def profile_code(self, message):
if not self.time:
self.time = time.time()
print("{} :: {:.2f}".format(message, time.time() - self.time))
self.time = time.time()
def load_ifc_files(self):
if not self.should_recut and not self.should_extract:
return
loaded_files = []
for filename in self.ifc_filenames:
print("Loading file {} ...".format(filename))
if filename:
self.ifc_files[filename] = ifcopenshell.open(filename)
def get_template_variables(self):
if not self.should_extract:
if os.path.isfile(self.text_pickle_file):
with open(self.text_pickle_file, "rb") as text_file:
self.template_variables = pickle.load(text_file)
return
data = {}
for text_obj in self.text_objs:
text_obj_data = self.get_text_variables(text_obj)
if text_obj_data:
data[text_obj.name] = text_obj_data
with open(self.text_pickle_file, "wb") as text_file:
pickle.dump(data, text_file, protocol=pickle.HIGHEST_PROTOCOL)
self.template_variables = data
def get_text_variables(self, text_obj):
text_obj_data = {}
text_body = text_obj.data.body
related_element = text_obj.data.BIMTextProperties.related_element
if not related_element:
return
global_id = related_element.BIMObjectProperties.attributes.get("GlobalId")
if not global_id:
return
element = self.get_ifc_element(global_id.string_value)
for variable in text_obj.data.BIMTextProperties.variables:
if element:
if "{{" in variable.prop_key:
prop_key = variable.prop_key.split("{{")[1].split("}}")[0]
prop_value = self.selector.get_element_value(element, prop_key)
variable_value = eval(variable.prop_key.replace("{{" + prop_key + "}}", str(prop_value)))
else:
variable_value = self.selector.get_element_value(element, variable.prop_key)
text_obj_data[variable.name] = variable_value
return text_obj_data
def get_product_shapes(self):
if not self.should_recut:
return
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)
products = []
for filename, ifc_file in self.ifc_files.items():
shape_pickle = os.path.join(
self.data_dir, "cache", "shapes", "{}.pickle".format(os.path.basename(filename))
)
shape_map = {}
if self.should_recut_selected and os.path.isfile(shape_pickle):
with open(shape_pickle, "rb") as shape_file:
shape_map = pickle.load(shape_file)
products.extend(self.selector.parse(ifc_file, self.cut_objects))
selected_elements = []
for i, product in enumerate(products):
if (
product.is_a("IfcOpeningElement")
or product.is_a("IfcSite")
or product.Representation is None
or self.has_annotation(product)
):
continue
try:
if self.should_recut_selected and product.GlobalId in self.selected_global_ids:
selected_elements.append(product)
elif product.GlobalId in shape_map:
shape = shape_map[product.GlobalId]
self.add_product_shape(product, shape)
else:
selected_elements.append(product)
except:
print("Failed to create shape for {}".format(product))
if selected_elements:
total = 0
checkpoint = time.time()
iterator = ifcopenshell.geom.iterator(
settings, ifc_file, multiprocessing.cpu_count(), include=selected_elements
)
valid_file = iterator.initialize()
if valid_file:
while True:
total += 1
if total % 250 == 0:
print("{} elements processed in {:.2f}s ...".format(total, time.time() - checkpoint))
checkpoint = time.time()
shape = iterator.get()
shape_map[shape.data.guid] = shape.geometry
self.add_product_shape(ifc_file.by_guid(shape.data.guid), shape.geometry)
if not iterator.next():
break
with open(shape_pickle, "wb") as shape_file:
pickle.dump(shape_map, shape_file, protocol=pickle.HIGHEST_PROTOCOL)
def add_product_shape(self, product, shape):
self.product_shapes.append((product, shape))
def has_annotation(self, element):
for representation in element.Representation.Representations:
if (
representation.ContextOfItems.ContextType == "Plan"
and representation.ContextOfItems.ContextIdentifier == "Annotation"
):
return True
return False
def create_section_box(self):
load_occ()
top_left_corner = gp.gp_Pnt(
self.section_box["top_left_corner"][0],
self.section_box["top_left_corner"][1],
self.section_box["top_left_corner"][2],
)
axis = gp.gp_Ax2(
top_left_corner,
gp.gp_Dir(
self.section_box["projection"][0], self.section_box["projection"][1], self.section_box["projection"][2]
),
gp.gp_Dir(self.section_box["x_axis"][0], self.section_box["x_axis"][1], self.section_box["x_axis"][2]),
)
section_box = BRepPrimAPI.BRepPrimAPI_MakeBox(
axis, self.section_box["x"], self.section_box["y"], self.section_box["z"]
)
self.section_box["shape"] = section_box.Shape()
self.section_box["face"] = section_box.BottomFace()
source = gp.gp_Ax3(axis)
self.transformation_data = {
"top_left_corner": self.section_box["top_left_corner"],
"projection": self.section_box["projection"],
"x_axis": self.section_box["x_axis"],
}
destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1), gp.gp_Dir(1, 0, 0))
self.transformation_dest = destination
self.transformation = gp.gp_Trsf()
self.transformation.SetDisplacement(source, destination)
def get_bbox(self, shape):
load_occ()
bbox = Bnd.Bnd_Box()
BRepBndLib.brepbndlib_Add(shape, bbox)
return bbox
def calculate_face_zpos(self, face):
bbox = self.get_bbox(face)
xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
zpos = zmin + ((zmax - zmin) / 2)
return zpos, zmax
def get_booleaned_edges(self, shape):
load_occ()
edges = []
exp = TopExp.TopExp_Explorer(shape, TopAbs.TopAbs_EDGE)
while exp.More():
edges.append(topods.Edge(exp.Current()))
exp.Next()
return edges
def get_cut_polygons(self):
if self.should_recut:
self.get_fresh_cut_polygons()
self.pickle_cut_polygons()
else:
self.get_pickled_cut_polygons()
def get_annotation(self):
import mathutils
load_occ()
self.annotation_objs = []
settings_2d = ifcopenshell.geom.settings()
settings_2d.set(settings_2d.INCLUDE_CURVES, True)
settings_py = ifcopenshell.geom.settings()
settings_py.set(settings_py.USE_PYTHON_OPENCASCADE, True)
for ifc_file in self.ifc_files.values():
for element in ifc_file.by_type("IfcElement"):
annotation_representation = None
box_representation = None
if not element.Representation:
continue # This can occur for aggregates
for representation in element.Representation.Representations:
if (
representation.ContextOfItems.ContextType == "Plan"
and representation.ContextOfItems.ContextIdentifier == "Annotation"
):
annotation_representation = representation
elif (
representation.ContextOfItems.ContextType == "Model"
and representation.ContextOfItems.ContextIdentifier == "Box"
):
box_representation = representation
if not annotation_representation or not box_representation:
continue
# This is bad code. See bug #85 to make it slightly less bad.
# Effectively if the bbox does not intersect with the camera
# plane, then we should "continue" and not process the 2D
# wireframe. This approach works but is not very smart.
for subelement in ifc_file.traverse(box_representation):
if subelement.is_a("IfcBoundingBox"):
block = ifc_file.createIfcBlock(
ifc_file.createIfcAxis2Placement3D(subelement.Corner, None, None),
subelement.XDim,
subelement.YDim,
subelement.ZDim,
)
for inverse in ifc_file.get_inverse(subelement):
ifcopenshell.util.element.replace_attribute(inverse, subelement, block)
element.Representation.Representations = [box_representation]
shape = ifcopenshell.geom.create_shape(settings_py, element)
section = BRepAlgoAPI.BRepAlgoAPI_Section(self.section_box["face"], shape.geometry).Shape()
section_edges = get_booleaned_edges(section)
if len(section_edges) <= 0:
# The bounding box of the annotation object does not
# intersect with the camera plane, so don't bother drawing
# the annotation
continue
# Monkey patch - see bug #771.
element.Representation.Representations = [annotation_representation]
shape = ifcopenshell.geom.create_shape(settings_2d, element)
if hasattr(shape, "geometry"):
geometry = shape.geometry
else:
geometry = shape
e = geometry.edges
v = geometry.verts
m = shape.transformation.matrix.data
mat = mathutils.Matrix(
([m[0], m[1], m[2], 0], [m[3], m[4], m[5], 0], [m[6], m[7], m[8], 0], [m[9], m[10], m[11], 1])
)
mat.transpose()
self.annotation_objs.append(
{
"raw": element,
"classes": self.get_classes(element, "annotation"),
"edges": [[e[i], e[i + 1]] for i in range(0, len(e), 2)],
"vertices": [mat @ mathutils.Vector((v[i], v[i + 1], v[i + 2])) for i in range(0, len(v), 3)],
}
)
def get_cut_polygon_metadata(self):
if not self.should_extract:
if os.path.isfile(self.metadata_pickle_file):
with open(self.metadata_pickle_file, "rb") as metadata_file:
self.metadata = pickle.load(metadata_file)
for polygon in self.cut_polygons:
if polygon["global_id"] in self.metadata:
polygon["metadata"] = self.metadata[polygon["global_id"]]
return
for polygon in self.cut_polygons:
metadata = {"classes": self.get_classes(self.get_ifc_element(polygon["global_id"]), "cut")}
self.metadata[polygon["global_id"]] = metadata
polygon["metadata"] = metadata
with open(self.metadata_pickle_file, "wb") as metadata_file:
pickle.dump(self.metadata, metadata_file, protocol=pickle.HIGHEST_PROTOCOL)
def pickle_cut_polygons(self):
with open(self.cut_pickle_file, "wb") as pickle_file:
pickle.dump(self.cut_polygons, pickle_file, protocol=pickle.HIGHEST_PROTOCOL)
def get_fresh_cut_polygons(self):
process_data = [
(p.GlobalId, s, self.section_box["face"], self.transformation_data) for p, s in self.product_shapes
]
import bpy
if bpy.app.version > (2, 90, 0) and os.name == 'nt':
# See bug #1148
for data in process_data:
results = do_cut(data)
polygons = [r for r in results if r["points"]]
self.cut_polygons.extend(polygons)
else:
multiprocessing.set_executable(bpy.app.binary_path_python)
with multiprocessing.Pool(9) as p:
results = p.map(do_cut, process_data)
for result in results:
polygons = [p for p in result if p["points"]]
self.cut_polygons.extend(polygons)
def get_polygon_metadata(self, polygon, position):
polygon["metadata"] = {"classes": self.get_classes(self.get_ifc_element(polygon["global_id"]), position)}
return polygon
def get_ifc_element(self, global_id):
# TODO: make this less bad
element = None
for ifc_file in self.ifc_files.values():
try:
element = ifc_file.by_id(global_id)
return element
except:
pass
def get_classes(self, element, position):
classes = [position, element.is_a()]
material = ifcopenshell.util.element.get_material(element)
if material:
classes.append(
"material-{}".format(
re.sub("[^0-9a-zA-Z]+", "", self.get_material_name(material))
)
)
classes.append("globalid-{}".format(element.GlobalId))
for attribute in self.attributes:
result = self.selector.get_element_value(element, attribute)
if result:
classes.append(
"{}-{}".format(re.sub("[^0-9a-zA-Z]+", "", attribute), re.sub("[^0-9a-zA-Z]+", "", result))
)
return classes
def get_material_name(self, element):
if hasattr(element, "Name") and element.Name:
return element.Name
elif hasattr(element, "LayerSetName") and element.LayerSetName:
return element.LayerSetName
return "mat-" + str(element.id())
def get_pickled_cut_polygons(self):
if os.path.isfile(self.cut_pickle_file):
with open(self.cut_pickle_file, "rb") as pickle_file:
self.cut_polygons = pickle.load(pickle_file)
@@ -3,6 +3,19 @@
<div style="position:relative" class="gantt" id="GanttChartDIV"></div>
<script type="text/javascript">
var g = new JSGantt.GanttChart(document.getElementById('GanttChartDIV'), 'day');
g.setOptions({
vCaptionType: 'Complete', // Set to Show Caption : None,Caption,Resource,Duration,Complete,
vQuarterColWidth: 36,
vDateTaskDisplayFormat: 'day dd month yyyy', // Shown in tool tip box
vDayMajorDateDisplayFormat: 'mon yyyy - Week ww',// Set format to dates in the "Major" header of the "Day" view
vWeekMinorDateDisplayFormat: 'dd mon', // Set format to display dates in the "Minor" header of the "Week" view
vLang: 'en',
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
vFormatArr: ['Day', 'Week', 'Month', 'Quarter'], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
vTotalHeight: 1000,
});
var json_data = `
{{{json_data}}}
`;
@@ -1,6 +1,6 @@
* { stroke-linecap: round; }
.cut { fill: black; stroke: black; stroke-linecap: 'round'; stroke-width: 0.35; }
.background { fill: white; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
* { stroke-linecap: round; stroke-linejoin: round; }
*[id] { fill: black; stroke: black; stroke-linecap: 'round'; stroke-width: 0.35; }
.projection { fill: white; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
.annotation { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
.hidden { stroke-dasharray: 3, 2; }
.solid {}
+5 -14
View File
@@ -49,7 +49,6 @@ class IfcExporter:
json.dump(jsonData, outfile, indent=None if self.ifc_export_settings.json_compact else 4)
def set_header(self):
# TODO: add all metadata, pending bug #747
self.file.wrapped_data.header.file_name.name = os.path.basename(self.ifc_export_settings.output_file)
self.file.wrapped_data.header.file_name.time_stamp = (
datetime.datetime.utcnow()
@@ -62,16 +61,6 @@ class IfcExporter:
self.file.wrapped_data.header.file_name.originating_system = "{} {}".format(
self.get_application_name(), self.get_application_version()
)
# TODO: reimplement. See #1222.
# if self.owner_history:
# if self.schema_version == "IFC2X3":
# self.file.wrapped_data.header.file_name.authorization = self.owner_history.OwningUser.ThePerson.Id
# else:
# self.file.wrapped_data.header.file_name.authorization = (
# self.owner_history.OwningUser.ThePerson.Identification
# )
# else:
# self.file.wrapped_data.header.file_name.authorization = "Nobody"
def sync_object_placements_and_deletions(self):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file)
@@ -94,11 +83,13 @@ class IfcExporter:
ifcopenshell.api.run("root.remove_product", self.file, **{"product": product})
def sync_edited_objects(self):
for obj_name in IfcStore.edited_objs.copy():
obj = bpy.data.objects.get(obj_name)
for obj in IfcStore.edited_objs.copy():
if not obj:
continue
bpy.ops.bim.update_mesh_representation(obj=obj.name)
try:
bpy.ops.bim.update_representation(obj=obj.name)
except ReferenceError:
pass # The object is likely deleted
IfcStore.edited_objs.clear()
def sync_object_placement(self, obj):
+24 -15
View File
@@ -1,7 +1,6 @@
import bpy
import json
import addon_utils
import blenderbim.bim.decoration as decoration
import ifcopenshell.api.owner.settings
from bpy.app.handlers import persistent
from blenderbim.bim.ifc import IfcStore
@@ -9,22 +8,25 @@ from ifcopenshell.api.attribute.data import Data as AttributeData
from ifcopenshell.api.type.data import Data as TypeData
global_subscription_owner = object()
def mode_callback(obj, data):
for obj in bpy.context.selected_objects:
for obj in bpy.context.selected_objects + [bpy.context.active_object]:
if (
obj.mode != "EDIT"
or not obj.data
or not isinstance(obj.data, bpy.types.Mesh)
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
if obj.data.BIMMeshProperties.ifc_definition_id:
representation = IfcStore.get_file().by_id(obj.data.BIMMeshProperties.ifc_definition_id)
if representation.RepresentationType == "Tessellation" or representation.RepresentationType == "Brep":
IfcStore.edited_objs.add(obj.name)
if representation.RepresentationType in ["Tessellation", "Brep", "Annotation2D"]:
IfcStore.edited_objs.add(obj)
elif IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id).is_a("IfcGridAxis"):
IfcStore.edited_objs.add(obj.name)
IfcStore.edited_objs.add(obj)
def name_callback(obj, data):
@@ -53,6 +55,15 @@ def name_callback(obj, data):
AttributeData.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
def active_object_callback():
obj = bpy.context.active_object
for obj in bpy.context.selected_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
if IfcStore.id_map[obj.BIMObjectProperties.ifc_definition_id] != obj:
bpy.ops.bim.copy_class(obj=obj.name)
def subscribe_to(object, data_path, callback):
subscribe_to = object.path_resolve(data_path, False)
bpy.msgbus.subscribe_rna(
@@ -88,6 +99,8 @@ def purge_module_data():
def loadIfcStore(scene):
IfcStore.purge()
ifc_file = IfcStore.get_file()
if not ifc_file:
return
IfcStore.get_schema()
[
IfcStore.link_element(ifc_file.by_id(o.BIMObjectProperties.ifc_definition_id), o)
@@ -174,6 +187,11 @@ def create_application_organisation(ifc):
@persistent
def setDefaultProperties(scene):
global global_subscription_owner
active_object_key = bpy.types.LayerObjects, "active"
bpy.msgbus.subscribe_rna(
key=active_object_key, owner=global_subscription_owner, args=(), notify=active_object_callback
)
ifcopenshell.api.owner.settings.get_person = (
lambda ifc: ifc.by_id(int(bpy.context.scene.BIMOwnerProperties.user_person))
if bpy.context.scene.BIMOwnerProperties.user_person
@@ -252,12 +270,3 @@ def setDefaultProperties(scene):
drawing_style.name = "Blender Default"
drawing_style.render_type = "DEFAULT"
bpy.ops.bim.save_drawing_style(index="2")
@persistent
def toggleDecorationsOnLoad(*args):
toggle = bpy.context.scene.DocProperties.should_draw_decorations
if toggle:
decoration.DecorationsHandler.install(bpy.context)
else:
decoration.DecorationsHandler.uninstall()
-125
View File
@@ -73,128 +73,3 @@ def export_attributes(props, callback=None):
elif attribute.data_type == "enum":
attributes[attribute.name] = attribute.enum_value
return attributes
# TODO: migrate the below helper functions into the drawing module, since it is specific to that module
def parse_diagram_scale(camera):
"""Returns numeric value of scale"""
if camera.BIMCameraProperties.diagram_scale == "CUSTOM":
_, fraction = camera.BIMCameraProperties.custom_diagram_scale.split("|")
else:
_, fraction = camera.BIMCameraProperties.diagram_scale.split("|")
numerator, denominator = fraction.split("/")
return float(numerator) / float(denominator)
def get_project_collection(scene):
"""Get main project collection"""
colls = [c for c in scene.collection.children if c.name.startswith("IfcProject")]
if len(colls) != 1:
raise RuntimeError("project collection missing or not unique")
return colls[0]
def get_active_drawing(scene):
"""Get active drawing collection and camera"""
props = scene.DocProperties
if props.active_drawing_index is None or len(props.drawings) == 0:
return None, None
try:
drawing = props.drawings[props.active_drawing_index]
return scene.collection.children["Views"].children[f"IfcGroup/{drawing.name}"], drawing.camera
except (KeyError, IndexError):
raise RuntimeError("missing drawing collection")
def ortho_view_frame(camera, margin=0.015):
"""Calculates 2d bounding box of camera view area.
Similar to `bpy.types.Camera.view_frame`
:arg camera: camera of drawing
:type camera: bpy.types.Camera + BIMCameraProperties
:arg margin: margins, in scene units
:type margin: float
:return: (xmin, xmax, ymin, ymax, zmin, zmax) in local camera coordinates
"""
aspect = camera.BIMCameraProperties.raster_y / camera.BIMCameraProperties.raster_x
size = camera.ortho_scale
hwidth = size * 0.5
hheight = size * 0.5 * aspect
scale = parse_diagram_scale(camera)
xmarg = margin * scale
ymarg = margin * scale * aspect
return (-hwidth + xmarg, hwidth - xmarg, -hheight + ymarg, hheight - ymarg, -camera.clip_start, -camera.clip_end)
def almost_zero(v):
return abs(v) < 1e-5
def clip_segment(bounds, segm):
"""Clipping line segment to bounds
:arg bounds: (xmin, xmax, ymin, ymax)
:arg segm: 2 vertices of the segment
:return: 2 new vertices of segment or None if segment outside the bounding box
"""
# LiangBarsky algorithm
xmin, xmax, ymin, ymax, _, _ = bounds
p1, p2 = segm
def clip_side(p, q):
if almost_zero(p): # ~= 0, parallel to the side
if q < 0:
return None # outside
else:
return 0, 1 # inside
t = q / p # the intersection point
if p < 0: # entering
return t, 1
else: # leaving
return 0, t
dlt = p2 - p1
tt = (
clip_side(-dlt.x, p1.x - xmin), # left
clip_side(+dlt.x, xmax - p1.x), # right
clip_side(-dlt.y, p1.y - ymin), # bottom
clip_side(+dlt.y, ymax - p1.y), # top
)
if None in tt:
return None
t1 = max(0, max(t[0] for t in tt))
t2 = min(1, min(t[1] for t in tt))
if t1 >= t2:
return None
p1c = p1 + dlt * t1
p2c = p1 + dlt * t2
return p1c, p2c
def elevate_segment(bounds, segm):
"""Elevate line xy-perpendicular segment vertically
:arg bounds: (xmin, xmax, ymin, ymax)
:arg segm: 2 vertices of the segment
:return: 2 new vertices of segment or None if segment outside the bounding box
"""
_, _, ymin, ymax, zmin, _ = bounds
p1, p2 = segm
dlt = p2 - p1
if not (almost_zero(dlt.x) and almost_zero(dlt.y)):
return None
x = p1.x
return [Vector((x, ymin, zmin)), Vector((x, ymax, zmin))]
+20
View File
@@ -14,6 +14,7 @@ class IfcStore:
pset_template_file = None
library_path = ""
library_file = None
element_listeners = set()
@staticmethod
def purge():
@@ -47,6 +48,23 @@ class IfcStore:
IfcStore.schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name(IfcStore.file.schema)
return IfcStore.schema
@staticmethod
def get_element(id_or_guid):
if isinstance(id_or_guid, int):
map_object = IfcStore.id_map
else:
map_object = IfcStore.guid_map
try:
obj = map_object[id_or_guid]
obj.type # In case the object has been deleted, this triggers an exception
except:
return
return obj
@staticmethod
def add_element_listener(callback):
IfcStore.element_listeners.add(callback)
@staticmethod
def link_element(element, obj):
IfcStore.id_map[element.id()] = obj
@@ -55,6 +73,8 @@ class IfcStore:
obj.BIMObjectProperties.ifc_definition_id = element.id()
blenderbim.bim.handler.subscribe_to(obj, "mode", blenderbim.bim.handler.mode_callback)
blenderbim.bim.handler.subscribe_to(obj, "name", blenderbim.bim.handler.name_callback)
for listener in IfcStore.element_listeners:
listener(element, obj)
@staticmethod
def unlink_element(element=None, obj=None):
+7 -7
View File
@@ -18,12 +18,11 @@ import multiprocessing
import zipfile
import tempfile
import numpy as np
import blenderbim.bim.prop
from blenderbim.bim.module.drawing.prop import getDiagramScales
from pathlib import Path
from itertools import cycle
from datetime import datetime
from blenderbim.bim.ifc import IfcStore
from . import schema
class FileCopy(threading.Thread):
@@ -443,9 +442,9 @@ class IfcImporter:
def is_native_swept_disk_solid(self, representations):
for representation in representations:
if len(representation["raw"].Items) > 1 or not representation["raw"].Items[0].is_a("IfcSweptDiskSolid"):
return False
return True
if len(representation["raw"].Items) == 1 and representation["raw"].Items[0].is_a("IfcSweptDiskSolid"):
return True
return False
def is_native_faceted_brep(self, representations):
for representation in representations:
@@ -1218,7 +1217,8 @@ class IfcImporter:
if not view_collection:
view_collection = bpy.data.collections.new("Views")
bpy.context.scene.collection.children.link(view_collection)
drawing_collection = bpy.data.collections.new(obj.name)
group = [r for r in element.HasAssignments if r.is_a("IfcRelAssignsToGroup")][0].RelatingGroup
drawing_collection = bpy.data.collections.new("IfcGroup/" + group.Name)
view_collection.children.link(drawing_collection)
drawing_collection.objects.link(obj)
else:
@@ -1342,7 +1342,7 @@ class IfcImporter:
camera.BIMCameraProperties.target_view = pset["TargetView"]
if "Scale" in pset:
valid_scales = [
i[0] for i in blenderbim.bim.prop.getDiagramScales(None, None) if pset["Scale"] == i[0].split("|")[-1]
i[0] for i in getDiagramScales(None, None) if pset["Scale"] == i[0].split("|")[-1]
]
if valid_scales:
camera.BIMCameraProperties.diagram_scale = valid_scales[0]
@@ -45,7 +45,8 @@ class AssignObject(bpy.types.Operator):
self.remove_collection(collection, spatial_collection)
else:
for collection in related_object.users_collection:
collection.objects.unlink(related_object)
if collection.name.startswith("Ifc"):
collection.objects.unlink(related_object)
relating_collection.objects.link(related_object)
return {"FINISHED"}
@@ -1,5 +1,4 @@
import bpy
import blenderbim.bim.schema # refactor
from blenderbim.bim.ifc import IfcStore
from blenderbim.bim.prop import StrProperty, Attribute
from bpy.types import PropertyGroup
@@ -1,5 +1,5 @@
import bcf
import bcf.bcfxml
import bcf.v2.bcfxml
class BcfStore:
bcfxml = None
@@ -7,5 +7,5 @@ class BcfStore:
@staticmethod
def get_bcfxml():
if not BcfStore.bcfxml:
BcfStore.bcfxml = bcf.bcfxml.BcfXml()
BcfStore.bcfxml = bcf.v2.bcfxml.BcfXml()
return BcfStore.bcfxml
@@ -1,6 +1,8 @@
import os
import bpy
import bcf
import bcf.bcfxml
import bcf.v2.data
from . import bcfstore
from blenderbim.bim.ifc import IfcStore
from math import radians, degrees, atan, tan, cos, sin
@@ -26,9 +28,10 @@ class LoadBcfProject(bpy.types.Operator):
def execute(self, context):
bpy.context.scene.BCFProperties.is_loaded = False
bcfxml = bcfstore.BcfStore.get_bcfxml()
if self.filepath:
bcfxml.get_project(self.filepath)
bcfstore.BcfStore.bcfxml = bcf.bcfxml.load(self.filepath)
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.get_project()
bpy.context.scene.BCFProperties.name = bcfxml.project.name
bpy.ops.bim.load_bcf_topics()
bpy.context.scene.BCFProperties.is_loaded = True
@@ -250,7 +253,7 @@ class AddBcfBimSnippet(bpy.types.Operator):
props = bpy.context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bim_snippet = bcf.data.BimSnippet()
bim_snippet = bcf.v2.data.BimSnippet()
bim_snippet.reference = blender_topic.bim_snippet_reference
bim_snippet.reference_schema = blender_topic.bim_snippet_schema
bim_snippet.snippet_type = blender_topic.bim_snippet_type
@@ -270,7 +273,7 @@ class AddBcfRelatedTopic(bpy.types.Operator):
related_topic = None
for topic in bcfxml.topics.values():
if topic.title == blender_topic.related_topic:
related_topic = bcf.data.RelatedTopic()
related_topic = bcf.v2.data.RelatedTopic()
related_topic.guid = topic.guid
break
if not related_topic:
@@ -291,7 +294,7 @@ class AddBcfHeaderFile(bpy.types.Operator):
props = bpy.context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
header_file = bcf.data.HeaderFile()
header_file = bcf.v2.data.HeaderFile()
header_file.reference = blender_topic.file_reference
if not os.path.exists(header_file.reference):
header_file.filename = header_file.reference
@@ -327,14 +330,14 @@ class AddBcfViewpoint(bpy.types.Operator):
props = bpy.context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
viewpoint = bcf.data.Viewpoint()
viewpoint = bcf.v2.data.Viewpoint()
if bpy.context.scene.camera.data.type == "ORTHO":
camera = bcf.data.OrthogonalCamera()
camera = bcf.v2.data.OrthogonalCamera()
camera.view_to_world_scale = bpy.context.scene.camera.data.ortho_scale
viewpoint.orthogonal_camera = camera
elif bpy.context.scene.camera.data.type == "PERSP":
camera = bcf.data.PerspectiveCamera()
camera = bcf.v2.data.PerspectiveCamera()
camera.field_of_view = degrees(bpy.context.scene.camera.data.angle)
viewpoint.perspective_camera = camera
camera.camera_view_point.x = bpy.context.scene.camera.location.x
@@ -422,7 +425,7 @@ class AddBcfDocumentReference(bpy.types.Operator):
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.document_reference:
return {"FINISHED"}
document_reference = bcf.data.DocumentReference()
document_reference = bcf.v2.data.DocumentReference()
document_reference.referenced_document = blender_topic.document_reference
document_reference.description = blender_topic.document_reference_description or None
bcfxml.add_document_reference(topic, document_reference)
@@ -609,10 +612,10 @@ class AddBcfComment(bpy.types.Operator):
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.comment:
return {"FINISHED"}
comment = bcf.data.Comment()
comment = bcf.v2.data.Comment()
comment.comment = blender_topic.comment
if blender_topic.has_related_viewpoint and blender_topic.viewpoints:
comment.viewpoint = bcf.data.Viewpoint()
comment.viewpoint = bcf.v2.data.Viewpoint()
comment.viewpoint.guid = blender_topic.viewpoints
bcfxml.add_comment(topic, comment)
bpy.ops.bim.load_bcf_comments(topic_guid = topic.guid)
@@ -0,0 +1,14 @@
import bpy
from . import ui
classes = (
ui.BIM_PT_boundary,
)
def register():
pass
def unregister():
pass
@@ -0,0 +1,34 @@
import bpy
import blenderbim.bim.helper
from bpy.types import Panel, UIList
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.boundary.data import Data
class BIM_PT_boundary(Panel):
bl_label = "IFC Space Boundaries"
bl_idname = "BIM_PT_boundary"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
@classmethod
def poll(cls, context):
if not context.active_object:
return False
props = context.active_object.BIMObjectProperties
if not props.ifc_definition_id:
return False
if IfcStore.get_file().by_id(props.ifc_definition_id).is_a() not in ["IfcSpace", "IfcExternalSpatialElement"]:
return False
return True
def draw(self, context):
self.oprops = context.active_object.BIMObjectProperties
if not Data.is_loaded:
Data.load(IfcStore.get_file())
for boundary_id in Data.spaces.get(self.oprops.ifc_definition_id, []):
boundary = Data.boundaries[boundary_id]
row = self.layout.row()
row.label(text=f"{boundary_id}", icon="GHOST_ENABLED")
@@ -93,6 +93,7 @@ class BIM_PT_ifcclash(Panel):
class BIM_PT_clash_manager(Panel):
bl_idname = "BIM_PT_clash_manager"
bl_label = "Clash Manager"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
@@ -332,6 +332,7 @@ class EnableEditingCostItemValues(bpy.types.Operator):
props = context.scene.BIMCostProperties
props.active_cost_item_id = self.cost_item
props.cost_item_editing_type = "VALUES"
bpy.ops.bim.disable_editing_cost_item_value()
return {"FINISHED"}
@@ -1,17 +1,76 @@
import bpy
from . import ui, operator
from . import ui, prop, operator, handler, gizmos
classes = (
operator.AddDrawing,
operator.CreateDrawing,
operator.AddAnnotation,
operator.AddSheet,
operator.OpenSheet,
operator.AddDrawingToSheet,
operator.CreateSheets,
operator.OpenView,
operator.OpenViewCamera,
operator.ActivateView,
operator.SelectDocIfcFile,
operator.GenerateReferences,
operator.ResizeText,
operator.AddVariable,
operator.RemoveVariable,
operator.PropagateTextData,
operator.RemoveDrawing,
operator.AddDrawingStyle,
operator.RemoveDrawingStyle,
operator.SaveDrawingStyle,
operator.ActivateDrawingStyle,
operator.EditVectorStyle,
operator.RemoveSheet,
operator.AddSchedule,
operator.RemoveSchedule,
operator.SelectScheduleFile,
operator.BuildSchedule,
operator.AddScheduleToSheet,
operator.AddDrawingStyleAttribute,
operator.RemoveDrawingStyleAttribute,
operator.RefreshDrawingList,
operator.CleanWireframes,
operator.CopyGrid,
operator.AddSectionsAnnotations,
prop.Variable,
prop.Drawing,
prop.Schedule,
prop.DrawingStyle,
prop.Sheet,
prop.DocProperties,
prop.BIMCameraProperties,
prop.BIMTextProperties,
ui.BIM_PT_camera,
ui.BIM_PT_drawing_underlay,
ui.BIM_PT_drawings,
ui.BIM_PT_schedules,
ui.BIM_PT_sheets,
ui.BIM_PT_text,
ui.BIM_PT_annotation_utilities,
ui.BIM_UL_drawinglist,
gizmos.UglyDotGizmo,
gizmos.DotGizmo,
gizmos.DimensionLabelGizmo,
gizmos.ExtrusionGuidesGizmo,
gizmos.ExtrusionWidget,
)
def register():
pass
bpy.types.Scene.DocProperties = bpy.props.PointerProperty(type=prop.DocProperties)
bpy.types.Camera.BIMCameraProperties = bpy.props.PointerProperty(type=prop.BIMCameraProperties)
bpy.types.TextCurve.BIMTextProperties = bpy.props.PointerProperty(type=prop.BIMTextProperties)
bpy.app.handlers.load_post.append(handler.toggleDecorationsOnLoad)
bpy.app.handlers.depsgraph_update_pre.append(handler.depsgraph_update_pre_handler)
def unregister():
pass
del bpy.types.Scene.DocProperties
del bpy.types.Camera.BIMCameraProperties
del bpy.types.TextCurve.BIMTextProperties
bpy.app.handlers.load_post.remove(handler.toggleDecorationsOnLoad)
bpy.app.handlers.depsgraph_update_pre.remove(handler.depsgraph_update_pre_handler)
@@ -17,9 +17,9 @@ class Annotator:
@staticmethod
def add_text(related_element=None):
curve = bpy.data.curves.new(type="FONT", name="Plan/Annotation/PLAN_VIEW/Text")
curve = bpy.data.curves.new(type="FONT", name="Text")
curve.body = "TEXT"
obj = bpy.data.objects.new("IfcAnnotation/Text", curve)
obj = bpy.data.objects.new("Text", curve)
obj.matrix_world = bpy.context.scene.camera.matrix_world
if related_element is None:
location, _, _, _ = Annotator.get_placeholder_coords()
@@ -138,12 +138,12 @@ class Annotator:
if name in obj.name:
return obj
if data_type == "mesh":
data = bpy.data.meshes.new("Plan/Annotation/PLAN_VIEW/" + name)
data = bpy.data.meshes.new(name)
elif data_type == "curve":
data = bpy.data.curves.new("Plan/Annotation/PLAN_VIEW/" + name, type="CURVE")
data = bpy.data.curves.new(name, type="CURVE")
data.dimensions = "3D"
data.resolution_u = 2
obj = bpy.data.objects.new("IfcAnnotation/" + name, data)
obj = bpy.data.objects.new(name, data)
collection.objects.link(obj)
return obj
@@ -164,4 +164,4 @@ class Annotator:
return (camera.location + z_offset,
camera.location + z_offset + y_offset,
camera.location + z_offset + x_offset,
camera.location + z_offset + x_offset + y_offset)
camera.location + z_offset + x_offset + y_offset)
@@ -13,7 +13,7 @@ import gpu
import bgl
from gpu.types import GPUShader, GPUBatch, GPUIndexBuf, GPUVertBuf, GPUVertFormat
from gpu_extras.batch import batch_for_shader
from . import helper
import blenderbim.bim.module.drawing.helper as helper
class BaseDecorator():
@@ -1,14 +1,12 @@
import bpy
import blf
from bpy import types
import math
import gpu, bgl
from bpy import types
from mathutils import Vector, Matrix
from mathutils import geometry
import gpu, bgl
from bpy_extras import view3d_utils
from .shaders import DotsGizmoShader, ExtrusionGuidesShader, BaseLinesShader
from blenderbim.bim.module.drawing.shaders import DotsGizmoShader, ExtrusionGuidesShader, BaseLinesShader
"""Gizmos under the hood
@@ -43,76 +41,196 @@ draw_select -- fake-draw of selection geometry for gpu-side cursor tracking
# some geometries for Gizmo.custom_shape shaders
CUBE = (
(+1, +1, +1), (-1, +1, +1), (+1, -1, +1), # top
(+1, -1, +1), (-1, +1, +1), (-1, -1, +1),
(+1, +1, +1), (+1, -1, +1), (+1, +1, -1), # right
(+1, +1, -1), (+1, -1, +1), (+1, -1, -1),
(+1, +1, +1), (+1, +1, -1), (-1, +1, +1), # back
(-1, +1, +1), (+1, +1, -1), (-1, +1, -1),
(-1, -1, -1), (-1, +1, -1), (+1, -1, -1), # bot
(+1, -1, -1), (-1, +1, -1), (+1, +1, -1),
(-1, -1, -1), (-1, -1, +1), (-1, +1, -1), # left
(-1, +1, -1), (-1, -1, +1), (-1, +1, +1),
(-1, -1, -1), (+1, -1, -1), (-1, -1, +1), # front
(-1, -1, +1), (+1, -1, -1), (+1, -1, +1)
(+1, +1, +1),
(-1, +1, +1),
(+1, -1, +1), # top
(+1, -1, +1),
(-1, +1, +1),
(-1, -1, +1),
(+1, +1, +1),
(+1, -1, +1),
(+1, +1, -1), # right
(+1, +1, -1),
(+1, -1, +1),
(+1, -1, -1),
(+1, +1, +1),
(+1, +1, -1),
(-1, +1, +1), # back
(-1, +1, +1),
(+1, +1, -1),
(-1, +1, -1),
(-1, -1, -1),
(-1, +1, -1),
(+1, -1, -1), # bot
(+1, -1, -1),
(-1, +1, -1),
(+1, +1, -1),
(-1, -1, -1),
(-1, -1, +1),
(-1, +1, -1), # left
(-1, +1, -1),
(-1, -1, +1),
(-1, +1, +1),
(-1, -1, -1),
(+1, -1, -1),
(-1, -1, +1), # front
(-1, -1, +1),
(+1, -1, -1),
(+1, -1, +1),
)
DISC = (
(0.0, 0.0, 0.0), (1.0, 0.0, 0), (0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0), (0.8660254037844387, 0.49999999999999994, 0), (0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0), (0.5000000000000001, 0.8660254037844386, 0), (6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0), (6.123233995736766e-17, 1.0, 0), (-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0), (-0.4999999999999998, 0.8660254037844387, 0), (-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0), (-0.8660254037844385, 0.5000000000000003, 0), (-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0), (-1.0, 1.2246467991473532e-16, 0), (-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0), (-0.8660254037844388, -0.4999999999999997, 0), (-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0), (-0.5000000000000004, -0.8660254037844384, 0), (-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0), (-1.8369701987210297e-16, -1.0, 0), (0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0), (0.49999999999999933, -0.866025403784439, 0), (0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0), (0.8660254037844384, -0.5000000000000004, 0), (1.0, 0.0, 0),
(0.0, 0.0, 0.0),
(1.0, 0.0, 0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0),
(0.5000000000000001, 0.8660254037844386, 0),
(6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0),
(6.123233995736766e-17, 1.0, 0),
(-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0),
(-0.4999999999999998, 0.8660254037844387, 0),
(-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844385, 0.5000000000000003, 0),
(-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0),
(-1.0, 1.2246467991473532e-16, 0),
(-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844388, -0.4999999999999997, 0),
(-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0),
(-0.5000000000000004, -0.8660254037844384, 0),
(-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0),
(-1.8369701987210297e-16, -1.0, 0),
(0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0),
(0.49999999999999933, -0.866025403784439, 0),
(0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0),
(0.8660254037844384, -0.5000000000000004, 0),
(1.0, 0.0, 0),
)
X3DISC = (
(0.0, 0.0, 0.0), (1.0, 0.0, 0), (0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0), (0.8660254037844387, 0.49999999999999994, 0), (0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0), (0.5000000000000001, 0.8660254037844386, 0), (6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0), (6.123233995736766e-17, 1.0, 0), (-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0), (-0.4999999999999998, 0.8660254037844387, 0), (-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0), (-0.8660254037844385, 0.5000000000000003, 0), (-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0), (-1.0, 1.2246467991473532e-16, 0), (-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0), (-0.8660254037844388, -0.4999999999999997, 0), (-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0), (-0.5000000000000004, -0.8660254037844384, 0), (-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0), (-1.8369701987210297e-16, -1.0, 0), (0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0), (0.49999999999999933, -0.866025403784439, 0), (0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0), (0.8660254037844384, -0.5000000000000004, 0), (1.0, 0.0, 0),
(0.0, 0.0, 0.0), (0, 1.0, 0.0), (0, 0.8660254037844387, 0.49999999999999994),
(0.0, 0.0, 0.0), (0, 0.8660254037844387, 0.49999999999999994), (0, 0.5000000000000001, 0.8660254037844386),
(0.0, 0.0, 0.0), (0, 0.5000000000000001, 0.8660254037844386), (0, 6.123233995736766e-17, 1.0),
(0.0, 0.0, 0.0), (0, 6.123233995736766e-17, 1.0), (0, -0.4999999999999998, 0.8660254037844387),
(0.0, 0.0, 0.0), (0, -0.4999999999999998, 0.8660254037844387), (0, -0.8660254037844385, 0.5000000000000003),
(0.0, 0.0, 0.0), (0, -0.8660254037844385, 0.5000000000000003), (0, -1.0, 1.2246467991473532e-16),
(0.0, 0.0, 0.0), (0, -1.0, 1.2246467991473532e-16), (0, -0.8660254037844388, -0.4999999999999997),
(0.0, 0.0, 0.0), (0, -0.8660254037844388, -0.4999999999999997), (0, -0.5000000000000004, -0.8660254037844384),
(0.0, 0.0, 0.0), (0, -0.5000000000000004, -0.8660254037844384), (0, -1.8369701987210297e-16, -1.0),
(0.0, 0.0, 0.0), (0, -1.8369701987210297e-16, -1.0), (0, 0.49999999999999933, -0.866025403784439),
(0.0, 0.0, 0.0), (0, 0.49999999999999933, -0.866025403784439), (0, 0.8660254037844384, -0.5000000000000004),
(0.0, 0.0, 0.0), (0, 0.8660254037844384, -0.5000000000000004), (0, 1.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0, 1.0), (0.49999999999999994, 0, 0.8660254037844387),
(0.0, 0.0, 0.0), (0.49999999999999994, 0, 0.8660254037844387), (0.8660254037844386, 0, 0.5000000000000001),
(0.0, 0.0, 0.0), (0.8660254037844386, 0, 0.5000000000000001), (1.0, 0, 6.123233995736766e-17),
(0.0, 0.0, 0.0), (1.0, 0, 6.123233995736766e-17), (0.8660254037844387, 0, -0.4999999999999998),
(0.0, 0.0, 0.0), (0.8660254037844387, 0, -0.4999999999999998), (0.5000000000000003, 0, -0.8660254037844385),
(0.0, 0.0, 0.0), (0.5000000000000003, 0, -0.8660254037844385), (1.2246467991473532e-16, 0, -1.0),
(0.0, 0.0, 0.0), (1.2246467991473532e-16, 0, -1.0), (-0.4999999999999997, 0, -0.8660254037844388),
(0.0, 0.0, 0.0), (-0.4999999999999997, 0, -0.8660254037844388), (-0.8660254037844384, 0, -0.5000000000000004),
(0.0, 0.0, 0.0), (-0.8660254037844384, 0, -0.5000000000000004), (-1.0, 0, -1.8369701987210297e-16),
(0.0, 0.0, 0.0), (-1.0, 0, -1.8369701987210297e-16), (-0.866025403784439, 0, 0.49999999999999933),
(0.0, 0.0, 0.0), (-0.866025403784439, 0, 0.49999999999999933), (-0.5000000000000004, 0, 0.8660254037844384),
(0.0, 0.0, 0.0), (-0.5000000000000004, 0, 0.8660254037844384), (0.0, 0, 1.0),
(0.0, 0.0, 0.0),
(1.0, 0.0, 0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0),
(0.5000000000000001, 0.8660254037844386, 0),
(6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0),
(6.123233995736766e-17, 1.0, 0),
(-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0),
(-0.4999999999999998, 0.8660254037844387, 0),
(-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844385, 0.5000000000000003, 0),
(-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0),
(-1.0, 1.2246467991473532e-16, 0),
(-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844388, -0.4999999999999997, 0),
(-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0),
(-0.5000000000000004, -0.8660254037844384, 0),
(-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0),
(-1.8369701987210297e-16, -1.0, 0),
(0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0),
(0.49999999999999933, -0.866025403784439, 0),
(0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0),
(0.8660254037844384, -0.5000000000000004, 0),
(1.0, 0.0, 0),
(0.0, 0.0, 0.0),
(0, 1.0, 0.0),
(0, 0.8660254037844387, 0.49999999999999994),
(0.0, 0.0, 0.0),
(0, 0.8660254037844387, 0.49999999999999994),
(0, 0.5000000000000001, 0.8660254037844386),
(0.0, 0.0, 0.0),
(0, 0.5000000000000001, 0.8660254037844386),
(0, 6.123233995736766e-17, 1.0),
(0.0, 0.0, 0.0),
(0, 6.123233995736766e-17, 1.0),
(0, -0.4999999999999998, 0.8660254037844387),
(0.0, 0.0, 0.0),
(0, -0.4999999999999998, 0.8660254037844387),
(0, -0.8660254037844385, 0.5000000000000003),
(0.0, 0.0, 0.0),
(0, -0.8660254037844385, 0.5000000000000003),
(0, -1.0, 1.2246467991473532e-16),
(0.0, 0.0, 0.0),
(0, -1.0, 1.2246467991473532e-16),
(0, -0.8660254037844388, -0.4999999999999997),
(0.0, 0.0, 0.0),
(0, -0.8660254037844388, -0.4999999999999997),
(0, -0.5000000000000004, -0.8660254037844384),
(0.0, 0.0, 0.0),
(0, -0.5000000000000004, -0.8660254037844384),
(0, -1.8369701987210297e-16, -1.0),
(0.0, 0.0, 0.0),
(0, -1.8369701987210297e-16, -1.0),
(0, 0.49999999999999933, -0.866025403784439),
(0.0, 0.0, 0.0),
(0, 0.49999999999999933, -0.866025403784439),
(0, 0.8660254037844384, -0.5000000000000004),
(0.0, 0.0, 0.0),
(0, 0.8660254037844384, -0.5000000000000004),
(0, 1.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0, 1.0),
(0.49999999999999994, 0, 0.8660254037844387),
(0.0, 0.0, 0.0),
(0.49999999999999994, 0, 0.8660254037844387),
(0.8660254037844386, 0, 0.5000000000000001),
(0.0, 0.0, 0.0),
(0.8660254037844386, 0, 0.5000000000000001),
(1.0, 0, 6.123233995736766e-17),
(0.0, 0.0, 0.0),
(1.0, 0, 6.123233995736766e-17),
(0.8660254037844387, 0, -0.4999999999999998),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0, -0.4999999999999998),
(0.5000000000000003, 0, -0.8660254037844385),
(0.0, 0.0, 0.0),
(0.5000000000000003, 0, -0.8660254037844385),
(1.2246467991473532e-16, 0, -1.0),
(0.0, 0.0, 0.0),
(1.2246467991473532e-16, 0, -1.0),
(-0.4999999999999997, 0, -0.8660254037844388),
(0.0, 0.0, 0.0),
(-0.4999999999999997, 0, -0.8660254037844388),
(-0.8660254037844384, 0, -0.5000000000000004),
(0.0, 0.0, 0.0),
(-0.8660254037844384, 0, -0.5000000000000004),
(-1.0, 0, -1.8369701987210297e-16),
(0.0, 0.0, 0.0),
(-1.0, 0, -1.8369701987210297e-16),
(-0.866025403784439, 0, 0.49999999999999933),
(0.0, 0.0, 0.0),
(-0.866025403784439, 0, 0.49999999999999933),
(-0.5000000000000004, 0, 0.8660254037844384),
(0.0, 0.0, 0.0),
(-0.5000000000000004, 0, 0.8660254037844384),
(0.0, 0, 1.0),
)
class CustomGizmo():
class CustomGizmo:
# FIXME: highliting/selection doesnt work
def draw_very_custom_shape(self, ctx, custom_shape, select_id=None):
# similar to draw_custom_shape
@@ -127,7 +245,7 @@ class CustomGizmo():
color = (*self.color_highlight, self.alpha_highlight)
else:
color = (*self.color, self.alpha)
shader.uniform_float('color', color)
shader.uniform_float("color", color)
shape.glenable()
shape.uniform_region(ctx)
@@ -139,31 +257,32 @@ class CustomGizmo():
bgl.glDisable(bgl.GL_BLEND)
class OffsetHandle():
class OffsetHandle:
"""Handling mouse to offset gizmo from base along Z axis"""
# FIXME: works a bit weird for rotated objects
def invoke(self, ctx, event):
self.init_value = self.target_get_value('offset') / self.scale_value
self.init_value = self.target_get_value("offset") / self.scale_value
coordz = self.project_mouse(ctx, event)
if coordz is None:
return {'CANCELLED'}
return {"CANCELLED"}
self.init_coordz = coordz
return {'RUNNING_MODAL'}
return {"RUNNING_MODAL"}
def modal(self, ctx, event, tweak):
coordz = self.project_mouse(ctx, event)
if coordz is None:
return {'CANCELLED'}
return {"CANCELLED"}
delta = coordz - self.init_coordz
if 'PRECISE' in tweak:
if "PRECISE" in tweak:
delta /= 10.0
value = max(0, self.init_value + delta)
value *= self.scale_value
# ctx.area.header_text_set(f"coords: {self.init_coordz} - {coordz}, delta: {delta}, value: {value}")
ctx.area.header_text_set(f"Depth: {value}")
self.target_set_value('offset', value)
return {'RUNNING_MODAL'}
self.target_set_value("offset", value)
return {"RUNNING_MODAL"}
def project_mouse(self, ctx, event):
"""Projecting mouse coords to local axis Z"""
@@ -189,30 +308,29 @@ class OffsetHandle():
def exit(self, ctx, cancel):
if cancel:
self.target_set_value('offset', self.init_value)
self.target_set_value("offset", self.init_value)
else:
self.group.update(ctx)
class UglyDotGizmo(OffsetHandle, types.Gizmo):
"""three orthogonal circles"""
bl_idname = "BIM_GT_uglydot_3d"
bl_target_properties = (
{'id': 'offset', 'type': 'FLOAT', 'array_length': 1},
)
bl_target_properties = ({"id": "offset", "type": "FLOAT", "array_length": 1},)
__slots__ = (
'scale_value',
'custom_shape',
'init_value',
'init_coordz',
"scale_value",
"custom_shape",
"init_value",
"init_coordz",
)
def setup(self):
self.custom_shape = self.new_custom_shape(type='TRIS', verts=X3DISC)
self.custom_shape = self.new_custom_shape(type="TRIS", verts=X3DISC)
def refresh(self):
offset = self.target_get_value('offset') / self.scale_value
offset = self.target_get_value("offset") / self.scale_value
self.matrix_offset.col[3][2] = offset # z-shift
def draw(self, ctx):
@@ -226,15 +344,14 @@ class UglyDotGizmo(OffsetHandle, types.Gizmo):
class DotGizmo(CustomGizmo, OffsetHandle, types.Gizmo):
"""Single dot viewport-aligned"""
# FIXME: make it selectable
bl_idname = "BIM_GT_dot_2d"
bl_target_properties = (
{'id': 'offset', 'type': 'FLOAT', 'array_length': 1},
)
bl_target_properties = ({"id": "offset", "type": "FLOAT", "array_length": 1},)
__slots__ = (
'scale_value',
'custom_shape',
"scale_value",
"custom_shape",
)
def setup(self):
@@ -243,7 +360,7 @@ class DotGizmo(CustomGizmo, OffsetHandle, types.Gizmo):
self.use_draw_scale = False
def refresh(self):
offset = self.target_get_value('offset') / self.scale_value
offset = self.target_get_value("offset") / self.scale_value
self.matrix_offset.col[3][2] = offset # z-shifted
def draw(self, ctx):
@@ -265,15 +382,11 @@ class ExtrusionGuidesGizmo(CustomGizmo, types.Gizmo):
Noninteractive gizmo to indicate extrusion depth and planes.
Draws main segment and orthogonal cross at endpoints.
"""
bl_idname = "BIM_GT_extrusion_guides"
bl_target_properties = (
{'id': 'depth', 'type': 'FLOAT', 'array_length': 1},
)
__slots__ = (
'scale_value',
'custom_shape'
)
bl_idname = "BIM_GT_extrusion_guides"
bl_target_properties = ({"id": "depth", "type": "FLOAT", "array_length": 1},)
__slots__ = ("scale_value", "custom_shape")
def setup(self):
shader = ExtrusionGuidesShader()
@@ -281,7 +394,7 @@ class ExtrusionGuidesGizmo(CustomGizmo, types.Gizmo):
self.use_draw_scale = False
def refresh(self):
depth = self.target_get_value('depth') / self.scale_value
depth = self.target_get_value("depth") / self.scale_value
self.matrix_offset.col[2][2] = depth # z-scaled
def draw(self, ctx):
@@ -291,25 +404,22 @@ class ExtrusionGuidesGizmo(CustomGizmo, types.Gizmo):
class DimensionLabelGizmo(types.Gizmo):
"""Text label for a dimension"""
# does not work properly, fonts are totally screwed up
bl_idname = "BIM_GT_dimension_label"
bl_target_properties = (
{'id': 'value', 'type': 'FLOAT', 'array_length': 1},
)
bl_target_properties = ({"id": "value", "type": "FLOAT", "array_length": 1},)
__slots__ = (
'text_label'
)
__slots__ = "text_label"
def setup(self):
pass
def refresh(self, ctx):
value = self.target_get_value('value')
self.matrix_offset.col[3][2] = value * .5
value = self.target_get_value("value")
self.matrix_offset.col[3][2] = value * 0.5
unit_system = ctx.scene.unit_settings.system
self.text_label = bpy.utils.units.to_string(unit_system, 'LENGTH', value, 3, split_unit=False)
self.text_label = bpy.utils.units.to_string(unit_system, "LENGTH", value, 3, split_unit=False)
def draw(self, ctx):
self.refresh(ctx)
@@ -337,41 +447,44 @@ class DimensionLabelGizmo(types.Gizmo):
class ExtrusionWidget(types.GizmoGroup):
bl_idname = "bim.extrusion_widget"
bl_label = "Extrusion Gizmos"
bl_space_type = 'VIEW_3D'
bl_region_type = 'WINDOW'
bl_options = {'3D', 'PERSISTENT', 'SHOW_MODAL_ALL'}
bl_space_type = "VIEW_3D"
bl_region_type = "WINDOW"
bl_options = {"3D", "PERSISTENT", "SHOW_MODAL_ALL"}
# FIXME: use proper scale from ifc value to blender units
@classmethod
def poll(cls, ctx):
obj = ctx.object
return (obj and obj.type == 'MESH'
and obj.data.BIMMeshProperties.ifc_parameters.get('IfcExtrudedAreaSolid/Depth') is not None)
return (
obj
and obj.type == "MESH"
and obj.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth") is not None
)
def setup(self, ctx):
target = ctx.object
prop = target.data.BIMMeshProperties.ifc_parameters.get('IfcExtrudedAreaSolid/Depth')
prop = target.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth")
basis = target.matrix_world.normalized()
theme = ctx.preferences.themes[0].user_interface
gz = self.handle = self.gizmos.new('BIM_GT_uglydot_3d')
gz = self.handle = self.gizmos.new("BIM_GT_uglydot_3d")
gz.matrix_basis = basis
gz.scale_basis = 0.1
gz.color = gz.color_highlight = tuple(theme.gizmo_primary)
gz.alpha = 0.5
gz.alpha_highlight = 1.0
gz.use_draw_modal = True
gz.target_set_prop('offset', prop, 'value')
gz.target_set_prop("offset", prop, "value")
gz.scale_value = 1000
gz = self.guides = self.gizmos.new('BIM_GT_extrusion_guides')
gz = self.guides = self.gizmos.new("BIM_GT_extrusion_guides")
gz.matrix_basis = basis
gz.color = gz.color_highlight = tuple(theme.gizmo_secondary)
gz.alpha = gz.alpha_highlight = 0.5
gz.use_draw_modal = True
gz.target_set_prop('depth', prop, 'value')
gz.target_set_prop("depth", prop, "value")
gz.scale_value = 1000
# gz = self.label = self.gizmos.new('GIZMO_GT_dimension_label')
@@ -395,6 +508,6 @@ class ExtrusionWidget(types.GizmoGroup):
# need to retrieve and rebind them again
bpy.ops.bim.get_representation_ifc_parameters()
target = ctx.object
prop = target.data.BIMMeshProperties.ifc_parameters.get('IfcExtrudedAreaSolid/Depth')
self.handle.target_set_prop('offset', prop, 'value')
self.guides.target_set_prop('depth', prop, 'value')
prop = target.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth")
self.handle.target_set_prop("offset", prop, "value")
self.guides.target_set_prop("depth", prop, "value")
@@ -0,0 +1,32 @@
import bpy
import blenderbim.bim.module.drawing.decoration as decoration
from bpy.app.handlers import persistent
@persistent
def toggleDecorationsOnLoad(*args):
toggle = bpy.context.scene.DocProperties.should_draw_decorations
if toggle:
decoration.DecorationsHandler.install(bpy.context)
else:
decoration.DecorationsHandler.uninstall()
@persistent
def depsgraph_update_pre_handler(scene):
set_active_camera_resolution(scene)
def set_active_camera_resolution(scene):
if not scene.camera or "/" not in scene.camera.name or not scene.DocProperties.drawings:
return
if (
scene.render.resolution_x != scene.camera.data.BIMCameraProperties.raster_x
or scene.render.resolution_y != scene.camera.data.BIMCameraProperties.raster_y
):
scene.render.resolution_x = scene.camera.data.BIMCameraProperties.raster_x
scene.render.resolution_y = scene.camera.data.BIMCameraProperties.raster_y
current_drawing = scene.DocProperties.drawings[scene.DocProperties.current_drawing_index]
if scene.camera != current_drawing.camera:
scene.DocProperties.current_drawing_index = scene.DocProperties.drawings.find(scene.camera.name.split("/")[1])
bpy.ops.bim.activate_view(drawing_index=scene.DocProperties.current_drawing_index)
@@ -1,5 +1,102 @@
import bpy
import math
import mathutils.geometry
from mathutils import Vector
# Code taken and updated from https://blenderartists.org/t/detecting-intersection-of-bounding-boxes/457520/2
class BoundingEdge:
def __init__(self, v0, v1):
self.vertex = (v0, v1)
self.vector = v1 - v0
class BoundingFace:
def __init__(self, v0, v1, v2):
self.vertex = (v0, v1, v2)
self.normal = mathutils.geometry.normal(v0, v1, v2)
class BoundingBox:
def __init__(self, ob, vertex=None):
self.vertex = vertex or [ob.matrix_world @ Vector(v) for v in ob.bound_box]
if self.vertex != None:
self.edge = [
BoundingEdge(self.vertex[0], self.vertex[1]),
BoundingEdge(self.vertex[1], self.vertex[2]),
BoundingEdge(self.vertex[2], self.vertex[3]),
BoundingEdge(self.vertex[3], self.vertex[0]),
BoundingEdge(self.vertex[4], self.vertex[5]),
BoundingEdge(self.vertex[5], self.vertex[6]),
BoundingEdge(self.vertex[6], self.vertex[7]),
BoundingEdge(self.vertex[7], self.vertex[4]),
BoundingEdge(self.vertex[0], self.vertex[4]),
BoundingEdge(self.vertex[1], self.vertex[5]),
BoundingEdge(self.vertex[2], self.vertex[6]),
BoundingEdge(self.vertex[3], self.vertex[7]),
]
self.face = [
BoundingFace(self.vertex[0], self.vertex[1], self.vertex[3]),
BoundingFace(self.vertex[0], self.vertex[4], self.vertex[1]),
BoundingFace(self.vertex[0], self.vertex[3], self.vertex[4]),
BoundingFace(self.vertex[6], self.vertex[5], self.vertex[7]),
BoundingFace(self.vertex[6], self.vertex[7], self.vertex[2]),
BoundingFace(self.vertex[6], self.vertex[2], self.vertex[5]),
]
def whichSide(self, vtxs, normal, faceVtx):
retVal = 0
positive = 0
negative = 0
for v in vtxs:
t = normal.dot(v - faceVtx)
if t > 0:
positive = positive + 1
elif t < 0:
negative = negative + 1
if positive != 0 and negative != 0:
return 0
if positive != 0:
retVal = 1
else:
retVal = -1
return retVal
# Taken from: http://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf
def intersect(self, bb):
retVal = False
if self.vertex != None and bb.vertex != None:
# check all the faces of this object for a seperation axis
for i, f in enumerate(self.face):
d = f.normal
if self.whichSide(bb.vertex, d, f.vertex[0]) > 0:
return False # all the vertexes are on the +ve side of the face
# now do it again for the other objects faces
for i, f in enumerate(bb.face):
d = f.normal
if self.whichSide(self.vertex, d, f.vertex[0]) > 0:
return False # all the vertexes are on the +ve side of the face
# do edge checks
for e1 in self.edge:
for e2 in bb.edge:
d = e1.vector.cross(e2.vector)
side0 = self.whichSide(self.vertex, d, e1.vertex[0])
if side0 == 0:
continue
side1 = self.whichSide(bb.vertex, d, e1.vertex[0])
if side1 == 0:
continue
if (side0 * side1) < 0:
return False
retVal = True
return retVal
# This function stolen from https://github.com/kevancress/MeasureIt_ARCH/blob/dcf607ce0896aa2284463c6b4ae9cd023fc54cbe/measureit_arch_baseclass.py
@@ -139,3 +236,125 @@ def format_distance(value, isArea=False, hide_units=True):
tx_dist = fmt % value
return tx_dist
def get_active_drawing(scene):
"""Get active drawing collection and camera"""
props = scene.DocProperties
if props.active_drawing_index is None or len(props.drawings) == 0:
return None, None
try:
drawing = props.drawings[props.active_drawing_index]
return scene.collection.children["Views"].children[f"IfcGroup/{drawing.name}"], drawing.camera
except (KeyError, IndexError):
raise RuntimeError("missing drawing collection")
def get_project_collection(scene):
"""Get main project collection"""
colls = [c for c in scene.collection.children if c.name.startswith("IfcProject")]
if len(colls) != 1:
raise RuntimeError("project collection missing or not unique")
return colls[0]
def parse_diagram_scale(camera):
"""Returns numeric value of scale"""
if camera.BIMCameraProperties.diagram_scale == "CUSTOM":
_, fraction = camera.BIMCameraProperties.custom_diagram_scale.split("|")
else:
_, fraction = camera.BIMCameraProperties.diagram_scale.split("|")
numerator, denominator = fraction.split("/")
return float(numerator) / float(denominator)
def ortho_view_frame(camera, margin=0.015):
"""Calculates 2d bounding box of camera view area.
Similar to `bpy.types.Camera.view_frame`
:arg camera: camera of drawing
:type camera: bpy.types.Camera + BIMCameraProperties
:arg margin: margins, in scene units
:type margin: float
:return: (xmin, xmax, ymin, ymax, zmin, zmax) in local camera coordinates
"""
aspect = camera.BIMCameraProperties.raster_y / camera.BIMCameraProperties.raster_x
size = camera.ortho_scale
hwidth = size * 0.5
hheight = size * 0.5 * aspect
scale = parse_diagram_scale(camera)
xmarg = margin * scale
ymarg = margin * scale * aspect
return (-hwidth + xmarg, hwidth - xmarg, -hheight + ymarg, hheight - ymarg, -camera.clip_start, -camera.clip_end)
def almost_zero(v):
return abs(v) < 1e-5
def clip_segment(bounds, segm):
"""Clipping line segment to bounds
:arg bounds: (xmin, xmax, ymin, ymax)
:arg segm: 2 vertices of the segment
:return: 2 new vertices of segment or None if segment outside the bounding box
"""
# LiangBarsky algorithm
xmin, xmax, ymin, ymax, _, _ = bounds
p1, p2 = segm
def clip_side(p, q):
if almost_zero(p): # ~= 0, parallel to the side
if q < 0:
return None # outside
else:
return 0, 1 # inside
t = q / p # the intersection point
if p < 0: # entering
return t, 1
else: # leaving
return 0, t
dlt = p2 - p1
tt = (
clip_side(-dlt.x, p1.x - xmin), # left
clip_side(+dlt.x, xmax - p1.x), # right
clip_side(-dlt.y, p1.y - ymin), # bottom
clip_side(+dlt.y, ymax - p1.y), # top
)
if None in tt:
return None
t1 = max(0, max(t[0] for t in tt))
t2 = min(1, min(t[1] for t in tt))
if t1 >= t2:
return None
p1c = p1 + dlt * t1
p2c = p1 + dlt * t2
return p1c, p2c
def elevate_segment(bounds, segm):
"""Elevate line xy-perpendicular segment vertically
:arg bounds: (xmin, xmax, ymin, ymax)
:arg segm: 2 vertices of the segment
:return: 2 new vertices of segment or None if segment outside the bounding box
"""
_, _, ymin, ymax, zmin, _ = bounds
p1, p2 = segm
dlt = p2 - p1
if not (almost_zero(dlt.x) and almost_zero(dlt.y)):
return None
x = p1.x
return [Vector((x, ymin, zmin)), Vector((x, ymax, zmin))]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,282 @@
import os
import bpy
import blenderbim.bim.module.drawing.annotation as annotation
import blenderbim.bim.module.drawing.decoration as decoration
from pathlib import Path
from blenderbim.bim.prop import Attribute, StrProperty
from bpy.types import PropertyGroup
from bpy.props import (
PointerProperty,
StringProperty,
EnumProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
CollectionProperty,
)
diagram_scales_enum = []
titleblocks_enum = []
sheets_enum = []
vector_styles_enum = []
def purge():
global diagram_scales_enum
global titleblocks_enum
global sheets_enum
global vector_styles_enum
diagram_scales_enum = []
titleblocks_enum = []
sheets_enum = []
vector_styles_enum = []
def getDiagramScales(self, context):
global diagram_scales_enum
if (
len(diagram_scales_enum) < 1
or (bpy.context.scene.unit_settings.system == "IMPERIAL" and len(diagram_scales_enum) == 13)
or (bpy.context.scene.unit_settings.system == "METRIC" and len(diagram_scales_enum) == 31)
):
if bpy.context.scene.unit_settings.system == "IMPERIAL":
diagram_scales_enum = [
("CUSTOM", "Custom", ""),
("1'=1'-0\"|1/1", "1'=1'-0\"", ""),
('6"=1\'-0"|1/6', '6"=1\'-0"', ""),
('1-1/2"=1\'-0"|1/8', '1-1/2"=1\'-0"', ""),
('1"=1\'-0"|1/12', '1"=1\'-0"', ""),
('3/4"=1\'-0"|1/16', '3/4"=1\'-0"', ""),
('1/2"=1\'-0"|1/24', '1/2"=1\'-0"', ""),
('3/8"=1\'-0"|1/32', '3/8"=1\'-0"', ""),
('1/4"=1\'-0"|1/48', '1/4"=1\'-0"', ""),
('3/16"=1\'-0"|1/64', '3/16"=1\'-0"', ""),
('1/8"=1\'-0"|1/96', '1/8"=1\'-0"', ""),
('3/32"=1\'-0"|1/128', '3/32"=1\'-0"', ""),
('1/16"=1\'-0"|1/192', '1/16"=1\'-0"', ""),
('1/32"=1\'-0"|1/384', '1/32"=1\'-0"', ""),
('1/64"=1\'-0"|1/768', '1/64"=1\'-0"', ""),
('1/128"=1\'-0"|1/1536', '1/128"=1\'-0"', ""),
("1\"=10'|1/120", "1\"=10'", ""),
("1\"=20'|1/240", "1\"=20'", ""),
("1\"=30'|1/360", "1\"=30'", ""),
("1\"=40'|1/480", "1\"=40'", ""),
("1\"=50'|1/600", "1\"=50'", ""),
("1\"=60'|1/720", "1\"=60'", ""),
("1\"=70'|1/840", "1\"=70'", ""),
("1\"=80'|1/960", "1\"=80'", ""),
("1\"=90'|1/1080", "1\"=90'", ""),
("1\"=100'|1/1200", "1\"=100'", ""),
("1\"=150'|1/1800", "1\"=150'", ""),
("1\"=200'|1/2400", "1\"=200'", ""),
("1\"=300'|1/3600", "1\"=300'", ""),
("1\"=400'|1/4800", "1\"=400'", ""),
("1\"=500'|1/6000", "1\"=500'", ""),
]
else:
diagram_scales_enum = [
("CUSTOM", "Custom", ""),
("1:5000|1/5000", "1:5000", ""),
("1:2000|1/2000", "1:2000", ""),
("1:1000|1/1000", "1:1000", ""),
("1:500|1/500", "1:500", ""),
("1:200|1/200", "1:200", ""),
("1:100|1/100", "1:100", ""),
("1:50|1/50", "1:50", ""),
("1:20|1/20", "1:20", ""),
("1:10|1/10", "1:10", ""),
("1:5|1/5", "1:5", ""),
("1:2|1/2", "1:2", ""),
("1:1|1/1", "1:1", ""),
]
return diagram_scales_enum
def updateDrawingName(self, context):
if not self.camera:
return
if self.camera.name == self.name:
return
self.camera.name = "IfcAnnotation/{}".format(self.name)
unique_name = "/".join(self.camera.name.split("/")[1:])
self.camera.users_collection[0].name = "IfcGroup/{}".format(unique_name)
if self.name != unique_name:
self.name = unique_name
def refreshActiveDrawingIndex(self, context):
bpy.ops.bim.activate_view(drawing_index=context.scene.DocProperties.active_drawing_index)
def getTitleblocks(self, context):
global titleblocks_enum
if len(titleblocks_enum) < 1:
titleblocks_enum.clear()
for filename in Path(os.path.join(context.scene.BIMProperties.data_dir, "templates", "titleblocks")).glob(
"*.svg"
):
f = str(filename.stem)
titleblocks_enum.append((f, f, ""))
return titleblocks_enum
def refreshTitleblocks(self, context):
global titleblocks_enum
titleblocks_enum.clear()
getTitleblocks(self, context)
def toggleDecorations(self, context):
toggle = self.should_draw_decorations
if toggle:
decoration.DecorationsHandler.install(context)
else:
decoration.DecorationsHandler.uninstall()
def getVectorStyles(self, context):
global vector_styles_enum
if len(vector_styles_enum) < 1:
sheets_enum.clear()
for filename in Path(os.path.join(context.scene.BIMProperties.data_dir, "styles")).glob("*.css"):
f = str(filename.stem)
vector_styles_enum.append((f, f, ""))
return vector_styles_enum
def refreshFontSize(self, context):
annotation.Annotator.resize_text(context.active_object)
class Variable(PropertyGroup):
name: StringProperty(name="Name")
prop_key: StringProperty(name="Property Key")
class Drawing(PropertyGroup):
name: StringProperty(name="Name", update=updateDrawingName)
camera: PointerProperty(name="Camera", type=bpy.types.Object)
class Schedule(PropertyGroup):
name: StringProperty(name="Name")
file: StringProperty(name="File")
class Sheet(PropertyGroup):
def set_name(self, new):
old = self.get("name")
path = os.path.join(bpy.context.scene.BIMProperties.data_dir, "sheets")
if old and os.path.isfile(os.path.join(path, old + ".svg")):
os.rename(os.path.join(path, old + ".svg"), os.path.join(path, new + ".svg"))
self["name"] = new
def get_name(self):
return self.get("name")
name: StringProperty(name="Name", get=get_name, set=set_name)
drawings: CollectionProperty(name="Drawings", type=Drawing)
active_drawing_index: IntProperty(name="Active Drawing Index")
class DrawingStyle(PropertyGroup):
name: StringProperty(name="Name")
raster_style: StringProperty(name="Raster Style")
render_type: EnumProperty(
items=[
("NONE", "None", ""),
("DEFAULT", "Default", ""),
("VIEWPORT", "Viewport", ""),
],
name="Render Type",
default="VIEWPORT",
)
vector_style: EnumProperty(items=getVectorStyles, name="Vector Style")
include_query: StringProperty(name="Include Query")
exclude_query: StringProperty(name="Exclude Query")
attributes: CollectionProperty(name="Attributes", type=StrProperty)
class DocProperties(PropertyGroup):
has_underlay: BoolProperty(name="Underlay", default=False)
has_linework: BoolProperty(name="Linework", default=True)
has_annotation: BoolProperty(name="Annotation", default=True)
should_use_underlay_cache: BoolProperty(name="Use Underlay Cache", default=False)
should_use_linework_cache: BoolProperty(name="Use Linework Cache", default=False)
should_use_annotation_cache: BoolProperty(name="Use Annotation Cache", default=False)
should_extract: BoolProperty(name="Should Extract", default=True)
drawings: CollectionProperty(name="Drawings", type=Drawing)
active_drawing_index: IntProperty(name="Active Drawing Index", update=refreshActiveDrawingIndex)
current_drawing_index: IntProperty(name="Current Drawing Index")
schedules: CollectionProperty(name="Schedules", type=Schedule)
active_schedule_index: IntProperty(name="Active Schedule Index")
titleblock: EnumProperty(items=getTitleblocks, name="Titleblock", update=refreshTitleblocks)
sheets: CollectionProperty(name="Sheets", type=Sheet)
active_sheet_index: IntProperty(name="Active Sheet Index")
ifc_files: CollectionProperty(name="IFCs", type=StrProperty)
drawing_styles: CollectionProperty(name="Drawing Styles", type=DrawingStyle)
should_draw_decorations: BoolProperty(name="Should Draw Decorations", update=toggleDecorations)
decorations_colour: FloatVectorProperty(
name="Decorations Colour", subtype="COLOR", default=(1, 0, 0, 1), min=0.0, max=1.0, size=4
)
class BIMCameraProperties(PropertyGroup):
view_name: StringProperty(name="View Name")
target_view: EnumProperty(
items=[
("PLAN_VIEW", "PLAN_VIEW", ""),
("ELEVATION_VIEW", "ELEVATION_VIEW", ""),
("SECTION_VIEW", "SECTION_VIEW", ""),
("REFLECTED_PLAN_VIEW", "REFLECTED_PLAN_VIEW", ""),
("MODEL_VIEW", "MODEL_VIEW", ""),
],
name="Target View",
default="PLAN_VIEW",
)
diagram_scale: EnumProperty(items=getDiagramScales, name="Drawing Scale")
custom_diagram_scale: StringProperty(name="Custom Scale")
raster_x: IntProperty(name="Raster X", default=1000)
raster_y: IntProperty(name="Raster Y", default=1000)
is_nts: BoolProperty(name="Is NTS")
cut_objects: EnumProperty(
items=[
(
".IfcWall|.IfcSlab|.IfcCurtainWall|.IfcStair|.IfcStairFlight|.IfcColumn|.IfcBeam|.IfcMember|.IfcCovering|.IfcSpace",
"Overall Plan / Section",
"",
),
(".IfcElement", "Detail Drawing", ""),
("CUSTOM", "Custom", ""),
],
name="Cut Objects",
)
cut_objects_custom: StringProperty(name="Custom Cut")
active_drawing_style_index: IntProperty(name="Active Drawing Style Index")
class BIMTextProperties(PropertyGroup):
font_size: EnumProperty(
items=[
("1.8", "1.8 - Small", ""),
("2.5", "2.5 - Regular", ""),
("3.5", "3.5 - Large", ""),
("5.0", "5.0 - Header", ""),
("7.0", "7.0 - Title", ""),
],
update=refreshFontSize,
name="Font Size",
)
symbol: EnumProperty(
items=[
("None", "None", ""),
("rectangle-tag", "Rectangle Tag", ""),
("door-tag", "Door Tag", ""),
],
update=refreshFontSize,
name="Symbol",
)
related_element: PointerProperty(name="Related Element", type=bpy.types.Object)
variables: CollectionProperty(name="Variables", type=Variable)
@@ -1,10 +1,10 @@
from mathutils import Matrix
import bgl
from mathutils import Matrix
from gpu.types import GPUShader
from gpu_extras.batch import batch_for_shader
class BaseShader():
class BaseShader:
"""Wrapepr for GPUShader
To use for viewport decorations with geometry generated on GPU side.
@@ -85,14 +85,15 @@ class BaseShader():
def __init__(self):
# NB: libcode arg doesn't work
self.prog = GPUShader(vertexcode=self.VERT_GLSL,
fragcode=self.FRAG_GLSL,
geocode=self.LIB_GLSL + self.GEOM_GLSL,
defines=self.DEF_GLSL)
self.prog = GPUShader(
vertexcode=self.VERT_GLSL,
fragcode=self.FRAG_GLSL,
geocode=self.LIB_GLSL + self.GEOM_GLSL,
defines=self.DEF_GLSL,
)
def batch(self, indices=None, **data):
"""Returns automatic GPUBatch filled with provided parameters
"""
"""Returns automatic GPUBatch filled with provided parameters"""
batch = batch_for_shader(self.prog, self.TYPE, data, indices=indices)
batch.program_set(self.prog)
return batch
@@ -113,23 +114,26 @@ class BaseShader():
region = ctx.region
region3d = ctx.region_data
try:
self.prog.uniform_float('viewMatrix', region3d.perspective_matrix)
self.prog.uniform_float("viewMatrix", region3d.perspective_matrix)
except ValueError: # unused uniform
pass
try:
self.prog.uniform_float('winSize', (region.width / 2, region.height / 2))
self.prog.uniform_float("winSize", (region.width / 2, region.height / 2))
except ValueError: # unused uniform
pass
class BaseLinesShader(BaseShader):
"""Draws line segments with gaps around vertices at endpoints
"""
TYPE = 'LINES'
"""Draws line segments with gaps around vertices at endpoints"""
DEF_GLSL = BaseShader.DEF_GLSL + """
TYPE = "LINES"
DEF_GLSL = (
BaseShader.DEF_GLSL
+ """
#define GAP_SIZE {gap_size}
"""
)
GEOM_GLSL = """
layout(lines) in;
@@ -171,6 +175,7 @@ class GizmoShader(BaseShader):
Scaling to match viewport is partially controlled by user preferences and gizmo code.
"""
# TODO: add some magic to respect gizmo settings/params
VERT_GLSL = """
@@ -187,12 +192,15 @@ class GizmoShader(BaseShader):
class DotsGizmoShader(GizmoShader):
"""Draws circles of radius 1 around points"""
TYPE = 'POINTS'
TYPE = "POINTS"
DEF_GLSL = BaseShader.DEF_GLSL + """
DEF_GLSL = (
BaseShader.DEF_GLSL
+ """
#define CIRCLE_SEGMENTS 12
#define CIRCLE_RADIUS 8
"""
)
GEOM_GLSL = """
layout(points) in;
@@ -235,11 +243,14 @@ class DotsGizmoShader(GizmoShader):
class ExtrusionGuidesShader(GizmoShader):
"""Draws lines and add cross in XY plane at endpoints"""
TYPE = 'LINES'
TYPE = "LINES"
DEF_GLSL = BaseShader.DEF_GLSL + """
DEF_GLSL = (
BaseShader.DEF_GLSL
+ """
#define CROSS_SIZE .5
"""
)
GEOM_GLSL = """
uniform mat4 ModelViewProjectionMatrix;
@@ -13,7 +13,7 @@ class SheetBuilder:
self.scale = "NTS"
def create(self, name, titleblock_name):
sheet_path = "{}sheets/{}.svg".format(self.data_dir, name)
sheet_path = os.path.join(self.data_dir, f"{name}.svg")
root = ET.Element("svg")
root.attrib["xmlns"] = "http://www.w3.org/2000/svg"
root.attrib["xmlns:xlink"] = "http://www.w3.org/1999/xlink"
@@ -121,9 +121,9 @@ class SheetBuilder:
title.attrib["height"] = str(self.convert_to_mm(title_root.attrib.get("height")))
def build(self, sheet_name):
os.makedirs("{}build/{}/".format(self.data_dir, sheet_name), exist_ok=True)
os.makedirs(os.path.join(self.data_dir, "build", sheet_name), exist_ok=True)
sheet_path = "{}sheets/{}.svg".format(self.data_dir, sheet_name)
sheet_path = os.path.join(self.data_dir, "sheets", f"{sheet_name}.svg")
ET.register_namespace("", "http://www.w3.org/2000/svg")
ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
@@ -140,7 +140,7 @@ class SheetBuilder:
self.build_drawings(root.findall('{http://www.w3.org/2000/svg}g[@data-type="drawing"]'), sheet_name)
self.build_schedules(root.findall('{http://www.w3.org/2000/svg}g[@data-type="schedule"]'))
with open("{}build/{}/{}.svg".format(self.data_dir, sheet_name, sheet_name), "wb") as output:
with open(os.path.join(self.data_dir, "build", sheet_name, f"{sheet_name}.svg"), "wb") as output:
tree.write(output)
def build_drawings(self, drawings, sheet_name):
@@ -155,8 +155,9 @@ class SheetBuilder:
view.append(self.parse_embedded_svg(foreground, {}))
# Add background
background_path = "{}sheets/{}".format(self.data_dir, self.get_href(background))
copy(background_path, "{}build/{}/".format(self.data_dir, sheet_name))
background_path = os.path.join(self.data_dir, "sheets", self.get_href(background))
copy(background_path, os.path.join(self.data_dir, "build", sheet_name))
# Add view title
foreground_path = self.get_href(foreground)
@@ -202,7 +203,7 @@ class SheetBuilder:
self.convert_to_mm(image.attrib.get("x")), self.convert_to_mm(image.attrib.get("y"))
)
svg_path = self.get_href(image)
with open("{}sheets/{}".format(self.data_dir, svg_path), "r") as template:
with open(os.path.join(self.data_dir, "sheets", svg_path), "r") as template:
embedded = ET.fromstring(pystache.render(template.read(), data))
# viewBox should not be nested
embedded.attrib["viewBox"] = ""
@@ -45,9 +45,10 @@ class SvgWriter:
self.vector_style = None
self.human_scale = "NTS"
self.annotations = {}
self.background_image = None
self.scale = 1 / 100 # 1:100
def write(self):
def write(self, layer):
self.calculate_scale()
self.svg = svgwrite.Drawing(
self.output,
@@ -58,14 +59,16 @@ class SvgWriter:
data_scale=self.human_scale,
)
self.add_stylesheet()
self.add_markers()
self.add_symbols()
self.add_patterns()
# self.draw_background_image()
# self.draw_background_elements()
# self.draw_cut_polygons()
self.draw_annotations()
if layer == "underlay":
self.draw_background_image()
elif layer == "annotation":
self.add_stylesheet()
self.add_markers()
self.add_symbols()
self.add_patterns()
# self.draw_background_elements()
# self.draw_cut_polygons()
self.draw_annotations()
self.svg.save(pretty=True)
def calculate_scale(self):
@@ -76,32 +79,31 @@ class SvgWriter:
self.height = self.raw_height * self.scale
def add_stylesheet(self):
with open("{}styles/{}.css".format(self.data_dir, self.vector_style), "r") as stylesheet:
with open(os.path.join(self.data_dir, "styles", f"{self.vector_style}.css"), "r") as stylesheet:
self.svg.defs.add(self.svg.style(stylesheet.read()))
def add_markers(self):
tree = ET.parse("{}templates/markers.svg".format(self.data_dir))
tree = ET.parse(os.path.join(self.data_dir, "templates", "markers.svg"))
root = tree.getroot()
for child in root.getchildren():
self.svg.defs.add(External(child))
def add_symbols(self):
tree = ET.parse("{}templates/symbols.svg".format(self.data_dir))
tree = ET.parse(os.path.join(self.data_dir, "templates", "symbols.svg"))
root = tree.getroot()
for child in root.getchildren():
self.svg.defs.add(External(child))
def add_patterns(self):
tree = ET.parse("{}templates/patterns.svg".format(self.data_dir))
tree = ET.parse(os.path.join(self.data_dir, "templates", "patterns.svg"))
root = tree.getroot()
for child in root.getchildren():
self.svg.defs.add(External(child))
def draw_background_image(self):
return # TODO reimplement for artistic drawing options
self.svg.add(
self.svg.image(
os.path.join("..", "diagrams", os.path.basename(self.ifc_cutter.background_image)),
os.path.join("..", "diagrams", os.path.basename(self.background_image)),
**{"width": self.width, "height": self.height}
)
)
@@ -27,12 +27,17 @@ class BIM_PT_camera(Panel):
dprops = bpy.context.scene.DocProperties
props = context.active_object.data.BIMCameraProperties
layout.label(text="Generation Options:")
col = layout.column(align=True)
row = col.row(align=True)
row.prop(dprops, "has_underlay", icon="OUTLINER_OB_IMAGE")
row.prop(dprops, "should_use_underlay_cache", text="", icon="FILE_REFRESH")
row = col.row(align=True)
row.prop(dprops, "has_linework", icon="IMAGE_DATA")
row.prop(dprops, "should_use_linework_cache", text="", icon="FILE_REFRESH")
row = col.row(align=True)
row.prop(dprops, "has_annotation", icon="MOD_EDGESPLIT")
row.prop(dprops, "should_use_annotation_cache", text="", icon="FILE_REFRESH")
row = layout.row()
row.prop(dprops, "should_recut")
row = layout.row()
row.prop(dprops, "should_recut_selected")
row = layout.row()
row.prop(dprops, "should_extract")
@@ -64,7 +69,31 @@ class BIM_PT_camera(Panel):
row = layout.row()
row.prop(props, "custom_diagram_scale")
layout.label(text="Drawing Styles:")
row = layout.row(align=True)
row.operator("bim.create_drawing", text="Create Drawing", icon="OUTPUT")
op = row.operator("bim.open_view", icon="URL", text="")
op.view = context.active_object.name.split("/")[1]
class BIM_PT_drawing_underlay(Panel):
bl_label = "Drawing Underlay"
bl_idname = "BIM_PT_drawing_underlay"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
bl_parent_id = "BIM_PT_camera"
@classmethod
def poll(cls, context):
engine = context.engine
return context.camera and hasattr(context.active_object.data, "BIMCameraProperties")
def draw(self, context):
layout = self.layout
layout.use_property_split = True
dprops = bpy.context.scene.DocProperties
props = context.active_object.data.BIMCameraProperties
row = layout.row(align=True)
row.operator("bim.add_drawing_style")
@@ -101,8 +130,214 @@ class BIM_PT_camera(Panel):
row.operator("bim.save_drawing_style")
row.operator("bim.activate_drawing_style")
class BIM_PT_drawings(Panel):
bl_label = "SVG Drawings"
bl_idname = "BIM_PT_drawings"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.cut_section", text="Create Drawing")
row.operator("bim.create_drawing", text="Create Drawing 2.0")
op = row.operator("bim.open_view", icon="URL", text="")
op.view = context.active_object.name.split("/")[1]
row.operator("bim.add_drawing")
row.operator("bim.refresh_drawing_list", icon="FILE_REFRESH", text="")
if props.drawings:
if props.active_drawing_index < len(props.drawings):
op = row.operator("bim.open_view", icon="URL", text="")
op.view = props.drawings[props.active_drawing_index].name
row.operator("bim.remove_drawing", icon="X", text="").index = props.active_drawing_index
layout.template_list("BIM_UL_generic", "", props, "drawings", props, "active_drawing_index")
row = layout.row()
row.operator("bim.add_ifc_file")
for index, ifc_file in enumerate(props.ifc_files):
row = layout.row(align=True)
row.prop(ifc_file, "name", text="IFC #{}".format(index + 1))
row.operator("bim.select_doc_ifc_file", icon="FILE_FOLDER", text="").index = index
row.operator("bim.remove_ifc_file", icon="X", text="").index = index
class BIM_PT_schedules(Panel):
bl_label = "ODS Schedules"
bl_idname = "BIM_PT_schedules"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_schedule")
if props.schedules:
row.operator("bim.build_schedule", icon="LINENUMBERS_ON", text="")
row.operator("bim.remove_schedule", icon="X", text="").index = props.active_schedule_index
layout.template_list("BIM_UL_generic", "", props, "schedules", props, "active_schedule_index")
row = layout.row()
row.prop(props.schedules[props.active_schedule_index], "file")
row.operator("bim.select_schedule_file", icon="FILE_FOLDER", text="")
class BIM_PT_sheets(Panel):
bl_label = "SVG Sheets"
bl_idname = "BIM_PT_sheets"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.prop(props, "titleblock", text="")
row.operator("bim.add_sheet")
if props.sheets:
row.operator("bim.open_sheet", icon="URL", text="")
row.operator("bim.remove_sheet", icon="X", text="").index = props.active_sheet_index
layout.template_list("BIM_UL_generic", "", props, "sheets", props, "active_sheet_index")
row = layout.row(align=True)
row.operator("bim.add_drawing_to_sheet")
row.operator("bim.add_schedule_to_sheet")
row = layout.row()
row.operator("bim.create_sheets")
class BIM_PT_text(Panel):
bl_label = "Text Paper Space"
bl_idname = "BIM_PT_text"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
@classmethod
def poll(cls, context):
return type(context.curve) is bpy.types.TextCurve
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = context.active_object.data.BIMTextProperties
row = layout.row()
row.operator("bim.propagate_text_data")
row = layout.row()
row.prop(props, "font_size")
row = layout.row()
row.prop(props, "symbol")
row = layout.row()
row.prop(props, "related_element")
row = layout.row()
row.operator("bim.add_variable")
for index, variable in enumerate(props.variables):
row = layout.row(align=True)
row.prop(variable, "name")
row.operator("bim.remove_variable", icon="X", text="").index = index
row = layout.row()
row.prop(variable, "prop_key")
class BIM_PT_annotation_utilities(Panel):
bl_idname = "BIM_PT_annotation_utilities"
bl_label = "Annotation"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
def draw(self, context):
layout = self.layout
row = layout.row(align=True)
row.operator("bim.clean_wireframes")
row = layout.row(align=True)
row.operator("bim.link_ifc")
row = layout.row(align=True)
row.operator("bim.add_grid")
row = layout.row(align=True)
row.operator("bim.add_sections_annotations")
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Dim", icon="ARROW_LEFTRIGHT")
op.obj_name = "Dimension"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Dim (Eq)", icon="ARROW_LEFTRIGHT")
op.obj_name = "Equal"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Text", icon="SMALL_CAPS")
op.data_type = "text"
op = row.operator("bim.add_annotation", text="Leader", icon="TRACKING_BACKWARDS")
op.obj_name = "Leader"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Stair Arrow", icon="SCREEN_BACK")
op.obj_name = "Stair"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Hidden", icon="CON_TRACKTO")
op.obj_name = "Hidden"
op.data_type = "mesh"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Level (Plan)", icon="SORTBYEXT")
op.obj_name = "Plan Level"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Level (Section)", icon="TRIA_DOWN")
op.obj_name = "Section Level"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Breakline", icon="FCURVE")
op.obj_name = "Break"
op.data_type = "mesh"
op = row.operator("bim.add_annotation", text="Misc", icon="MESH_MONKEY")
op.obj_name = "Misc"
op.data_type = "mesh"
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_drawing")
row.operator("bim.refresh_drawing_list", icon="FILE_REFRESH", text="")
if props.drawings:
if props.active_drawing_index < len(props.drawings):
op = row.operator("bim.open_view", icon="URL", text="")
op.view = props.drawings[props.active_drawing_index].name
row.operator("bim.remove_drawing", icon="X", text="").index = props.active_drawing_index
layout.template_list("BIM_UL_drawinglist", "", props, "drawings", props, "active_drawing_index")
layout.prop(props, "should_draw_decorations")
layout.prop(props, "decorations_colour")
class BIM_UL_drawinglist(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if item:
row = layout.row(align=True)
row.prop(item, "name", text="", emboss=False)
op = row.operator("bim.open_view_camera", icon="OUTLINER_OB_CAMERA", text="")
op.view_name = item.name
else:
layout.label(text="", translate=False)
@@ -4,11 +4,9 @@ from . import ui, prop, operator
classes = (
operator.EditObjectPlacement,
operator.AddRepresentation,
operator.MapRepresentations,
operator.MapRepresentation,
operator.SwitchRepresentation,
operator.RemoveRepresentation,
operator.UpdateMeshRepresentation,
operator.UpdateRepresentation,
operator.UpdateParametricRepresentation,
operator.GetRepresentationIfcParameters,
prop.BIMGeometryProperties,
@@ -3,6 +3,7 @@ import numpy as np
import ifcopenshell
import ifcopenshell.util.unit
import ifcopenshell.util.element
import ifcopenshell.util.representation
import logging
import ifcopenshell.api
from blenderbim.bim.ifc import IfcStore
@@ -13,14 +14,6 @@ from ifcopenshell.api.void.data import Data as VoidData
from mathutils import Vector
def get_context_id(context_type, context_identifier, target_view):
for context in ContextData.contexts.values():
if context["ContextType"] == context_type:
for i, subcontext in context["HasSubContexts"].items():
if subcontext["ContextIdentifier"] == context_identifier and subcontext["TargetView"] == target_view:
return i
class EditObjectPlacement(bpy.types.Operator):
bl_idname = "bim.edit_object_placement"
bl_label = "Edit Object Placement"
@@ -71,116 +64,122 @@ class AddRepresentation(bpy.types.Operator):
bpy.ops.bim.edit_object_placement(obj=obj.name)
if obj.data:
product = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
if not obj.data:
return {"FINISHED"}
context_id = self.context_id or int(bpy.context.scene.BIMProperties.contexts)
context_of_items = self.file.by_id(context_id)
product = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
gprop = context.scene.BIMGeoreferenceProperties
coordinate_offset = None
if gprop.has_blender_offset and gprop.blender_offset_type == "CARTESIAN_POINT":
coordinate_offset = Vector(
(
float(gprop.blender_eastings),
float(gprop.blender_northings),
float(gprop.blender_orthogonal_height),
)
context_id = self.context_id or int(bpy.context.scene.BIMProperties.contexts)
context_of_items = self.file.by_id(context_id)
gprop = context.scene.BIMGeoreferenceProperties
coordinate_offset = None
if gprop.has_blender_offset and gprop.blender_offset_type == "CARTESIAN_POINT":
coordinate_offset = Vector(
(
float(gprop.blender_eastings),
float(gprop.blender_northings),
float(gprop.blender_orthogonal_height),
)
representation_data = {
"context": context_of_items,
"blender_object": obj,
"geometry": obj.data,
"coordinate_offset": coordinate_offset,
"total_items": max(1, len(obj.material_slots)),
"should_force_faceted_brep": context.scene.BIMGeometryProperties.should_force_faceted_brep,
"should_force_triangulation": context.scene.BIMGeometryProperties.should_force_triangulation,
}
result = ifcopenshell.api.run("geometry.add_representation", self.file, **representation_data)
if not result:
print("Failed to write shape representation")
return {"FINISHED"}
box_context_id = get_context_id("Model", "Box", "MODEL_VIEW")
old_box = ifcopenshell.util.element.get_representation(product, "Model", "Box", "MODEL_VIEW")
if (
box_context_id
and context_of_items.ContextType == "Model"
and context_of_items.ContextIdentifier
and context_of_items.ContextIdentifier == "Body"
):
if old_box:
bpy.ops.bim.remove_representation(representation_id=old_box.id(), obj=obj.name)
representation_data["context"] = self.file.by_id(box_context_id)
new_box = ifcopenshell.api.run("geometry.add_representation", self.file, **representation_data)
ifcopenshell.api.run(
"geometry.assign_representation", self.file, **{"product": product, "representation": new_box}
)
[
bpy.ops.bim.add_style(material=s.material.name)
for s in obj.material_slots
if s.material and not s.material.BIMMaterialProperties.ifc_style_id
]
ifcopenshell.api.run(
"geometry.assign_styles",
self.file,
**{
"shape_representation": result,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
ifcopenshell.api.run(
"geometry.assign_representation", self.file, **{"product": product, "representation": result}
)
existing_mesh = obj.data
mesh = obj.data.copy()
mesh.name = "{}/{}".format(context_id, result.id())
mesh.BIMMeshProperties.ifc_definition_id = int(result.id())
obj.data = mesh
representation_data = {
"context": context_of_items,
"blender_object": obj,
"geometry": obj.data,
"coordinate_offset": coordinate_offset,
"total_items": max(1, len(obj.material_slots)),
"should_force_faceted_brep": context.scene.BIMGeometryProperties.should_force_faceted_brep,
"should_force_triangulation": context.scene.BIMGeometryProperties.should_force_triangulation,
}
result = ifcopenshell.api.run("geometry.add_representation", self.file, **representation_data)
if not result:
print("Failed to write shape representation")
return {"FINISHED"}
[
bpy.ops.bim.add_style(material=s.material.name)
for s in obj.material_slots
if s.material and not s.material.BIMMaterialProperties.ifc_style_id
]
ifcopenshell.api.run(
"geometry.assign_styles",
self.file,
**{
"shape_representation": result,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
ifcopenshell.api.run(
"geometry.assign_representation", self.file, **{"product": product, "representation": result}
)
existing_mesh = obj.data
mesh = obj.data.copy()
mesh.name = "{}/{}".format(context_id, result.id())
mesh.BIMMeshProperties.ifc_definition_id = int(result.id())
obj.data = mesh
Data.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
if product.is_a("IfcTypeProduct"):
if self.file.schema == "IFC2X3":
types = product.ObjectTypeOf
else:
types = product.Types
if types:
for element in types[0].RelatedObjects:
Data.load(IfcStore.get_file(), element.id())
return {"FINISHED"}
class SwitchRepresentation(bpy.types.Operator):
bl_idname = "bim.switch_representation"
bl_label = "Switch Representation"
obj: bpy.props.StringProperty()
ifc_definition_id: bpy.props.IntProperty()
should_reload: bpy.props.BoolProperty()
disable_opening_subtractions: bpy.props.BoolProperty()
def execute(self, context):
self.obj = bpy.context.active_object
self.oprops = self.obj.BIMObjectProperties
self.element_obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
self.oprops = self.element_obj.BIMObjectProperties
self.file = IfcStore.get_file()
self.context_of_items = self.file.by_id(self.ifc_definition_id).ContextOfItems
self.mesh_name = "{}/{}".format(self.context_of_items.id(), self.ifc_definition_id)
self.mesh_name = self.get_mesh_name()
mesh = bpy.data.meshes.get(self.mesh_name)
if mesh:
self.obj.data.user_remap(mesh)
self.pull_mesh_from_ifc()
self.element_obj.data.user_remap(mesh)
if not mesh or self.should_reload:
self.pull_mesh_from_ifc()
return {"FINISHED"}
def get_mesh_name(self):
representation = self.resolve_mapped_representation(self.file.by_id(self.ifc_definition_id))
return "{}/{}".format(self.context_of_items.id(), representation.id())
def resolve_mapped_representation(self, representation):
if representation.RepresentationType == "MappedRepresentation":
return self.resolve_mapped_representation(representation.Items[0].MappingSource.MappedRepresentation)
return representation
def pull_mesh_from_ifc(self):
self.file = IfcStore.get_file()
logger = logging.getLogger("ImportIFC")
ifc_import_settings = import_ifc.IfcImportSettings.factory(bpy.context, IfcStore.path, logger)
element = self.file.by_id(self.oprops.ifc_definition_id)
settings = ifcopenshell.geom.settings()
if self.context_of_items.ContextIdentifier == "Body":
if self.disable_opening_subtractions:
if element.is_a("IfcTypeProduct") or self.disable_opening_subtractions:
shape = ifcopenshell.geom.create_shape(settings, self.file.by_id(self.ifc_definition_id))
else:
shape = ifcopenshell.geom.create_shape(settings, self.file.by_id(self.oprops.ifc_definition_id))
@@ -193,23 +192,24 @@ class SwitchRepresentation(bpy.types.Operator):
mesh = ifc_importer.create_mesh(element, shape)
mesh.name = self.mesh_name
mesh.BIMMeshProperties.ifc_definition_id = self.ifc_definition_id
self.obj.data.user_remap(mesh)
self.element_obj.data.user_remap(mesh)
material_creator = import_ifc.MaterialCreator(ifc_import_settings, ifc_importer)
material_creator.create(element, self.obj, mesh)
material_creator.create(element, self.element_obj, mesh)
if self.disable_opening_subtractions and self.context_of_items.ContextIdentifier == "Body":
if self.oprops.ifc_definition_id not in VoidData.products:
VoidData.load(IfcStore.get_file(), self.oprops.ifc_definition_id)
for opening_id in VoidData.products[self.oprops.ifc_definition_id]:
if opening_id in IfcStore.id_map:
opening = IfcStore.id_map[opening_id]
modifier = self.obj.modifiers.new("IfcOpeningElement", "BOOLEAN")
modifier.operation = "DIFFERENCE"
modifier.object = opening
opening = IfcStore.get_element(opening_id)
if not opening:
continue
modifier = self.element_obj.modifiers.new("IfcOpeningElement", "BOOLEAN")
modifier.operation = "DIFFERENCE"
modifier.object = opening
else:
for modifier in self.obj.modifiers:
for modifier in self.element_obj.modifiers:
if modifier.type == "BOOLEAN" and "IfcOpeningElement" in modifier.name:
self.obj.modifiers.remove(modifier)
self.element_obj.modifiers.remove(modifier)
class RemoveRepresentation(bpy.types.Operator):
@@ -248,64 +248,9 @@ class RemoveRepresentation(bpy.types.Operator):
return {"FINISHED"}
class MapRepresentations(bpy.types.Operator):
bl_idname = "bim.map_representations"
bl_label = "Map Representations"
product_id: bpy.props.IntProperty()
type_product_id: bpy.props.IntProperty()
def execute(self, context):
related_object = IfcStore.id_map[self.product_id]
if self.product_id not in Data.products:
Data.load(IfcStore.get_file(), self.product_id)
for representation_id in Data.products[self.product_id]:
bpy.ops.bim.remove_representation(obj=related_object.name, representation_id=representation_id)
if self.type_product_id not in Data.products:
Data.load(IfcStore.get_file(), self.type_product_id)
for representation_id in Data.products[self.type_product_id]:
bpy.ops.bim.map_representation(
obj=related_object.name,
representation_id=representation_id,
obj_data=IfcStore.id_map[self.type_product_id].data.name,
)
return {"FINISHED"}
class MapRepresentation(bpy.types.Operator):
bl_idname = "bim.map_representation"
bl_label = "Map Representation"
obj: bpy.props.StringProperty()
representation_id: bpy.props.IntProperty()
obj_data: bpy.props.StringProperty()
def execute(self, context):
objs = [bpy.data.objects.get(self.obj)] if self.obj else bpy.context.selected_objects
obj_data = bpy.data.meshes.get(self.obj_data) if self.obj_data else None
self.file = IfcStore.get_file()
for obj in objs:
bpy.ops.bim.edit_object_placement(obj=obj.name)
product = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
if obj_data:
obj.data = obj_data
result = ifcopenshell.api.run(
"geometry.map_representation", self.file, **{"representation": self.file.by_id(self.representation_id)}
)
ifcopenshell.api.run(
"geometry.assign_representation", self.file, **{"product": product, "representation": result}
)
Data.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
return {"FINISHED"}
class UpdateMeshRepresentation(bpy.types.Operator):
bl_idname = "bim.update_mesh_representation"
bl_label = "Update Mesh Representation"
class UpdateRepresentation(bpy.types.Operator):
bl_idname = "bim.update_representation"
bl_label = "Update Representation"
obj: bpy.props.StringProperty()
ifc_representation_class: bpy.props.StringProperty()
@@ -318,14 +263,14 @@ class UpdateMeshRepresentation(bpy.types.Operator):
for obj in objs:
self.update_obj_mesh_representation(context, obj)
IfcStore.edited_objs.discard(obj.name)
IfcStore.edited_objs.discard(obj)
return {"FINISHED"}
def update_obj_mesh_representation(self, context, obj):
product = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
if product.is_a("IfcGridAxis"):
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"AxisCurve": obj, "grid_axis": product})
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"axis_curve": obj, "grid_axis": product})
return
bpy.ops.bim.edit_object_placement(obj=obj.name)
@@ -357,20 +302,6 @@ class UpdateMeshRepresentation(bpy.types.Operator):
new_representation = ifcopenshell.api.run("geometry.add_representation", self.file, **representation_data)
box_context_id = get_context_id("Model", "Box", "MODEL_VIEW")
old_box = ifcopenshell.util.element.get_representation(product, "Model", "Box", "MODEL_VIEW")
if (
box_context_id
and old_box
and context_of_items.ContextType == "Model"
and context_of_items.ContextIdentifier
and context_of_items.ContextIdentifier == "Body"
):
representation_data["context"] = self.file.by_id(box_context_id)
new_box = ifcopenshell.api.run("geometry.add_representation", self.file, **representation_data)
for inverse in self.file.get_inverse(old_box):
ifcopenshell.util.element.replace_attribute(inverse, old_box, new_box)
ifcopenshell.api.run(
"geometry.assign_styles",
self.file,
@@ -406,7 +337,7 @@ class UpdateParametricRepresentation(bpy.types.Operator):
props = obj.data.BIMMeshProperties
parameter = props.ifc_parameters[self.index]
element = IfcStore.get_file().by_id(parameter.step_id)[parameter.index] = parameter.value
bpy.ops.bim.switch_representation(ifc_definition_id=props.ifc_definition_id)
bpy.ops.bim.switch_representation(ifc_definition_id=props.ifc_definition_id, should_reload=True)
return {"FINISHED"}
@@ -39,6 +39,7 @@ class BIM_PT_representations(Panel):
row.label(text=representation["ContextOfItems"]["TargetView"])
row.label(text=representation["RepresentationType"])
op = row.operator("bim.switch_representation", icon="OUTLINER_DATA_MESH", text="")
op.should_reload = True
op.ifc_definition_id = ifc_definition_id
op.disable_opening_subtractions = False
row.operator("bim.remove_representation", icon="X", text="").representation_id = ifc_definition_id
@@ -68,29 +69,31 @@ class BIM_PT_mesh(Panel):
row = layout.row(align=True)
op = row.operator("bim.switch_representation", text="Bake Voids", icon="SELECT_SUBTRACT")
op.should_reload = True
op.ifc_definition_id = props.ifc_definition_id
op.disable_opening_subtractions = False
op = row.operator("bim.switch_representation", text="Dynamic Voids", icon="SELECT_INTERSECT")
op.should_reload = True
op.ifc_definition_id = props.ifc_definition_id
op.disable_opening_subtractions = True
row = layout.row()
row.operator("bim.update_mesh_representation")
row.operator("bim.update_representation")
row = layout.row()
op = row.operator("bim.update_mesh_representation", text="Update Mesh As Rectangle Extrusion")
op = row.operator("bim.update_representation", text="Update Mesh As Rectangle Extrusion")
op.ifc_representation_class = "IfcExtrudedAreaSolid/IfcRectangleProfileDef"
row = layout.row()
op = row.operator("bim.update_mesh_representation", text="Update Mesh As Circle Extrusion")
op = row.operator("bim.update_representation", text="Update Mesh As Circle Extrusion")
op.ifc_representation_class = "IfcExtrudedAreaSolid/IfcCircleProfileDef"
row = layout.row()
op = row.operator("bim.update_mesh_representation", text="Update Mesh As Arbitrary Extrusion")
op = row.operator("bim.update_representation", text="Update Mesh As Arbitrary Extrusion")
op.ifc_representation_class = "IfcExtrudedAreaSolid/IfcArbitraryClosedProfileDef"
row = layout.row()
op = row.operator("bim.update_mesh_representation", text="Update Mesh As Arbitrary Extrusion With Voids")
op = row.operator("bim.update_representation", text="Update Mesh As Arbitrary Extrusion With Voids")
op.ifc_representation_class = "IfcExtrudedAreaSolid/IfcArbitraryProfileDefWithVoids"
row = layout.row()
@@ -187,6 +187,7 @@ class BIM_PT_gis(Panel):
class BIM_PT_gis_utilities(Panel):
bl_idname = "BIM_PT_gis_utilities"
bl_label = "Georeferencing Utilities"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
@@ -24,7 +24,7 @@ class BIM_PT_groups(Panel):
row.label(text="{} Groups Found".format(len(Data.groups)), icon="OUTLINER")
if self.props.is_editing:
row.operator("bim.add_group", text="", icon="ADD")
row.operator("bim.disable_group_editing_ui", text="", icon="CHECKMARK")
row.operator("bim.disable_group_editing_ui", text="", icon="CANCEL")
else:
row.operator("bim.load_groups", text="", icon="GREASEPENCIL")
@@ -42,7 +42,7 @@ class AddMaterial(bpy.types.Operator):
def execute(self, context):
obj = bpy.data.materials.get(self.obj) if self.obj else bpy.context.active_object.active_material
self.file = IfcStore.get_file()
result = ifcopenshell.api.run("material.add_material", self.file, **{"Name": obj.name})
result = ifcopenshell.api.run("material.add_material", self.file, **{"name": obj.name})
obj.BIMObjectProperties.ifc_definition_id = result.id()
Data.load(IfcStore.get_file())
material_prop_purge()
@@ -1,5 +1,4 @@
import bpy
import blenderbim.bim.schema # refactor
from ifcopenshell.api.material.data import Data
from blenderbim.bim.ifc import IfcStore
from blenderbim.bim.prop import StrProperty, Attribute
@@ -109,7 +109,7 @@ class BIM_PT_object_material(Panel):
if self.props.is_editing:
op = row.operator("bim.edit_assigned_material", icon="CHECKMARK", text="")
op.material_set = self.material_set_id
row.operator("bim.disable_editing_assigned_material", icon="X", text="")
row.operator("bim.disable_editing_assigned_material", icon="CANCEL", text="")
else:
row.operator("bim.enable_editing_assigned_material", icon="GREASEPENCIL", text="")
row.operator("bim.unassign_material", icon="X", text="")
@@ -168,7 +168,7 @@ class BIM_PT_object_material(Panel):
row.prop(self.props, "material_set_item_material", icon="MATERIAL")
op = row.operator("bim.edit_material_set_item", icon="CHECKMARK", text="")
op.material_set_item = set_item_id
row.operator("bim.disable_editing_material_set_item", icon="X", text="")
row.operator("bim.disable_editing_material_set_item", icon="CANCEL", text="")
for attribute in self.props.material_set_item_attributes:
row = box.row(align=True)
@@ -197,7 +197,7 @@ class BIM_PT_object_material(Panel):
else:
# TODO: support non parametric profiles by showing a list of named profiles to select from, or an
# eyedropper to pick profile geometry from the scene
row.operator("bim.disable_editing_material_set_item", icon="X", text="")
row.operator("bim.disable_editing_material_set_item", icon="CANCEL", text="")
def draw_editable_profile_ui(self, layout, item):
for attribute in self.props.material_set_item_profile_attributes:
@@ -224,7 +224,11 @@ class BIM_PT_object_material(Panel):
else:
item = self.set_data[set_item_id]
row = self.layout.row(align=True)
row.label(text=item.get("Name", "Unnamed") or "Unnamed", icon="ALIGN_CENTER")
item_name = item.get("Name", "Unnamed") or "Unnamed"
thickness = item.get("LayerThickness")
if thickness:
item_name += f" ({thickness})"
row.label(text=item_name, icon="ALIGN_CENTER")
row.label(text=Data.materials[item["Material"]]["Name"], icon="MATERIAL")
if not is_first:
@@ -261,6 +265,7 @@ class BIM_PT_object_material(Panel):
row.label(text="Description")
row.label(text=str(self.material_set_data["Description"]))
total_thickness = 0
for item_id in self.set_items:
if self.product_data["type"] == "IfcMaterialList":
row = self.layout.row(align=True)
@@ -269,5 +274,14 @@ class BIM_PT_object_material(Panel):
else:
item = self.set_data[item_id]
row = self.layout.row(align=True)
row.label(text=item.get("Name", "Unnamed") or "Unnamed", icon="ALIGN_CENTER")
item_name = item.get("Name", "Unnamed") or "Unnamed"
thickness = item.get("LayerThickness")
if thickness:
item_name += f" ({thickness})"
total_thickness += thickness
row.label(text=item_name, icon="ALIGN_CENTER")
row.label(text=Data.materials[item["Material"]]["Name"], icon="MATERIAL")
if total_thickness:
row = self.layout.row(align=True)
row.label(text=f"Total Thickness: {total_thickness}")
@@ -1,13 +1,21 @@
import bpy
from . import grid, wall, stair, door, window, slab, opening, pie
from . import handler, prop, ui, grid, product, wall, slab, stair, door, window, opening, pie, workspace
classes = (
product.AddTypeInstance,
wall.AddWall,
wall.JoinWall,
wall.AlignWall,
wall.FlipWall,
wall.SplitWall,
prop.BIMModelProperties,
ui.BIM_PT_authoring,
ui.BIM_PT_authoring_architectural,
ui.BIM_PT_misc_utilities,
grid.BIM_OT_add_object,
wall.BIM_OT_add_object,
stair.BIM_OT_add_object,
door.BIM_OT_add_object,
window.BIM_OT_add_object,
slab.BIM_OT_add_object,
opening.BIM_OT_add_object,
pie.OpenPieClass,
pie.PieUpdateContainer,
@@ -27,13 +35,14 @@ addon_keymaps = []
def register():
bpy.utils.register_tool(workspace.WallTool, after={"builtin.scale_cage"}, separator=True, group=True)
bpy.types.Scene.BIMModelProperties = bpy.props.PointerProperty(type=prop.BIMModelProperties)
bpy.types.VIEW3D_MT_mesh_add.append(grid.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(wall.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(stair.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(door.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(window.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(slab.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(opening.add_object_button)
bpy.app.handlers.load_post.append(handler.load_post)
wm = bpy.context.window_manager
if wm.keyconfigs.addon:
km = wm.keyconfigs.addon.keymaps.new(name="3D View", space_type="VIEW_3D")
@@ -43,12 +52,13 @@ def register():
def unregister():
bpy.utils.unregister_tool(workspace.WallTool)
del bpy.types.Scene.BIMModelProperties
bpy.app.handlers.load_post.remove(handler.load_post)
bpy.types.VIEW3D_MT_mesh_add.remove(grid.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(wall.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(stair.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(door.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(window.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(slab.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.remove(opening.add_object_button)
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
@@ -57,10 +57,10 @@ def add_object(self, context):
result = ifcopenshell.api.run(
"grid.create_grid_axis",
self.file,
**{"AxisTag": tag, "AxisCurve": obj, "UVWAxes": "UAxes", "Grid": grid},
**{"axis_tag": tag, "uvw_axes": "UAxes", "grid": grid},
)
IfcStore.link_element(result, obj)
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"AxisCurve": obj, "grid_axis": result})
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"axis_curve": obj, "grid_axis": result})
obj.BIMObjectProperties.ifc_definition_id = result.id()
axes_collection = bpy.data.collections.new("VAxes")
@@ -83,10 +83,10 @@ def add_object(self, context):
result = ifcopenshell.api.run(
"grid.create_grid_axis",
self.file,
**{"AxisTag": tag, "AxisCurve": obj, "UVWAxes": "VAxes", "Grid": grid},
**{"axis_tag": tag, "uvw_axes": "VAxes", "grid": grid},
)
IfcStore.link_element(result, obj)
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"AxisCurve": obj, "grid_axis": result})
ifcopenshell.api.run("grid.create_axis_curve", self.file, **{"axis_curve": obj, "grid_axis": result})
obj.BIMObjectProperties.ifc_definition_id = result.id()
@@ -0,0 +1,20 @@
import bpy
import ifcopenshell
import ifcopenshell.api
from blenderbim.bim.module.model import product, wall, slab
from blenderbim.bim.ifc import IfcStore
from bpy.app.handlers import persistent
@persistent
def load_post(*args):
ifcopenshell.api.add_post_listener("geometry.add_representation", None, product.generate_box)
ifcopenshell.api.add_post_listener("geometry.add_representation", None, wall.generate_axis)
ifcopenshell.api.add_post_listener("geometry.add_representation", None, wall.calculate_quantities)
ifcopenshell.api.add_pre_listener("material.edit_layer", None, wall.DumbWallPlaner().regenerate_from_layer)
ifcopenshell.api.add_pre_listener("type.assign_type", None, wall.DumbWallPlaner().regenerate_from_type)
IfcStore.add_element_listener(slab.element_listener)
ifcopenshell.api.add_pre_listener("material.edit_layer", None, slab.DumbSlabPlaner().regenerate_from_layer)
ifcopenshell.api.add_pre_listener("type.assign_type", None, slab.DumbSlabPlaner().regenerate_from_type)
@@ -116,7 +116,7 @@ class VIEW3D_MT_PIE_bim(bpy.types.Menu):
def draw(self, context):
pie = self.layout.menu_pie()
pie.operator("bim.edit_object_placement")
pie.operator("bim.update_mesh_representation")
pie.operator("bim.update_representation")
pie.operator("bim.pie_add_opening")
pie.operator("bim.pie_update_container")
pie.operator("bim.open_pie_class", text="Assign IFC Class")
@@ -0,0 +1,89 @@
import bpy
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.element
import ifcopenshell.util.representation
from . import wall, slab
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.pset.data import Data as PsetData
class AddTypeInstance(bpy.types.Operator):
bl_idname = "bim.add_type_instance"
bl_label = "Add Type Instance"
bl_options = {"REGISTER", "UNDO"}
ifc_class: bpy.props.StringProperty()
relating_type: bpy.props.IntProperty()
def execute(self, context):
tprops = context.scene.BIMTypeProperties
ifc_class = self.ifc_class or tprops.ifc_class
relating_type = self.relating_type or tprops.relating_type
if not ifc_class or not relating_type:
return {"FINISHED"}
self.file = IfcStore.get_file()
instance_class = ifcopenshell.util.type.get_applicable_entities(ifc_class, self.file.schema)[0]
if ifc_class == "IfcWallType":
obj = wall.DumbWallGenerator(self.file.by_id(int(relating_type))).generate()
if obj:
return {"FINISHED"}
elif ifc_class == "IfcSlabType":
obj = slab.DumbSlabGenerator(self.file.by_id(int(relating_type))).generate()
if obj:
return {"FINISHED"}
# A cube
verts = [
Vector((-1, -1, -1)),
Vector((-1, -1, 1)),
Vector((-1, 1, -1)),
Vector((-1, 1, 1)),
Vector((1, -1, -1)),
Vector((1, -1, 1)),
Vector((1, 1, -1)),
Vector((1, 1, 1)),
]
edges = []
faces = [
[0, 2, 3, 1],
[2, 3, 7, 6],
[4, 5, 7, 6],
[0, 1, 5, 4],
[1, 3, 7, 5],
[0, 2, 6, 4],
]
mesh = bpy.data.meshes.new(name="Instance")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Instance", mesh)
obj.location = context.scene.cursor.location
collection = bpy.context.view_layer.active_layer_collection.collection
collection.objects.link(obj)
collection_obj = bpy.data.objects.get(collection.name)
bpy.ops.bim.assign_class(obj=obj.name, ifc_class=instance_class)
bpy.ops.bim.assign_type(relating_type=int(tprops.relating_type), related_object=obj.name)
if collection_obj and collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = collection_obj.location[2] - min([v[2] for v in obj.bound_box])
return {"FINISHED"}
def generate_box(usecase_path, ifc_file, **settings):
box_context = ifcopenshell.util.representation.get_context(ifc_file, "Model", "Box", "MODEL_VIEW")
if not box_context:
return
obj = settings["blender_object"]
product = ifc_file.by_id(obj.BIMObjectProperties.ifc_definition_id)
old_box = ifcopenshell.util.representation.get_representation(product, "Model", "Box", "MODEL_VIEW")
if settings["context"].ContextType == "Model" and getattr(settings["context"], "ContextIdentifier") == "Body":
if old_box:
bpy.ops.bim.remove_representation(representation_id=old_box.id(), obj=obj.name)
new_settings = settings.copy()
new_settings["context"] = box_context
new_box = ifcopenshell.api.run(
"geometry.add_representation", ifc_file, should_run_listeners=False, **new_settings
)
ifcopenshell.api.run(
"geometry.assign_representation",
ifc_file,
should_run_listeners=False,
**{"product": product, "representation": new_box}
)
@@ -0,0 +1,32 @@
import bpy
import ifcopenshell.util.type
from blenderbim.bim.prop import StrProperty, Attribute
from blenderbim.bim.ifc import IfcStore
from bpy.types import PropertyGroup
from bpy.props import (
PointerProperty,
StringProperty,
EnumProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
CollectionProperty,
)
relating_types_enum = []
def purge():
global relating_types_enum
relating_types_enum = []
def getRelatingTypes(self, context):
global relating_types_enum
if len(relating_types_enum) < 1:
elements = IfcStore.get_file().by_type("IfcWallType")
relating_types_enum.extend((str(e.id()), e.Name, "") for e in elements)
return relating_types_enum
class BIMModelProperties(PropertyGroup):
relating_type: EnumProperty(items=getRelatingTypes, name="Relating Type")
@@ -1,46 +1,174 @@
import bpy
from bpy.types import Operator
from bpy.props import FloatProperty
from mathutils import Vector
import bmesh
import math
import ifcopenshell
import ifcopenshell.util.type
import ifcopenshell.util.unit
import mathutils.geometry
import blenderbim.bim.handler
from blenderbim.bim.ifc import IfcStore
from math import pi, degrees
from mathutils import Vector, Matrix
from ifcopenshell.api.material.data import Data as MaterialData
def add_object(self, context):
verts = [
Vector((0, 0, 0)),
Vector((0, self.width, 0)),
Vector((self.length, self.width, 0)),
Vector((self.length, 0, 0)),
]
edges = []
faces = [[0, 1, 2, 3]]
def element_listener(element, obj):
blenderbim.bim.handler.subscribe_to(obj, "mode", mode_callback)
mesh = bpy.data.meshes.new(name="Dumb Slab")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Slab", mesh)
modifier = obj.modifiers.new("Slab Depth", "SOLIDIFY")
modifier.use_even_offset = True
modifier.offset = 1
modifier.thickness = self.depth
obj.name = "Slab"
context.view_layer.active_layer_collection.collection.objects.link(obj)
if IfcStore.get_file():
def mode_callback(obj, data):
for obj in bpy.context.selected_objects + [bpy.context.active_object]:
if (
obj.mode != "EDIT"
or not obj.data
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
product = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if parametric and parametric["Engine"] != "BlenderBIM.DumbSlab":
return
modifier = [m for m in obj.modifiers if m.type == "SOLIDIFY"]
if modifier:
return
depth = obj.dimensions.z
bm = bmesh.from_edit_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
bm.faces.ensure_lookup_table()
non_bottom_faces = []
for face in bm.faces:
if face.normal.z > -0.9:
non_bottom_faces.append(face)
else:
face.normal_flip()
bmesh.ops.delete(bm, geom=non_bottom_faces, context="FACES")
bmesh.update_edit_mesh(obj.data)
bm.free()
modifier = obj.modifiers.new("Slab Depth", "SOLIDIFY")
modifier.use_even_offset = True
modifier.offset = 1
modifier.thickness = depth
class DumbSlabGenerator:
def __init__(self, relating_type):
self.relating_type = relating_type
def generate(self):
self.file = IfcStore.get_file()
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
thicknesses = []
for rel in self.relating_type.HasAssociations:
if rel.is_a("IfcRelAssociatesMaterial"):
material = rel.RelatingMaterial
if material.is_a("IfcMaterialLayerSet"):
thicknesses = [l.LayerThickness for l in material.MaterialLayers]
break
if not thicknesses:
return
self.collection = bpy.context.view_layer.active_layer_collection.collection
self.collection_obj = bpy.data.objects.get(self.collection.name)
self.depth = sum(thicknesses) * unit_scale
self.width = 3
self.length = 3
self.rotation = 0
self.location = Vector((0, 0, 0))
return self.derive_from_cursor()
def derive_from_cursor(self):
self.location = bpy.context.scene.cursor.location
return self.create_slab()
def create_slab(self):
verts = [
Vector((0, 0, 0)),
Vector((0, self.width, 0)),
Vector((self.length, self.width, 0)),
Vector((self.length, 0, 0)),
]
edges = []
faces = [[0, 3, 2, 1]]
mesh = bpy.data.meshes.new(name="Dumb Slab")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Slab", mesh)
modifier = obj.modifiers.new("Slab Depth", "SOLIDIFY")
modifier.use_even_offset = True
modifier.offset = 1
modifier.thickness = self.depth
obj.name = "Slab"
obj.location = self.location
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2] - self.depth
else:
obj.location[2] -= self.depth
self.collection.objects.link(obj)
bpy.ops.bim.assign_class(obj=obj.name, ifc_class="IfcSlab", predefined_type="FLOOR")
obj.location = context.scene.cursor.location
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
pset = ifcopenshell.api.run("pset.add_pset", self.file, product=element, name="EPset_Parametric")
ifcopenshell.api.run("pset.edit_pset", self.file, pset=pset, properties={"Engine": "BlenderBIM.DumbSlab"})
MaterialData.load(self.file)
obj.select_set(True)
return obj
class BIM_OT_add_object(Operator):
bl_idname = "mesh.add_slab"
bl_label = "Dumb Slab"
class DumbSlabPlaner:
def regenerate_from_layer(self, usecase_path, ifc_file, **settings):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
layer = settings["layer"]
thickness = settings["attributes"].get("LayerThickness")
if thickness is None or layer.LayerThickness == thickness:
return
delta_thickness = thickness - layer.LayerThickness
for layer_set in layer.ToMaterialLayerSet:
total_thickness = sum([l.LayerThickness for l in layer_set.MaterialLayers])
if not total_thickness:
continue
for inverse in ifc_file.get_inverse(layer_set):
if not inverse.is_a("IfcMaterialLayerSetUsage"):
continue
if ifc_file.schema == "IFC2X3":
for rel in ifc_file.get_inverse(inverse):
if not rel.is_a("IfcRelAssociatesMaterial"):
continue
for element in rel.RelatedObjects:
self.change_thickness(element, delta_thickness)
else:
for rel in inverse.AssociatedTo:
for element in rel.RelatedObjects:
self.change_thickness(element, delta_thickness)
length: FloatProperty(name="Length", default=2)
width: FloatProperty(name="Width", default=2)
depth: FloatProperty(name="Depth", default=0.2)
def regenerate_from_type(self, usecase_path, ifc_file, **settings):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
new_material = ifcopenshell.util.element.get_material(settings["relating_type"])
if not new_material.is_a("IfcMaterialLayerSet"):
return
obj = IfcStore.get_element(settings["related_object"].id())
if not obj:
return
current_thickness = obj.dimensions.z / self.unit_scale
new_thickness = sum([l.LayerThickness for l in new_material.MaterialLayers])
if current_thickness == new_thickness:
return
self.change_thickness(settings["related_object"], new_thickness - current_thickness)
def execute(self, context):
add_object(self, context)
return {"FINISHED"}
def change_thickness(self, element, delta_thickness):
parametric = ifcopenshell.util.element.get_psets(element).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbSlab":
return
obj = IfcStore.get_element(element.id())
if not obj:
return
def add_object_button(self, context):
self.layout.operator(BIM_OT_add_object.bl_idname, icon="PLUGIN")
modifier = [m for m in obj.modifiers if m.type == "SOLIDIFY"]
if modifier:
modifier = modifier[0]
else:
pass
modifier.thickness += delta_thickness * self.unit_scale
obj.location[2] -= delta_thickness * self.unit_scale
@@ -0,0 +1,63 @@
from bpy.types import Panel
from blenderbim.bim.ifc import IfcStore
class BIM_PT_authoring(Panel):
bl_idname = "BIM_PT_authoring"
bl_label = "Authoring"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
def draw(self, context):
tprops = context.scene.BIMTypeProperties
col = self.layout.column(align=True)
col.prop(tprops, "ifc_class", text="", icon="FILE_VOLUME")
col.prop(tprops, "relating_type", text="", icon="FILE_3D")
col.operator("bim.add_type_instance", icon="ADD")
class BIM_PT_authoring_architectural(Panel):
bl_label = "Architectural"
bl_idname = "BIM_PT_authoring_architectural"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
bl_parent_id = "BIM_PT_authoring"
def draw(self, context):
row = self.layout.row(align=True)
row.operator("bim.join_wall", icon="MOD_SKIN", text="T").join_type = "T"
row.operator("bim.join_wall", icon="MOD_SKIN", text="L").join_type = "L"
row.operator("bim.join_wall", icon="MOD_SKIN", text="V").join_type = "V"
row.operator("bim.join_wall", icon="X", text="").join_type = ""
row = self.layout.row(align=True)
row.operator("bim.align_wall", icon="ANCHOR_TOP", text="Ext.").align_type = "EXTERIOR"
row.operator("bim.align_wall", icon="ANCHOR_CENTER", text="C/L").align_type = "CENTERLINE"
row.operator("bim.align_wall", icon="ANCHOR_BOTTOM", text="Int.").align_type = "INTERIOR"
row = self.layout.row(align=True)
row.operator("bim.flip_wall", icon="ORIENTATION_NORMAL", text="Flip")
row.operator("bim.split_wall", icon="MOD_PHYSICS", text="Split")
class BIM_PT_misc_utilities(Panel):
bl_idname = "BIM_PT_misc_utilities"
bl_label = "Miscellaneous"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
def draw(self, context):
layout = self.layout
props = context.scene.BIMProperties
row = layout.row()
row.prop(props, "override_colour", text="")
row = layout.row(align=True)
row.operator("bim.set_override_colour")
row = layout.row(align=True)
row.operator("bim.set_viewport_shadow_from_sun")
row = layout.row(align=True)
row.operator("bim.snap_spaces_together")
@@ -1,64 +1,863 @@
import bpy
from bpy.types import Operator
from bpy.props import FloatProperty, BoolProperty
from mathutils import Vector
import math
import bmesh
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.unit
import ifcopenshell.util.element
import ifcopenshell.util.representation
import mathutils.geometry
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.pset.data import Data as PsetData
from ifcopenshell.api.material.data import Data as MaterialData
from math import pi, degrees
from mathutils import Vector, Matrix
def add_object(self, context):
if self.use_plane:
verts = [
Vector((0, 0, 0)),
Vector((0, 0, self.height)),
Vector((self.length, 0, self.height)),
Vector((self.length, 0, 0)),
]
edges = []
faces = [[0, 1, 2, 3]]
else:
verts = [
Vector((0, 0, 0)),
Vector((self.length, 0, 0)),
]
edges = [[0, 1]]
faces = []
mesh = bpy.data.meshes.new(name="Dumb Wall")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Wall", mesh)
context.view_layer.active_layer_collection.collection.objects.link(obj)
if not self.use_plane:
modifier = obj.modifiers.new("Wall Height", "SCREW")
modifier.angle = 0
modifier.screw_offset = self.height
modifier.use_smooth_shade = False
modifier.use_normal_calculate = True
modifier.use_normal_flip = True
modifier.steps = 1
modifier.render_steps = 1
modifier = obj.modifiers.new("Wall Width", "SOLIDIFY")
modifier.use_even_offset = True
modifier.thickness = self.width
obj.name = "Wall"
if IfcStore.get_file():
bpy.ops.bim.assign_class(obj=obj.name, ifc_class="IfcWall")
obj.location = context.scene.cursor.location
return obj
class BIM_OT_add_object(Operator):
bl_idname = "mesh.add_wall"
bl_label = "Dumb Wall"
height: FloatProperty(name="Height", default=3)
length: FloatProperty(name="Length", default=1)
width: FloatProperty(name="Width", default=0.2)
use_plane: BoolProperty(name="Use Plane", default=False)
class AddWall(bpy.types.Operator):
bl_idname = "bim.add_wall"
bl_label = "Add Wall"
bl_options = {"REGISTER", "UNDO"}
join_type: bpy.props.StringProperty()
def execute(self, context):
add_object(self, context)
props = context.scene.BIMModelProperties
bpy.ops.bim.add_type_instance(ifc_class="IfcWallType", relating_type=int(props.relating_type))
return {"FINISHED"}
def add_object_button(self, context):
self.layout.operator(BIM_OT_add_object.bl_idname, icon="PLUGIN")
class JoinWall(bpy.types.Operator):
bl_idname = "bim.join_wall"
bl_label = "Join Wall"
bl_options = {"REGISTER", "UNDO"}
join_type: bpy.props.StringProperty()
def execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) == 0:
return {"FINISHED"}
if not self.join_type:
for obj in selected_objs:
DumbWallJoiner(obj, obj).unjoin()
return {"FINISHED"}
if len(selected_objs) < 2 or not context.active_object:
return {"FINISHED"}
for obj in selected_objs:
if obj == context.active_object:
continue
joiner = DumbWallJoiner(obj, context.active_object)
if self.join_type == "T":
joiner.join_T()
elif self.join_type == "L":
joiner.join_L()
elif self.join_type == "V":
joiner.join_V()
IfcStore.edited_objs.add(obj)
if self.join_type != "T":
IfcStore.edited_objs.add(context.active_object)
return {"FINISHED"}
class AlignWall(bpy.types.Operator):
bl_idname = "bim.align_wall"
bl_label = "Align Wall"
bl_options = {"REGISTER", "UNDO"}
align_type: bpy.props.StringProperty()
def execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) < 2 or not context.active_object:
return {"FINISHED"}
for obj in selected_objs:
if obj == context.active_object:
continue
aligner = DumbWallAligner(obj, context.active_object)
if self.align_type == "CENTERLINE":
aligner.align_centerline()
elif self.align_type == "EXTERIOR":
aligner.align_first_layer()
elif self.align_type == "INTERIOR":
aligner.align_last_layer()
return {"FINISHED"}
class FlipWall(bpy.types.Operator):
bl_idname = "bim.flip_wall"
bl_label = "Flip Wall"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) == 0:
return {"FINISHED"}
for obj in selected_objs:
DumbWallFlipper(obj).flip()
return {"FINISHED"}
class SplitWall(bpy.types.Operator):
bl_idname = "bim.split_wall"
bl_label = "Split Wall"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) == 0:
return {"FINISHED"}
for obj in selected_objs:
DumbWallSplitter(obj, bpy.context.scene.cursor.location).split()
return {"FINISHED"}
def recalculate_dumb_wall_origin(wall, new_origin=None):
if new_origin is None:
new_origin = wall.matrix_world @ Vector(wall.bound_box[0])
if (wall.matrix_world.translation - new_origin).length < 0.001:
return
wall.data.transform(
Matrix.Translation(
(wall.matrix_world.inverted().to_quaternion() @ (wall.matrix_world.translation - new_origin))
)
)
wall.matrix_world.translation = new_origin
class DumbWallSplitter:
def __init__(self, wall, point):
self.wall = wall
self.point = point
def split(self):
recalculate_dumb_wall_origin(self.wall)
self.point = self.determine_split_point()
if not self.point:
return
new_wall = self.duplicate_wall()
self.snap_end_face_to_point(self.wall, "max")
self.snap_end_face_to_point(new_wall, "min")
def determine_split_point(self):
start = self.wall.matrix_world @ Vector(self.wall.bound_box[0])
end = self.wall.matrix_world @ Vector(self.wall.bound_box[4])
point, distance = mathutils.geometry.intersect_point_line(self.point, start, end)
if round(distance, 2) <= 0 or round(distance, 2) >= 1:
return # The split point is not on the wall
return point
def duplicate_wall(self):
new = self.wall.copy()
self.wall.users_collection[0].objects.link(new)
bpy.ops.bim.copy_class(obj=new.name)
return new
def snap_end_face_to_point(self, wall, which_end):
bm = bmesh.new()
bm.from_mesh(wall.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
min_face, max_face = self.get_wall_end_faces(wall, bm)
face = min_face if which_end == "min" else max_face
local_point = wall.matrix_world.inverted() @ self.point
for vert in face.verts:
vert.co.x = local_point.x
bm.to_mesh(wall.data)
wall.data.update()
bm.free()
IfcStore.edited_objs.add(wall)
# An end face is a quad that is on one end of the wall or the other. It must
# have at least one vertex on either extreme X-axis, and a non-insignificant
# X component of its face normal
def get_wall_end_faces(self, wall, bm):
min_face = None
max_face = None
min_x = min([v[0] for v in wall.bound_box])
max_x = max([v[0] for v in wall.bound_box])
bm.faces.ensure_lookup_table()
for f in bm.faces:
for v in f.verts:
if v.co.x == min_x and abs(f.normal.x) > 0.1:
min_face = f
elif v.co.x == max_x and abs(f.normal.x) > 0.1:
max_face = f
if min_face and max_face:
break
return min_face, max_face
class DumbWallFlipper:
# A flip switches the origin from the min XY corner to the max XY corner, and rotates the origin by 180.
def __init__(self, wall):
self.wall = wall
def flip(self):
if (
self.wall.matrix_world.translation - self.wall.matrix_world @ Vector(self.wall.bound_box[0])
).length < 0.001:
recalculate_dumb_wall_origin(self.wall, self.wall.matrix_world @ Vector(self.wall.bound_box[7]))
self.rotate_wall_180()
else:
recalculate_dumb_wall_origin(self.wall)
def rotate_wall_180(self):
flip_matrix = Matrix.Rotation(pi, 4, "Z")
self.wall.data.transform(flip_matrix)
self.wall.rotation_euler.rotate(flip_matrix)
class DumbWallAligner:
# An alignment shifts the origin of all walls to the closest point on the
# local X axis of the reference wall. In addition, the Z rotation is copied.
# Z translations are ignored for alignment.
def __init__(self, wall, reference_wall):
self.wall = wall
self.reference_wall = reference_wall
def align_centerline(self):
recalculate_dumb_wall_origin(self.wall)
recalculate_dumb_wall_origin(self.reference_wall)
self.align_rotation()
width = (Vector(self.wall.bound_box[3]) - Vector(self.wall.bound_box[0])).y
reference_width = (Vector(self.reference_wall.bound_box[3]) - Vector(self.reference_wall.bound_box[0])).y
if self.is_rotation_flipped():
offset = self.wall.matrix_world.to_quaternion() @ Vector((0, -(reference_width / 2) - (width / 2), 0))
else:
offset = self.wall.matrix_world.to_quaternion() @ Vector((0, (reference_width / 2) - (width / 2), 0))
self.align(
self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[0]),
self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[4]),
offset,
)
def align_last_layer(self):
recalculate_dumb_wall_origin(self.wall)
recalculate_dumb_wall_origin(self.reference_wall)
self.align_rotation()
if self.is_rotation_flipped():
DumbWallFlipper(self.wall).flip()
bpy.context.view_layer.update()
start = self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[3])
end = self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[7])
wall_width = (Vector(self.wall.bound_box[3]) - Vector(self.wall.bound_box[0])).y
offset = self.wall.matrix_world.to_quaternion() @ Vector((0, -wall_width, 0))
self.align(start, end, offset)
def align_first_layer(self):
recalculate_dumb_wall_origin(self.wall)
recalculate_dumb_wall_origin(self.reference_wall)
self.align_rotation()
if self.is_rotation_flipped():
DumbWallFlipper(self.wall).flip()
bpy.context.view_layer.update()
start = self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[0])
end = self.reference_wall.matrix_world @ Vector(self.reference_wall.bound_box[4])
self.align(start, end)
def align(self, start, end, offset=None):
if offset is None:
offset = Vector((0, 0, 0))
point, distance = mathutils.geometry.intersect_point_line(self.wall.matrix_world.translation, start, end)
new_origin = point + offset
self.wall.matrix_world.translation[0] = new_origin[0]
self.wall.matrix_world.translation[1] = new_origin[1]
def align_rotation(self):
reference = (self.reference_wall.matrix_world.to_quaternion() @ Vector((1, 0, 0))).to_2d()
wall = (self.wall.matrix_world.to_quaternion() @ Vector((1, 0, 0))).to_2d()
angle = reference.angle_signed(wall)
if round(degrees(angle) % 360) in (0, 180):
return
elif angle > (pi / 2):
self.wall.rotation_euler[2] -= pi - angle
else:
self.wall.rotation_euler[2] += angle
bpy.context.view_layer.update()
def is_rotation_flipped(self):
reference = (self.reference_wall.matrix_world.to_quaternion() @ Vector((1, 0, 0))).to_2d()
wall = (self.wall.matrix_world.to_quaternion() @ Vector((1, 0, 0))).to_2d()
angle = reference.angle_signed(wall)
return round(degrees(angle) % 360) == 180
class DumbWallJoiner:
# A dumb wall is a prismatic wall along its local X axis.
# Given two dumb walls, there are three types of wall joints.
# 1. T-junction joints
# 2. L-junction "butt" joints
# 3. V-junction "mitre" joints
# The algorithms that handle all joints rely on three fundamental functions.
# 1. Identify faces at either end of the wall, called "end faces".
# 2. Given an "end face", identify a side "target face" of the other wall
# to project towards.
# 3. Project the vertices of an "end face" to the "target face".
def __init__(self, wall1, wall2):
self.wall1 = wall1
self.wall2 = wall2
self.should_project_to_frontface = True
self.should_attempt_v_junction_projection = False
self.initialise_convenience_variables()
def initialise_convenience_variables(self):
self.wall1_matrix = self.wall1.matrix_world
self.wall2_matrix = self.wall2.matrix_world
self.pos_x = self.wall1_matrix.to_quaternion() @ Vector((1, 0, 0))
self.neg_x = self.wall1_matrix.to_quaternion() @ Vector((-1, 0, 0))
# Unjoining a wall geometrically means to flatten the ends of the wall to
# remove any mitred angle from it.
def unjoin(self):
wall1_min_faces, wall1_max_faces = self.get_wall_end_faces(self.wall1)
min_x = min([v[0] for v in self.wall1.bound_box])
max_x = max([v[0] for v in self.wall1.bound_box])
for face in wall1_min_faces:
for v in face.vertices:
self.wall1.data.vertices[v].co[0] = min_x
for face in wall1_max_faces:
for v in face.vertices:
self.wall1.data.vertices[v].co[0] = max_x
self.recalculate_origins()
# A T-junction is an ordered operation where a single end of wall1 is joined
# to wall2 if possible (i.e. walls aren't parallel). Wall2 is not modified.
# First, wall1 end faces are identified. We attempt to project an end face
# at both ends to a front face of wall2. We then choose the end face that
# has the shortest projection distance, and project it.
def join_T(self):
self._join_T()
self.recalculate_origins()
def _join_T(self):
wall1_min_faces, wall1_max_faces = self.get_wall_end_faces(self.wall1)
wall2_end_faces1, wall2_end_faces2 = self.get_wall_end_faces(self.wall2)
self.wall2_end_faces = wall2_end_faces1 + wall2_end_faces2
ef1_distance, ef1_target_frontface, ef1_target_backface = self.get_projection_target(wall1_min_faces, 1)
ef2_distance, ef2_target_frontface, ef2_target_backface = self.get_projection_target(wall1_max_faces, 2)
# Large distances probably means rounding issues which lead to very long projections
if ef1_distance and ef1_distance > 50:
ef1_distance = None
if ef2_distance and ef2_distance > 50:
ef2_distance = None
# Project only the end faces that are closer to their target
if ef1_distance and ef2_distance is None:
self.project_end_faces(wall1_min_faces, ef1_target_frontface, ef1_target_backface)
return (wall1_min_faces, ef1_target_frontface, ef1_target_backface)
elif ef2_distance and ef1_distance is None:
self.project_end_faces(wall1_max_faces, ef2_target_frontface, ef2_target_backface)
return (wall1_max_faces, ef2_target_frontface, ef2_target_backface)
elif ef1_distance is None and ef2_distance is None:
return (None, None, None) # Life is short. BIM is hard.
elif ef1_distance < ef2_distance:
self.project_end_faces(wall1_min_faces, ef1_target_frontface, ef1_target_backface)
return (wall1_min_faces, ef1_target_frontface, ef1_target_backface)
else:
self.project_end_faces(wall1_max_faces, ef2_target_frontface, ef2_target_backface)
return (wall1_max_faces, ef2_target_frontface, ef2_target_backface)
# An L-junction is ordered operation where a single end of wall1 is joined
# to the backface of a side of wall2, and then a single end of wall2 is
# joined back to wall1 as a regular T-junction.
def join_L(self):
self.should_project_to_frontface = False
self._join_T()
self.swap_walls()
self.should_project_to_frontface = True
self._join_T()
self.recalculate_origins()
# A V-junction is an unordered operation where wall1 is joined to wall2,
# then vice versa. First, we do a T-junction from wall1 to wall2, then vice
# versa. This creates a junction where the inner vertices of the mitre joint
# touches, but the outer vertices do not. So, we just loop through the end
# point vertices of each wall, find outer vertices (i.e. vertices that don't
# touch the other wall), then continue projecting those to the back face of
# the other wall.
def join_V(self):
wall2_end_faces, wall2_target_frontface, wall2_target_backface = self._join_T()
self.swap_walls()
wall1_end_faces, wall1_target_frontface, wall1_target_backface = self._join_T()
for face in wall1_end_faces or []:
for v in face.vertices:
global_co = self.wall1_matrix @ self.wall1.data.vertices[v].co
if self.wall2.closest_point_on_mesh(self.wall2_matrix.inverted() @ global_co, distance=0.001)[0]:
continue # Vertex is already coincident with other wall, do not mitre
target_face_center = self.wall2_matrix @ wall1_target_backface.center
target_face_normal = (self.wall2_matrix.to_quaternion() @ wall1_target_backface.normal).normalized()
self.project_vertex(v, target_face_center, target_face_normal, self.wall1, self.wall1_matrix)
self.swap_walls()
for face in wall2_end_faces or []:
for v in face.vertices:
global_co = self.wall1_matrix @ self.wall1.data.vertices[v].co
if self.wall2.closest_point_on_mesh(self.wall2_matrix.inverted() @ global_co, distance=0.001)[0]:
continue # Vertex is already coincident with other wall, do not mitre
target_face_center = self.wall2_matrix @ wall2_target_backface.center
target_face_normal = (self.wall2_matrix.to_quaternion() @ wall2_target_backface.normal).normalized()
self.project_vertex(v, target_face_center, target_face_normal, self.wall1, self.wall1_matrix)
self.recalculate_origins()
def recalculate_origins(self):
bpy.context.view_layer.update()
recalculate_dumb_wall_origin(self.wall1)
recalculate_dumb_wall_origin(self.wall2)
def swap_walls(self):
self.wall1, self.wall2 = self.wall2, self.wall1
self.initialise_convenience_variables()
def project_end_faces(self, end_faces, target_frontface, target_backface):
target_face = target_frontface if self.should_project_to_frontface else target_backface
target_face_center = self.wall2_matrix @ target_face.center
target_face_normal = (self.wall2_matrix.to_quaternion() @ target_face.normal).normalized()
for end_face in end_faces:
for v in end_face.vertices:
self.project_vertex(v, target_face_center, target_face_normal, self.wall1, self.wall1_matrix)
def project_vertex(self, v, target_face_center, target_face_normal, wall, wall_matrix):
original_point = wall_matrix @ wall.data.vertices[v].co
point = mathutils.geometry.intersect_line_plane(
original_point,
(original_point) + self.pos_x,
target_face_center,
target_face_normal,
)
if not point or (point - original_point).length > 50:
return
local_point = wall_matrix.inverted() @ point
wall.data.vertices[v].co = local_point
# A projection target face is a side face on the target wall that has a
# significant local Y component to its normal (i.e. is not pointing up or
# down or something). In addition, its plane must intersect with the
# projection vector of an end face. Finally, the projection vector and the
# normal of the target face must not be acute.
def get_projection_target(self, end_faces, which_end):
if not end_faces:
return (None, None, None)
# Get a single end face as a sample.
f1 = end_faces[0]
f1_center = self.wall1_matrix @ f1.center
if which_end == 1:
outwards = self.neg_x
inwards = self.pos_x
elif which_end == 2:
outwards = self.pos_x
inwards = self.neg_x
distance = None
target_frontface = None
target_backface = None
for f2 in self.wall2.data.polygons:
if abs(f2.normal.y) < 0.75:
continue # Probably not a side wall
if f2 in self.wall2_end_faces:
continue
# Can we project the end face to the target face?
f2_center = self.wall2_matrix @ f2.center
f1_center_offset_x = f1_center + outwards
f2_normal = (self.wall2_matrix.to_quaternion() @ f2.normal).normalized()
point = mathutils.geometry.intersect_line_plane(
f1_center,
f1_center_offset_x,
f2_center,
f2_normal,
)
if not point:
continue # We can't project to the face at all
intersection_point, signed_distance = mathutils.geometry.intersect_point_line(
point, f1_center, f1_center_offset_x
)
raycast_direction = outwards if signed_distance > 0 else inwards
if raycast_direction == outwards and f2_normal.angle(raycast_direction) < math.pi / 2:
target_backface = f2 # f2 is on the wrong side of the wall
elif raycast_direction == inwards and f2_normal.angle(raycast_direction) > math.pi / 2:
target_backface = f2 # f2 is on the wrong side of the wall
else:
target_frontface = f2
distance = (point - f1_center).length
if distance is not None and target_frontface is not None and target_backface is not None:
return (distance, target_frontface, target_backface)
return (None, None, None)
# An end face is a set of faces that represents either one end of the wall or
# the other. There is typically only 1 quad or 2 tris for each end.
# An end face is defined as having at least one vertex on either extreme
# X-axis, and a non-insignificant X component of its face normal
def get_wall_end_faces(self, wall):
min_faces = []
max_faces = []
min_x = min([v[0] for v in wall.bound_box])
max_x = max([v[0] for v in wall.bound_box])
for f in wall.data.polygons:
end_face_index = self.get_wall_face_end(wall, f, min_x, max_x)
if end_face_index == 1:
min_faces.append(f)
elif end_face_index == 2:
max_faces.append(f)
return (min_faces, max_faces)
# 1 is the leftmost (minimum local X axis) end, and 2 is the rightmost end
def get_wall_face_end(self, wall, face, min_x, max_x):
for v in face.vertices:
if wall.data.vertices[v].co.x == min_x and abs(face.normal.x) > 0.1:
return 1
if wall.data.vertices[v].co.x == max_x and abs(face.normal.x) > 0.1:
return 2
class DumbWallGenerator:
def __init__(self, relating_type):
self.relating_type = relating_type
def generate(self):
self.file = IfcStore.get_file()
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
thicknesses = []
for rel in self.relating_type.HasAssociations:
if rel.is_a("IfcRelAssociatesMaterial"):
material = rel.RelatingMaterial
if material.is_a("IfcMaterialLayerSet"):
thicknesses = [l.LayerThickness for l in material.MaterialLayers]
break
if not thicknesses:
return
self.collection = bpy.context.view_layer.active_layer_collection.collection
self.collection_obj = bpy.data.objects.get(self.collection.name)
self.width = sum(thicknesses) * unit_scale
self.height = 3
self.length = 1
self.rotation = 0
self.location = Vector((0, 0, 0))
if self.has_sketch():
return self.derive_from_sketch()
return self.derive_from_cursor()
def has_sketch(self):
return (
bpy.context.scene.grease_pencil
and len(bpy.context.scene.grease_pencil.layers) == 1
and bpy.context.scene.grease_pencil.layers[0].active_frame.strokes
)
def derive_from_sketch(self):
objs = []
strokes = []
layer = bpy.context.scene.grease_pencil.layers[0]
for stroke in layer.active_frame.strokes:
if len(stroke.points) == 1:
continue
coords = (stroke.points[0].co, stroke.points[-1].co)
direction = coords[1] - coords[0]
length = direction.length
if length < 0.1:
continue
data = {"coords": coords}
# Round to nearest 50mm (yes, metric for now)
self.length = 0.05 * round(length / 0.05)
self.rotation = math.atan2(direction[1], direction[0])
# Round to nearest 5 degrees
nearest_degree = (math.pi / 180) * 5
self.rotation = nearest_degree * round(self.rotation / nearest_degree)
self.location = coords[0]
data["obj"] = self.create_wall()
strokes.append(data)
objs.append(data["obj"])
if len(objs) < 2:
return objs
l_joins = set()
for stroke in strokes:
if not stroke["obj"]:
continue
for stroke2 in strokes:
if stroke2 == stroke or not stroke2["obj"]:
continue
if self.has_nearby_ends(stroke, stroke2):
wall_join = "-JOIN-".join(sorted([stroke["obj"].name, stroke2["obj"].name]))
if wall_join not in l_joins:
l_joins.add(wall_join)
DumbWallJoiner(stroke["obj"], stroke2["obj"]).join_L()
elif self.has_end_near_stroke(stroke, stroke2):
DumbWallJoiner(stroke["obj"], stroke2["obj"]).join_T()
bpy.context.scene.grease_pencil.layers.remove(layer)
return objs
def has_end_near_stroke(self, stroke, stroke2):
point, distance = mathutils.geometry.intersect_point_line(stroke["coords"][0], *stroke2["coords"])
if distance > 0 and distance < 1 and self.is_near(point, stroke["coords"][0]):
return True
point, distance = mathutils.geometry.intersect_point_line(stroke["coords"][1], *stroke2["coords"])
if distance > 0 and distance < 1 and self.is_near(point, stroke["coords"][1]):
return True
def has_nearby_ends(self, stroke, stroke2):
return (
self.is_near(stroke["coords"][0], stroke2["coords"][0])
or self.is_near(stroke["coords"][0], stroke2["coords"][1])
or self.is_near(stroke["coords"][1], stroke2["coords"][0])
or self.is_near(stroke["coords"][1], stroke2["coords"][1])
)
def is_near(self, point1, point2):
return (point1 - point2).length < 0.1
def derive_from_cursor(self):
self.location = bpy.context.scene.cursor.location
if self.collection:
for sibling_obj in self.collection.objects:
if not isinstance(sibling_obj.data, bpy.types.Mesh):
continue
if "IfcWall" not in sibling_obj.name:
continue
local_location = sibling_obj.matrix_world.inverted() @ self.location
raycast = sibling_obj.closest_point_on_mesh(local_location, distance=0.01)
if not raycast[0]:
continue
for face in sibling_obj.data.polygons:
if (
abs(face.normal.y) >= 0.75
and abs(mathutils.geometry.distance_point_to_plane(local_location, face.center, face.normal))
< 0.01
):
# Rotate the wall in the direction of the face normal
normal = (sibling_obj.matrix_world.to_quaternion() @ face.normal).normalized()
self.rotation = math.atan2(normal[1], normal[0])
break
return self.create_wall()
def create_wall(self):
verts = [
Vector((0, self.width, 0)),
Vector((0, 0, 0)),
Vector((0, self.width, self.height)),
Vector((0, 0, self.height)),
Vector((self.length, self.width, 0)),
Vector((self.length, 0, 0)),
Vector((self.length, self.width, self.height)),
Vector((self.length, 0, self.height)),
]
faces = [
[1, 3, 2, 0],
[4, 6, 7, 5],
[1, 0, 4, 5],
[3, 7, 6, 2],
[0, 2, 6, 4],
[1, 5, 7, 3],
]
mesh = bpy.data.meshes.new(name="Wall")
mesh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new("Wall", mesh)
obj.location = self.location
obj.rotation_euler[2] = self.rotation
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2]
self.collection.objects.link(obj)
bpy.ops.bim.assign_class(obj=obj.name, ifc_class="IfcWall")
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
pset = ifcopenshell.api.run("pset.add_pset", self.file, product=element, name="EPset_Parametric")
ifcopenshell.api.run("pset.edit_pset", self.file, pset=pset, properties={"Engine": "BlenderBIM.DumbWall"})
MaterialData.load(self.file)
obj.select_set(True)
return obj
def generate_axis(usecase_path, ifc_file, **settings):
axis_context = ifcopenshell.util.representation.get_context(ifc_file, "Model", "Axis", "GRAPH_VIEW")
if not axis_context:
return
obj = settings["blender_object"]
product = ifc_file.by_id(obj.BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbWall":
return
old_axis = ifcopenshell.util.representation.get_representation(product, "Model", "Axis", "GRAPH_VIEW")
if settings["context"].ContextType == "Model" and getattr(settings["context"], "ContextIdentifier") == "Body":
if old_axis:
bpy.ops.bim.remove_representation(representation_id=old_axis.id(), obj=obj.name)
new_settings = settings.copy()
new_settings["context"] = axis_context
mesh = bpy.data.meshes.new("Temporary Axis")
start = Vector(obj.bound_box[0])
end = Vector(obj.bound_box[4])
mesh.from_pydata([start, end], [(0, 1)], [])
new_settings["geometry"] = mesh
new_axis = ifcopenshell.api.run(
"geometry.add_representation", ifc_file, should_run_listeners=False, **new_settings
)
ifcopenshell.api.run(
"geometry.assign_representation",
ifc_file,
should_run_listeners=False,
**{"product": product, "representation": new_axis}
)
bpy.data.meshes.remove(mesh)
def calculate_quantities(usecase_path, ifc_file, **settings):
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
obj = settings["blender_object"]
product = ifc_file.by_id(obj.BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbWall":
return
qto = ifcopenshell.api.run(
"pset.add_qto", ifc_file, should_run_listeners=False, product=product, name="Qto_WallBaseQuantities"
)
length = obj.dimensions[0] / unit_scale
width = obj.dimensions[1] / unit_scale
height = obj.dimensions[2] / unit_scale
if product.HasOpenings:
# TODO: calculate gross / net
gross_volume = 0
net_volume = 0
else:
bm = bmesh.new()
bm.from_mesh(obj.data)
gross_volume = bm.calc_volume()
net_volume = gross_volume
bm.free()
ifcopenshell.api.run(
"pset.edit_qto",
ifc_file,
should_run_listeners=False,
qto=qto,
properties={
"Length": round(length, 2),
"Width": round(width, 2),
"Height": round(height, 2),
"GrossVolume": round(gross_volume, 2),
"NetVolume": round(net_volume, 2),
},
)
PsetData.load(ifc_file, obj.BIMObjectProperties.ifc_definition_id)
class DumbWallPlaner:
def regenerate_from_layer(self, usecase_path, ifc_file, **settings):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
layer = settings["layer"]
thickness = settings["attributes"].get("LayerThickness")
if thickness is None or layer.LayerThickness == thickness:
return
delta_thickness = thickness - layer.LayerThickness
for layer_set in layer.ToMaterialLayerSet:
total_thickness = sum([l.LayerThickness for l in layer_set.MaterialLayers])
if not total_thickness:
continue
for inverse in ifc_file.get_inverse(layer_set):
if not inverse.is_a("IfcMaterialLayerSetUsage"):
continue
if ifc_file.schema == "IFC2X3":
for rel in ifc_file.get_inverse(inverse):
if not rel.is_a("IfcRelAssociatesMaterial"):
continue
for element in rel.RelatedObjects:
self.change_thickness(element, delta_thickness)
else:
for rel in inverse.AssociatedTo:
for element in rel.RelatedObjects:
self.change_thickness(element, delta_thickness)
def regenerate_from_type(self, usecase_path, ifc_file, **settings):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
new_material = ifcopenshell.util.element.get_material(settings["relating_type"])
if not new_material.is_a("IfcMaterialLayerSet"):
return
obj = IfcStore.get_element(settings["related_object"].id())
if not obj:
return
current_thickness = obj.dimensions.y / self.unit_scale
new_thickness = sum([l.LayerThickness for l in new_material.MaterialLayers])
if current_thickness == new_thickness:
return
self.change_thickness(settings["related_object"], new_thickness - current_thickness)
def change_thickness(self, element, delta_thickness):
parametric = ifcopenshell.util.element.get_psets(element).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbWall":
return
obj = IfcStore.get_element(element.id())
if not obj:
return
bm = bmesh.new()
bm.from_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
min_face, max_face = self.get_wall_end_faces(obj, bm)
self.thicken_face(min_face, delta_thickness)
self.thicken_face(max_face, delta_thickness)
bm.to_mesh(obj.data)
obj.data.update()
bm.free()
def thicken_face(self, face, delta_thickness):
slide_magnitude = abs(delta_thickness) / 2 * self.unit_scale
for vert in face.verts:
slide_vector = None
for edge in vert.link_edges:
other_vert = edge.verts[1] if edge.verts[0] == vert else edge.verts[0]
if delta_thickness > 0:
potential_slide_vector = vert.co - other_vert.co
else:
potential_slide_vector = other_vert.co - vert.co
if abs(potential_slide_vector.x) > 0.9 or abs(potential_slide_vector.z) > 0.9:
continue
slide_vector = potential_slide_vector
break
if not slide_vector:
continue
slide_vector *= slide_magnitude / abs(slide_vector.y)
vert.co += slide_vector
# An end face is a quad that is on one end of the wall or the other. It must
# have at least one vertex on either extreme X-axis, and a non-insignificant
# X component of its face normal
def get_wall_end_faces(self, wall, bm):
min_face = None
max_face = None
min_x = min([v[0] for v in wall.bound_box])
max_x = max([v[0] for v in wall.bound_box])
bm.faces.ensure_lookup_table()
for f in bm.faces:
for v in f.verts:
if v.co.x == min_x and abs(f.normal.x) > 0.1:
min_face = f
elif v.co.x == max_x and abs(f.normal.x) > 0.1:
max_face = f
if min_face and max_face:
break
return min_face, max_face
@@ -0,0 +1,58 @@
import bpy
from bpy.types import WorkSpaceTool
class WallTool(WorkSpaceTool):
bl_space_type = "VIEW_3D"
bl_context_mode = "OBJECT"
bl_idname = "bim.wall_tool"
bl_label = "Wall Tool"
bl_description = "Gives you wall related superpowers"
bl_icon = "ops.generic.select_circle"
bl_widget = None
# https://docs.blender.org/api/current/bpy.types.KeyMapItems.html
bl_keymap = (
# ("bim.wall_tool_op", {"type": 'MOUSEMOVE', "value": 'ANY'}, {"properties": []}),
# ("mesh.add_wall", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": []}),
("bim.add_wall", {"type": "A", "value": "PRESS", "shift": True}, {"properties": []}),
("bim.join_wall", {"type": "E", "value": "PRESS", "shift": True}, {"properties": [("join_type", "T")]}),
("bim.join_wall", {"type": "T", "value": "PRESS", "shift": True}, {"properties": [("join_type", "L")]}),
("bim.join_wall", {"type": "Y", "value": "PRESS", "shift": True}, {"properties": [("join_type", "V")]}),
("bim.flip_wall", {"type": "F", "value": "PRESS", "shift": True}, {"properties": []}),
("bim.split_wall", {"type": "S", "value": "PRESS", "shift": True}, {"properties": []}),
(
"bim.align_wall",
{"type": "X", "value": "PRESS", "shift": True},
{"properties": [("align_type", "EXTERIOR")]},
),
(
"bim.align_wall",
{"type": "C", "value": "PRESS", "shift": True},
{"properties": [("align_type", "CENTERLINE")]},
),
(
"bim.align_wall",
{"type": "V", "value": "PRESS", "shift": True},
{"properties": [("align_type", "INTERIOR")]},
),
)
def draw_settings(context, layout, tool):
props = context.scene.BIMModelProperties
row = layout.row(align=True)
row.prop(props, "relating_type", text="")
row.label(text="", icon="BLANK1")
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Add", icon="EVENT_A")
row.label(text="Extend", icon="EVENT_E")
row.label(text="Butt", icon="EVENT_T")
row.label(text="Mitre", icon="EVENT_Y")
row.label(text="Flip", icon="EVENT_F")
row.label(text="Split", icon="EVENT_S")
row.label(text="", icon="EVENT_X")
row.label(text="", icon="EVENT_C")
row.label(text="", icon="EVENT_V")
row.label(text="Align")
@@ -0,0 +1,15 @@
import bpy
from . import ui, operator
classes = (
operator.ActivateParametricEngine,
ui.BIM_PT_parametric,
)
def register():
pass
def unregister():
pass
@@ -0,0 +1,10 @@
import bpy
from blenderbim.bim.ifc import IfcStore
class ActivateParametricEngine(bpy.types.Operator):
bl_idname = "bim.activate_parametric_engine"
bl_label = "Activate Parametric Engine"
def execute(self, context):
return {"FINISHED"}
@@ -0,0 +1,22 @@
from bpy.types import Panel
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.type.data import Data
class BIM_PT_parametric(Panel):
bl_label = "IFC Parametric Engines"
bl_idname = "BIM_PT_parametric"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "scene"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def draw(self, context):
#props = context.active_object.BIMTypeProperties
row = self.layout.row(align=True)
#row.prop(props, "relating_type_class", text="")
row.operator("bim.activate_parametric_engine", icon="PLUGIN")
@@ -1,3 +1,4 @@
import os
import bpy
import json
@@ -46,7 +47,7 @@ class ExecuteIfcPatch(bpy.types.Operator):
"output": context.scene.BIMPatchProperties.ifc_patch_output,
"recipe": context.scene.BIMPatchProperties.ifc_patch_recipes,
"arguments": json.loads(context.scene.BIMPatchProperties.ifc_patch_args or "[]"),
"log": context.scene.BIMProperties.data_dir + "process.log",
"log": os.path.join(context.scene.BIMProperties.data_dir, "process.log"),
}
)
return {"FINISHED"}
@@ -13,6 +13,9 @@ classes = (
operator.UnassignLibraryDeclaration,
operator.SaveLibraryFile,
operator.AppendLibraryElement,
operator.EnableEditingHeader,
operator.DisableEditingHeader,
operator.EditHeader,
prop.LibraryElement,
prop.BIMProjectProperties,
ui.BIM_PT_project,
@@ -255,3 +255,60 @@ class AppendLibraryElement(bpy.types.Operator):
ifc_importer.type_collection = type_collection
ifc_importer.create_type_product(element)
ifc_importer.place_objects_in_spatial_tree()
class EnableEditingHeader(bpy.types.Operator):
bl_idname = "bim.enable_editing_header"
bl_label = "Enable Editing Header"
def execute(self, context):
self.file = IfcStore.get_file()
props = context.scene.BIMProjectProperties
props.is_editing = True
mvd = "".join(IfcStore.get_file().wrapped_data.header.file_description.description)
if "[" in mvd:
props.mvd = mvd.split("[")[1][0:-1]
else:
props.mvd = ""
author = self.file.wrapped_data.header.file_name.author
if author:
props.author_name = author[0]
if len(author) > 1:
props.author_email = author[1]
organisation = self.file.wrapped_data.header.file_name.organization
if organisation:
props.organisation_name = organisation[0]
if len(organisation) > 1:
props.organisation_email = organisation[1]
props.authorisation = self.file.wrapped_data.header.file_name.authorization
return {"FINISHED"}
class EditHeader(bpy.types.Operator):
bl_idname = "bim.edit_header"
bl_label = "Edit Header"
def execute(self, context):
self.file = IfcStore.get_file()
props = context.scene.BIMProjectProperties
props.is_editing = True
self.file.wrapped_data.header.file_description.description = (f'ViewDefinition[{props.mvd}]',)
self.file.wrapped_data.header.file_name.author = (props.author_name, props.author_email)
self.file.wrapped_data.header.file_name.organization = (props.organisation_name, props.organisation_email)
self.file.wrapped_data.header.file_name.authorization = props.authorisation
bpy.ops.bim.disable_editing_header()
return {"FINISHED"}
class DisableEditingHeader(bpy.types.Operator):
bl_idname = "bim.disable_editing_header"
bl_label = "Disable Editing Header"
def execute(self, context):
context.scene.BIMProjectProperties.is_editing = False
return {"FINISHED"}
@@ -21,6 +21,13 @@ class LibraryElement(PropertyGroup):
class BIMProjectProperties(PropertyGroup):
is_authoring: BoolProperty(name="Enable Authoring Mode", default=True)
is_editing: BoolProperty(name="Is Editing", default=False)
mvd: StringProperty(name="MVD")
author_name: StringProperty(name="Author")
author_email: StringProperty(name="Author Email")
organisation_name: StringProperty(name="Organisation")
organisation_email: StringProperty(name="Organisation Email")
authorisation: StringProperty(name="Authoriser")
active_library_element: StringProperty(name="Enable Authoring Mode", default="")
library_breadcrumb: CollectionProperty(name="Library Breadcrumb", type=StrProperty)
library_elements: CollectionProperty(name="Library Elements", type=LibraryElement)
@@ -28,10 +28,40 @@ class BIM_PT_project(Panel):
row.label(text=os.path.basename(props.ifc_file) or "No File Found")
if IfcStore.get_file():
row.prop(pprops, "is_authoring", icon="GREASEPENCIL", text="")
row.prop(pprops, "is_authoring", icon="MODIFIER", text="")
if pprops.is_editing:
row.operator("bim.edit_header", icon="CHECKMARK", text="")
row.operator("bim.disable_editing_header", icon="CANCEL", text="")
else:
row.operator("bim.enable_editing_header", icon="GREASEPENCIL", text="")
row = self.layout.row(align=True)
row.label(text="IFC Schema", icon="FILE_CACHE")
row.label(text=IfcStore.get_file().schema)
if pprops.is_editing:
row = self.layout.row(align=True)
row.prop(pprops, "mvd")
row = self.layout.row(align=True)
row.prop(pprops, "author_name")
row = self.layout.row(align=True)
row.prop(pprops, "author_email")
row = self.layout.row(align=True)
row.prop(pprops, "organisation_name")
row = self.layout.row(align=True)
row.prop(pprops, "organisation_email")
row = self.layout.row(align=True)
row.prop(pprops, "authorisation")
else:
row = self.layout.row(align=True)
row.label(text="IFC MVD", icon="FILE_HIDDEN")
mvd = "".join(IfcStore.get_file().wrapped_data.header.file_description.description)
if "[" in mvd:
mvd = mvd.split("[")[1][0:-1]
row.label(text=mvd)
else:
row = self.layout.row(align=True)
row.label(text="File Not Loaded", icon="ERROR")
@@ -187,8 +187,8 @@ class EditPset(bpy.types.Operator):
self.file,
**{
"pset": self.file.by_id(pset_id),
"Name": props.active_pset_name,
"Properties": properties,
"name": props.active_pset_name,
"properties": properties,
},
)
else:
@@ -197,8 +197,8 @@ class EditPset(bpy.types.Operator):
self.file,
**{
"qto": self.file.by_id(pset_id),
"Name": props.active_pset_name,
"Properties": properties,
"name": props.active_pset_name,
"properties": properties,
},
)
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
@@ -260,7 +260,7 @@ class AddPset(bpy.types.Operator):
self.file,
**{
"product": self.file.by_id(oprops.ifc_definition_id),
"Name": pset_name,
"name": pset_name,
},
)
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
@@ -281,7 +281,7 @@ class AddQto(bpy.types.Operator):
self.file,
**{
"product": self.file.by_id(oprops.ifc_definition_id),
"Name": props.qto_name,
"name": props.qto_name,
},
)
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
@@ -1,3 +1,4 @@
import bpy
import bmesh
@@ -11,3 +12,50 @@ def calculate_volume(obj):
result = bm.calc_volume()
bm.free()
return result
def calculate_formwork_area(objs):
"""
Formwork is defined as the surface area required to cover all exposed
surfaces of one or more objects, excluding top surfaces (i.e. that have a
face normal with a significant Z component).
"""
copied_objs = []
result = 0
for obj in objs:
new_obj = obj.copy()
new_obj.data = obj.data.copy()
new_obj.animation_data_clear()
bpy.context.collection.objects.link(new_obj)
copied_objs.append(new_obj)
context_override = {}
context_override["object"] = context_override["active_object"] = copied_objs[0]
context_override["selected_objects"] = context_override["selected_editable_objects"] = copied_objs
bpy.ops.object.join(context_override)
copied_objs[0].name = "Formwork"
copied_objs[0].BIMObjectProperties.ifc_definition_id = 0
modifier = copied_objs[0].modifiers.new("Formwork", "REMESH")
modifier.mode = "SHARP"
# This hardcoded value may be optimised through a better understanding of the octree division.
# These values are based off some trial and error heuristics I've learned through experience.
max_dim = max(copied_objs[0].dimensions)
if max_dim > 45:
modifier.octree_depth = 9
elif max_dim > 35:
modifier.octree_depth = 8
elif max_dim > 12:
modifier.octree_depth = 7
elif max_dim > 5:
modifier.octree_depth = 6
else:
modifier.octree_depth = 5
mesh = copied_objs[0].evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()
for polygon in mesh.polygons:
if polygon.normal.z > 0.5:
continue
result += polygon.area
return result
@@ -69,6 +69,8 @@ class ExecuteQtoMethod(bpy.types.Operator):
elif props.qto_methods == "VOLUME":
for obj in bpy.context.selected_objects:
result += helper.calculate_volume(obj)
elif props.qto_methods == "FORMWORK":
result = helper.calculate_formwork_area(bpy.context.selected_objects)
props.qto_result = str(round(result, 3))
return {"FINISHED"}
@@ -88,6 +90,8 @@ class QuantifyObjects(bpy.types.Operator):
result = helper.calculate_height(obj)
elif props.qto_methods == "VOLUME":
result = helper.calculate_volume(obj)
elif props.qto_methods == "FORMWORK":
result = helper.calculate_formwork_area([obj])
if not result:
continue
result = round(result, 3)
@@ -95,13 +99,13 @@ class QuantifyObjects(bpy.types.Operator):
"pset.add_qto",
self.file,
product=self.file.by_id(obj.BIMObjectProperties.ifc_definition_id),
Name=props.qto_name,
name=props.qto_name,
)
ifcopenshell.api.run(
"pset.edit_qto",
self.file,
qto=qto,
Properties={props.prop_name: result}
properties={props.prop_name: result}
)
PsetData.load(self.file, obj.BIMObjectProperties.ifc_definition_id)
return {"FINISHED"}
@@ -4,6 +4,7 @@ from bpy.types import Panel
class BIM_PT_qto_utilities(Panel):
bl_idname = "BIM_PT_qto_utilities"
bl_label = "Quantity Take-off"
bl_options = {"DEFAULT_CLOSED"}
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
@@ -245,9 +245,7 @@ class CopyClass(bpy.types.Operator):
IfcStore.link_element(result, obj)
relating_type = ifcopenshell.util.element.get_type(result)
if relating_type and relating_type.RepresentationMaps:
bpy.ops.bim.map_representations(
product_id=result.id(), type_product_id=ifcopenshell.util.element.get_type(result).id()
)
bpy.ops.bim.assign_type(relating_type=relating_type.id(), related_object=obj.name)
else:
bpy.ops.bim.add_representation(obj=obj.name)
return {"FINISHED"}
@@ -1,5 +1,6 @@
import bpy
from bpy.types import Panel
from blenderbim.bim.ifc import IfcStore
class BIM_PT_search(Panel):
@@ -10,6 +11,10 @@ class BIM_PT_search(Panel):
bl_region_type = "WINDOW"
bl_context = "scene"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def draw(self, context):
props = context.scene.BIMSearchProperties
@@ -66,6 +66,10 @@ classes = (
operator.SelectTaskRelatedProducts,
operator.VisualiseWorkScheduleDate,
operator.VisualiseWorkScheduleDateRange,
operator.RecalculateSchedule,
operator.BlenderBIM_DatePicker,
operator.BlenderBIM_DatePickerSetDate,
operator.BlenderBIM_RedrawDatePicker,
prop.WorkPlan,
prop.BIMWorkPlanProperties,
prop.Task,
@@ -74,6 +78,7 @@ classes = (
prop.WorkCalendar,
prop.RecurrenceComponent,
prop.BIMWorkCalendarProperties,
prop.DatePickerProperties,
ui.BIM_PT_work_plans,
ui.BIM_PT_work_schedules,
ui.BIM_PT_work_calendars,
@@ -91,6 +96,7 @@ def register():
bpy.types.Scene.BIMWorkScheduleProperties = bpy.props.PointerProperty(type=prop.BIMWorkScheduleProperties)
bpy.types.Scene.BIMTaskTreeProperties = bpy.props.PointerProperty(type=prop.BIMTaskTreeProperties)
bpy.types.Scene.BIMWorkCalendarProperties = bpy.props.PointerProperty(type=prop.BIMWorkCalendarProperties)
bpy.types.Scene.DatePickerProperties = bpy.props.PointerProperty(type=prop.DatePickerProperties)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
@@ -99,4 +105,5 @@ def unregister():
del bpy.types.Scene.BIMWorkScheduleProperties
del bpy.types.Scene.BIMTaskTreeProperties
del bpy.types.Scene.BIMWorkCalendarProperties
del bpy.types.Scene.DatePickerProperties
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
@@ -1,3 +1,4 @@
import bpy
import math
import isodate
import datetime
@@ -5,8 +6,6 @@ from dateutil import parser
from ifcopenshell.api.sequence.data import Data
def derive_date(ifc_definition_id, attribute_name, date=None, is_earliest=False, is_latest=False):
task = Data.tasks[ifc_definition_id]
if task["TaskTime"]:
@@ -56,3 +55,23 @@ def parse_duration(value):
return isodate.parse_duration(value)
except:
return None
def canonicalise_time(time):
if not time:
return "-"
return time.strftime("%d/%m/%y")
def get_scene_prop(prop_path):
prop = bpy.context.scene.get(prop_path.split(".")[0])
for part in prop_path.split(".")[1:]:
if part:
prop = prop.get(part)
return prop
def set_scene_prop(prop_path, value):
parent = get_scene_prop(prop_path[: prop_path.rfind(".")])
prop = prop_path.split(".")[-1]
parent[prop] = value
@@ -3,6 +3,7 @@ import os
import bpy
import json
import time
import calendar
import isodate
import pystache
import webbrowser
@@ -13,7 +14,7 @@ import blenderbim.bim.helper
import blenderbim.bim.module.sequence.helper as helper
from datetime import datetime
from datetime import timedelta
from dateutil import parser
from dateutil import parser, relativedelta
from blenderbim.bim.ifc import IfcStore
from bpy_extras.io_utils import ImportHelper
from ifcopenshell.api.sequence.data import Data
@@ -660,6 +661,15 @@ class GenerateGanttChart(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
self.json = []
self.sequence_type_map = {
None: "FS",
"START_START": "SS",
"START_FINISH": "SF",
"FINISH_START": "FS",
"FINISH_FINISH": "FF",
"USERDEFINED": "FS",
"NOTDEFINED": "FS",
}
for task_id in Data.work_schedules[self.work_schedule]["RelatedObjects"]:
self.create_new_task_json(task_id)
with open(os.path.join(bpy.context.scene.BIMProperties.data_dir, "gantt", "index.html"), "w") as f:
@@ -670,23 +680,35 @@ class GenerateGanttChart(bpy.types.Operator):
def create_new_task_json(self, task_id):
task = self.file.by_id(task_id)
self.json.append(
{
"pID": task.id(),
"pName": task.Name,
"pStart": task.TaskTime.ScheduleStart if task.TaskTime else "",
"pEnd": task.TaskTime.ScheduleFinish if task.TaskTime else "",
"pPlanStart": task.TaskTime.ScheduleStart if task.TaskTime else "",
"pPlanEnd": task.TaskTime.ScheduleFinish if task.TaskTime else "",
"pClass": "ggroupblack",
"pMile": 1 if task.IsMilestone else 0,
"pComp": 0,
"pGroup": 1,
"pParent": task.Nests[0].RelatingObject.id() if task.Nests else 0,
"pOpen": 1,
"pCost": 1,
}
data = {
"pID": task.id(),
"pName": task.Name,
"pStart": task.TaskTime.ScheduleStart if task.TaskTime else "",
"pEnd": task.TaskTime.ScheduleFinish if task.TaskTime else "",
"pPlanStart": task.TaskTime.ScheduleStart if task.TaskTime else "",
"pPlanEnd": task.TaskTime.ScheduleFinish if task.TaskTime else "",
"pMile": 1 if task.IsMilestone else 0,
"pComp": 0,
"pGroup": 1 if task.IsNestedBy else 0,
"pParent": task.Nests[0].RelatingObject.id() if task.Nests else 0,
"pOpen": 1,
"pCost": 1,
}
if task.TaskTime and task.TaskTime.IsCritical:
data["pClass"] = "gtaskred"
elif data["pGroup"]:
data["pClass"] = "ggroupblack"
elif data["pMile"]:
data["pClass"] = "gmilestone"
else:
data["pClass"] = "gtaskblue"
data["pDepend"] = ",".join(
[
"{}{}".format(rel.RelatingProcess.id(), self.sequence_type_map[rel.SequenceType])
for rel in task.IsSuccessorFrom or []
]
)
self.json.append(data)
for task_id in Data.tasks[task_id]["RelatedObjects"]:
self.create_new_task_json(task_id)
@@ -1424,3 +1446,105 @@ class VisualiseWorkScheduleDateRange(bpy.types.Operator):
"STARTED": round(self.start_frame + (((start - self.start) / self.duration) * self.total_frames)),
"COMPLETED": round(self.start_frame + (((finish - self.start) / self.duration) * self.total_frames)),
}
class BlenderBIM_DatePicker(bpy.types.Operator):
bl_label = "Date Picker"
bl_idname = "bim.datepicker"
display_date: bpy.props.StringProperty(name="Display Date")
selected_date: bpy.props.StringProperty(name="Selected Date")
target_prop: bpy.props.StringProperty(name="Target date prop to set")
def execute(self, context):
helper.set_scene_prop(self.target_prop, self.selected_date)
return {"FINISHED"}
def draw(self, context):
self.selected_date = helper.get_scene_prop("DatePickerProperties.selected_date") or helper.canonicalise_time(
datetime.now()
)
current_date = parser.parse(context.scene.DatePickerProperties.display_date, dayfirst=True, fuzzy=True)
current_month = (current_date.year, current_date.month)
lines = calendar.monthcalendar(*current_month)
month_title, week_titles = calendar.month(*current_month).splitlines()[:2]
layout = self.layout
row = layout.row()
row.prop(self, "selected_date")
split = layout.split()
col = split.row()
op = col.operator("bim.redraw_datepicker", icon="TRIA_LEFT", text="")
op.action = "previous"
col = split.row()
col.label(text=month_title.strip())
col = split.row()
col.alignment = "RIGHT"
op = col.operator("bim.redraw_datepicker", icon="TRIA_RIGHT", text="")
op.action = "next"
row = layout.row(align=True)
for title in week_titles.split():
col = row.column(align=True)
col.alignment = "CENTER"
col.label(text=title.strip())
for line in lines:
row = layout.row(align=True)
for i in line:
col = row.column(align=True)
if i == 0:
col.label(text=" ")
else:
op = col.operator("bim.datepicker_setdate", text="{:2d}".format(i))
selected_date = "{}/{}/{}".format(i, current_date.month, current_date.year)
selected_date = parser.parse(selected_date, dayfirst=True, fuzzy=True)
op.selected_date = helper.canonicalise_time(selected_date)
def invoke(self, context, event):
self.display_date = helper.get_scene_prop(self.target_prop) or helper.canonicalise_time(datetime.now())
context.scene.DatePickerProperties.display_date = self.display_date
context.scene.DatePickerProperties.selected_date = self.display_date
return context.window_manager.invoke_props_dialog(self)
class BlenderBIM_DatePickerSetDate(bpy.types.Operator):
bl_label = "set date"
bl_idname = "bim.datepicker_setdate"
selected_date: bpy.props.StringProperty()
def invoke(self, context, event):
context.scene.DatePickerProperties.selected_date = self.selected_date
return {"FINISHED"}
class BlenderBIM_RedrawDatePicker(bpy.types.Operator):
bl_label = "redraw datepicker window"
bl_idname = "bim.redraw_datepicker"
action: bpy.props.StringProperty()
def invoke(self, context, event):
current_date = parser.parse(context.scene.DatePickerProperties.display_date, dayfirst=True, fuzzy=True)
if self.action == "previous":
date_to_set = current_date - relativedelta.relativedelta(months=1)
elif self.action == "next":
date_to_set = current_date + relativedelta.relativedelta(months=1)
context.scene.DatePickerProperties.display_date = helper.canonicalise_time(date_to_set)
return {"FINISHED"}
class RecalculateSchedule(bpy.types.Operator):
bl_idname = "bim.recalculate_schedule"
bl_label = "Recalculate Schedule"
work_schedule: bpy.props.IntProperty()
def execute(self, context):
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"sequence.recalculate_schedule", self.file, work_schedule=self.file.by_id(self.work_schedule)
)
Data.load(self.file)
return {"FINISHED"}
@@ -104,6 +104,7 @@ def updateTaskTimeDateTime(self, context, startfinish):
**{"task_time": task_time, "attributes": {startfinish_key: startfinish_datetime}},
)
Data.load(IfcStore.get_file())
bpy.ops.bim.load_task_properties(task=props.active_task_id)
setattr(self, startfinish, canonicalise_time(startfinish_datetime))
@@ -121,12 +122,13 @@ def updateTaskduration(self, context):
ifcopenshell.api.run(
"sequence.edit_task_time",
self.file,
**{"task_time":task_time, "attributes": {"ScheduleDuration": self.duration}},
**{"task_time": task_time, "attributes": {"ScheduleDuration": self.duration}},
)
Data.load(IfcStore.get_file())
if props.active_task_id == self.ifc_definition_id:
attribute = props.task_attributes.get("Duration")
attribute.string_value = self.duration
bpy.ops.bim.load_task_properties(task=props.active_task_id)
def updateVisualisationStart(self, context):
@@ -283,3 +285,8 @@ class BIMWorkCalendarProperties(PropertyGroup):
)
start_time: StringProperty(name="Start Time")
end_time: StringProperty(name="End Time")
class DatePickerProperties(PropertyGroup):
display_date: StringProperty()
selected_date: StringProperty()
@@ -2,6 +2,8 @@ import isodate
from bpy.types import Panel, UIList
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.sequence.data import Data
import blenderbim.bim.module.sequence.helper as helper
from datetime import datetime
class BIM_PT_work_plans(Panel):
@@ -112,6 +114,7 @@ class BIM_PT_work_schedules(Panel):
row.prop(self.props, "should_show_calendars", text="", icon="VIEW_ORTHO")
row.prop(self.props, "should_show_visualisation_ui", text="", icon="CAMERA_STEREO")
row.operator("bim.generate_gantt_chart", text="", icon="NLA").work_schedule = work_schedule_id
row.operator("bim.recalculate_schedule", text="", icon="FILE_REFRESH").work_schedule = work_schedule_id
row.operator("bim.add_summary_task", text="", icon="ADD").work_schedule = work_schedule_id
row.operator("bim.disable_editing_work_schedule", text="", icon="CANCEL")
elif self.props.active_work_schedule_id:
@@ -133,8 +136,12 @@ class BIM_PT_work_schedules(Panel):
def draw_visualisation_ui(self):
row = self.layout.row(align=True)
row.prop(self.props, "visualisation_start", text="", icon="REW")
row.prop(self.props, "visualisation_finish", text="", icon="FF")
target_prop = "BIMWorkScheduleProperties.visualisation_start"
op = row.operator("bim.datepicker", text=helper.get_scene_prop(target_prop), icon="REW")
op.target_prop = target_prop
target_prop = "BIMWorkScheduleProperties.visualisation_finish"
op = row.operator("bim.datepicker", text=helper.get_scene_prop(target_prop), icon="FF")
op.target_prop = target_prop
op = row.operator("bim.visualise_work_schedule_date", text="", icon="RESTRICT_RENDER_OFF")
op.work_schedule = self.props.active_work_schedule_id
op = row.operator("bim.visualise_work_schedule_date_range", text="", icon="OUTLINER_OB_CAMERA")
@@ -38,7 +38,7 @@ class AssignContainer(bpy.types.Operator):
aggregate_collection = bpy.data.collections.get(related_element.name)
relating_structure_obj = IfcStore.id_map.get(relating_structure)
relating_structure_obj = IfcStore.get_element(relating_structure)
relating_collection = None
if relating_structure_obj:
relating_collection = bpy.data.collections.get(relating_structure_obj.name)
@@ -47,6 +47,7 @@ def draw_boundary_condition_editable_ui(layout, props):
if attribute.is_optional:
row.prop(attribute, "is_null", icon="RADIOBUT_OFF" if attribute.is_null else "RADIOBUT_ON", text="")
def draw_boundary_condition_read_only_ui(layout, boundary_condition_data):
for key, value in boundary_condition_data.items():
if key == "id" or key == "type" or value == None:
@@ -59,7 +60,6 @@ def draw_boundary_condition_read_only_ui(layout, boundary_condition_data):
row.label(text=str(value))
class BIM_PT_structural_boundary_conditions(Panel):
bl_label = "IFC Structural Boundary Conditions"
bl_idname = "BIM_PT_structural_boundary_conditions"
@@ -231,7 +231,9 @@ class BIM_PT_structural_connection(Panel):
row.prop(self.props, "ccs_z_angle", text="Z Angle")
else:
row = self.layout.row()
row.operator("bim.enable_editing_structural_connection_cs", text="Edit Connection CS", icon="GREASEPENCIL")
row.operator(
"bim.enable_editing_structural_connection_cs", text="Edit Connection CS", icon="GREASEPENCIL"
)
else:
row = self.layout.row()
row.label(text="TODO")
@@ -417,7 +419,6 @@ class BIM_PT_structural_load_cases(Panel):
)
class BIM_UL_structural_activities(UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if item:
@@ -444,9 +445,7 @@ class BIM_PT_structural_loads(Panel):
self.props = context.scene.BIMStructuralProperties
row = self.layout.row(align=True)
row.label(
text="{} Structural Loads Found".format(len(Data.structural_loads)), icon="GHOST_ENABLED"
)
row.label(text="{} Structural Loads Found".format(len(Data.structural_loads)), icon="GHOST_ENABLED")
if self.props.is_editing_loads:
row.prop(self.props, "structural_load_types", text="")
row.operator("bim.add_structural_load", text="", icon="ADD").ifc_class = self.props.structural_load_types
@@ -11,9 +11,9 @@ def get_colour_settings(material):
transparency = bsdf.inputs["Alpha"].default_value
diffuse_colour = bsdf.inputs["Base Color"].default_value
return {
"SurfaceColour": material.diffuse_color,
"Transparency": transparency,
"DiffuseColour": diffuse_colour,
"surface_colour": tuple(material.diffuse_color),
"transparency": transparency,
"diffuse_colour": tuple(diffuse_colour),
}
@@ -40,7 +40,7 @@ class AddStyle(bpy.types.Operator):
self.file = IfcStore.get_file()
material = bpy.data.materials.get(self.material) if self.material else bpy.context.active_object.active_material
settings = get_colour_settings(material)
settings["Name"] = material.name
settings["name"] = material.name
settings["external_definition"] = None # TODO: Implement. See #1222
style = ifcopenshell.api.run("style.add_style", self.file, **settings)
material.BIMMaterialProperties.ifc_style_id = int(style.id())
@@ -7,17 +7,17 @@ classes = (
operator.EnableEditingType,
operator.DisableEditingType,
operator.SelectSimilarType,
operator.AddTypeInstance,
prop.BIMTypeProperties,
prop.BIMTypeObjectProperties,
ui.BIM_PT_type,
)
def register():
bpy.types.Object.BIMTypeProperties = bpy.props.PointerProperty(type=prop.BIMTypeProperties)
bpy.types.VIEW3D_MT_mesh_add.append(ui.add_object_button)
bpy.types.Scene.BIMTypeProperties = bpy.props.PointerProperty(type=prop.BIMTypeProperties)
bpy.types.Object.BIMTypeProperties = bpy.props.PointerProperty(type=prop.BIMTypeObjectProperties)
def unregister():
del bpy.types.Scene.BIMTypeProperties
del bpy.types.Object.BIMTypeProperties
bpy.types.VIEW3D_MT_mesh_add.remove(ui.add_object_button)
@@ -4,8 +4,8 @@ import ifcopenshell.util.type
import ifcopenshell.api
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.type.data import Data
from blenderbim.bim.module.type.prop import getIfcTypes, getAvailableTypes, updateTypeInstanceIfcClass
from mathutils import Vector
from ifcopenshell.api.geometry.data import Data as GeometryData
from ifcopenshell.api.material.data import Data as MaterialData
class AssignType(bpy.types.Operator):
@@ -31,10 +31,22 @@ class AssignType(bpy.types.Operator):
},
)
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
if self.file.by_id(relating_type).RepresentationMaps:
bpy.ops.bim.map_representations(product_id=oprops.ifc_definition_id, type_product_id=relating_type)
GeometryData.load(IfcStore.get_file(), oprops.ifc_definition_id)
MaterialData.load(IfcStore.get_file(), oprops.ifc_definition_id)
representation_ids = GeometryData.products[oprops.ifc_definition_id]
if not representation_ids:
pass # TODO: clear geometry? Make void? Make none type?
has_switched = False
for representation_id in representation_ids:
representation = GeometryData.representations[representation_id]
if representation["ContextOfItems"]["ContextIdentifier"] == "Body":
bpy.ops.bim.switch_representation(obj=related_object.name, ifc_definition_id=representation_id)
has_switched = True
if not has_switched and representation_ids:
bpy.ops.bim.switch_representation(obj=related_object.name, ifc_definition_id=representation_id)
bpy.ops.bim.disable_editing_type(obj=related_object.name)
MaterialData.load(self.file)
return {"FINISHED"}
@@ -104,47 +116,3 @@ class SelectSimilarType(bpy.types.Operator):
if obj.BIMObjectProperties.ifc_definition_id in related_objects:
obj.select_set(True)
return {"FINISHED"}
class AddTypeInstance(bpy.types.Operator):
bl_idname = "bim.add_type_instance"
bl_label = "Add Type Instance"
ifc_class: bpy.props.EnumProperty(items=getIfcTypes, name="IFC Class", update=updateTypeInstanceIfcClass)
relating_type: bpy.props.EnumProperty(items=getAvailableTypes, name="Relating Type")
def execute(self, context):
if not self.ifc_class or not self.relating_type:
return {"FINISHED"}
# A cube
verts = [
Vector((-1, -1, -1)),
Vector((-1, -1, 1)),
Vector((-1, 1, -1)),
Vector((-1, 1, 1)),
Vector((1, -1, -1)),
Vector((1, -1, 1)),
Vector((1, 1, -1)),
Vector((1, 1, 1)),
]
edges = []
faces = [
[0, 2, 3, 1],
[2, 3, 7, 6],
[4, 5, 7, 6],
[0, 1, 5, 4],
[1, 3, 7, 5],
]
mesh = bpy.data.meshes.new(name="Instance")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Instance", mesh)
obj.location = context.scene.cursor.location
context.view_layer.active_layer_collection.collection.objects.link(obj)
self.file = IfcStore.get_file()
instance_class = ifcopenshell.util.type.get_applicable_entities(self.ifc_class, self.file.schema)[0]
bpy.ops.bim.assign_class(obj=obj.name, ifc_class=instance_class)
bpy.ops.bim.assign_type(relating_type=int(self.relating_type), related_object=obj.name)
return {"FINISHED"}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
@@ -88,6 +88,11 @@ def updateTypeDropdowns(self, context):
class BIMTypeProperties(PropertyGroup):
ifc_class: bpy.props.EnumProperty(items=getIfcTypes, name="IFC Class", update=updateTypeInstanceIfcClass)
relating_type: bpy.props.EnumProperty(items=getAvailableTypes, name="Relating Type")
class BIMTypeObjectProperties(PropertyGroup):
is_editing_type: BoolProperty(name="Is Editing Type", update=updateTypeDropdowns)
relating_type_class: EnumProperty(items=getApplicableTypes, name="Relating Type Class")
relating_type: EnumProperty(items=getRelatingTypes, name="Relating Type")
File diff suppressed because it is too large Load Diff
+28 -274
View File
@@ -1,14 +1,9 @@
import json
import os
from pathlib import Path
import bpy
import json
import importlib
import ifcopenshell
from . import export_ifc
from . import schema
from . import ifc
import blenderbim.bim.module.drawing.annotation as annotation
from . import decoration
import bpy
import ifcopenshell.util.pset
from blenderbim.bim.handler import purge_module_data
from blenderbim.bim.ifc import IfcStore
from bpy.types import PropertyGroup
@@ -25,14 +20,26 @@ from bpy.props import (
cwd = os.path.dirname(os.path.realpath(__file__))
diagram_scales_enum = []
titleblocks_enum = []
materialpsetnames_enum = []
contexts_enum = []
subcontexts_enum = []
target_views_enum = []
sheets_enum = []
vector_styles_enum = []
def getAttributeEnumValues(self, context):
return [(e, e, "") for e in json.loads(self.enum_items)]
def updateSchemaDir(self, context):
import blenderbim.bim.schema
blenderbim.bim.schema.ifc.schema_dir = context.scene.BIMProperties.schema_dir
def updateDataDir(self, context):
import blenderbim.bim.schema
blenderbim.bim.schema.ifc.data_dir = context.scene.BIMProperties.data_dir
def updateIfcFile(self, context):
@@ -42,114 +49,11 @@ def updateIfcFile(self, context):
purge_module_data()
def getDiagramScales(self, context):
global diagram_scales_enum
if (
len(diagram_scales_enum) < 1
or (bpy.context.scene.unit_settings.system == "IMPERIAL" and len(diagram_scales_enum) == 13)
or (bpy.context.scene.unit_settings.system == "METRIC" and len(diagram_scales_enum) == 31)
):
if bpy.context.scene.unit_settings.system == "IMPERIAL":
diagram_scales_enum = [
("CUSTOM", "Custom", ""),
("1'=1'-0\"|1/1", "1'=1'-0\"", ""),
('6"=1\'-0"|1/6', '6"=1\'-0"', ""),
('1-1/2"=1\'-0"|1/8', '1-1/2"=1\'-0"', ""),
('1"=1\'-0"|1/12', '1"=1\'-0"', ""),
('3/4"=1\'-0"|1/16', '3/4"=1\'-0"', ""),
('1/2"=1\'-0"|1/24', '1/2"=1\'-0"', ""),
('3/8"=1\'-0"|1/32', '3/8"=1\'-0"', ""),
('1/4"=1\'-0"|1/48', '1/4"=1\'-0"', ""),
('3/16"=1\'-0"|1/64', '3/16"=1\'-0"', ""),
('1/8"=1\'-0"|1/96', '1/8"=1\'-0"', ""),
('3/32"=1\'-0"|1/128', '3/32"=1\'-0"', ""),
('1/16"=1\'-0"|1/192', '1/16"=1\'-0"', ""),
('1/32"=1\'-0"|1/384', '1/32"=1\'-0"', ""),
('1/64"=1\'-0"|1/768', '1/64"=1\'-0"', ""),
('1/128"=1\'-0"|1/1536', '1/128"=1\'-0"', ""),
("1\"=10'|1/120", "1\"=10'", ""),
("1\"=20'|1/240", "1\"=20'", ""),
("1\"=30'|1/360", "1\"=30'", ""),
("1\"=40'|1/480", "1\"=40'", ""),
("1\"=50'|1/600", "1\"=50'", ""),
("1\"=60'|1/720", "1\"=60'", ""),
("1\"=70'|1/840", "1\"=70'", ""),
("1\"=80'|1/960", "1\"=80'", ""),
("1\"=90'|1/1080", "1\"=90'", ""),
("1\"=100'|1/1200", "1\"=100'", ""),
("1\"=150'|1/1800", "1\"=150'", ""),
("1\"=200'|1/2400", "1\"=200'", ""),
("1\"=300'|1/3600", "1\"=300'", ""),
("1\"=400'|1/4800", "1\"=400'", ""),
("1\"=500'|1/6000", "1\"=500'", ""),
]
else:
diagram_scales_enum = [
("CUSTOM", "Custom", ""),
("1:5000|1/5000", "1:5000", ""),
("1:2000|1/2000", "1:2000", ""),
("1:1000|1/1000", "1:1000", ""),
("1:500|1/500", "1:500", ""),
("1:200|1/200", "1:200", ""),
("1:100|1/100", "1:100", ""),
("1:50|1/50", "1:50", ""),
("1:20|1/20", "1:20", ""),
("1:10|1/10", "1:10", ""),
("1:5|1/5", "1:5", ""),
("1:2|1/2", "1:2", ""),
("1:1|1/1", "1:1", ""),
]
return diagram_scales_enum
def updateDrawingName(self, context):
if not self.camera:
return
if self.camera.name == self.name:
return
self.camera.name = "IfcGroup/{}".format(self.name)
self.camera.users_collection[0].name = self.camera.name
self.name = self.camera.name.split("/")[1]
def refreshActiveDrawingIndex(self, context):
bpy.ops.bim.activate_view(drawing_index=context.scene.DocProperties.active_drawing_index)
def getAttributeEnumValues(self, context):
return [(e, e, "") for e in json.loads(self.enum_items)]
def getTitleblocks(self, context):
global titleblocks_enum
if len(titleblocks_enum) < 1:
titleblocks_enum.clear()
for filename in Path(os.path.join(context.scene.BIMProperties.data_dir, "templates", "titleblocks")).glob(
"*.svg"
):
f = str(filename.stem)
titleblocks_enum.append((f, f, ""))
return titleblocks_enum
def refreshTitleblocks(self, context):
global titleblocks_enum
titleblocks_enum.clear()
getTitleblocks(self, context)
def toggleDecorations(self, context):
toggle = self.should_draw_decorations
if toggle:
decoration.DecorationsHandler.install(context)
else:
decoration.DecorationsHandler.uninstall()
def getMaterialPsetNames(self, context):
global materialpsetnames_enum
materialpsetnames_enum.clear()
pset_names = schema.ifc.psetqto.get_applicable_names("IfcMaterial", pset_only=True)
psetqto = ifcopenshell.util.pset.get_template("IFC4")
pset_names = psetqto.get_applicable_names("IfcMaterial", pset_only=True)
materialpsetnames_enum.extend([(p, p, "") for p in pset_names])
return materialpsetnames_enum
@@ -190,6 +94,7 @@ def getSubcontexts(self, context):
"CoG",
"Profile",
"SurveyPoints",
"Lighting",
]
for subcontext in subcontexts:
subcontexts_enum.append((subcontext, subcontext, ""))
@@ -215,29 +120,10 @@ def getTargetViews(self, context):
return target_views_enum
def getVectorStyles(self, context):
global vector_styles_enum
if len(vector_styles_enum) < 1:
sheets_enum.clear()
for filename in Path(os.path.join(context.scene.BIMProperties.data_dir, "styles")).glob("*.css"):
f = str(filename.stem)
vector_styles_enum.append((f, f, ""))
return vector_styles_enum
def refreshFontSize(self, context):
annotation.Annotator.resize_text(context.active_object)
class StrProperty(PropertyGroup):
pass
class Variable(PropertyGroup):
name: StringProperty(name="Name")
prop_key: StringProperty(name="Property Key")
def updateAttributeStringValue(self, context):
updateAttributeValue(self, self.string_value)
@@ -276,132 +162,13 @@ class Attribute(PropertyGroup):
enum_value: EnumProperty(items=getAttributeEnumValues, name="Value", update=updateAttributeEnumValue)
class Drawing(PropertyGroup):
name: StringProperty(name="Name", update=updateDrawingName)
camera: PointerProperty(name="Camera", type=bpy.types.Object)
class Schedule(PropertyGroup):
name: StringProperty(name="Name")
file: StringProperty(name="File")
class Sheet(PropertyGroup):
def set_name(self, new):
old = self.get("name")
path = os.path.join(bpy.context.scene.BIMProperties.data_dir, "sheets")
if old and os.path.isfile(os.path.join(path, old + ".svg")):
os.rename(os.path.join(path, old + ".svg"), os.path.join(path, new + ".svg"))
self["name"] = new
def get_name(self):
return self.get("name")
name: StringProperty(name="Name", get=get_name, set=set_name)
drawings: CollectionProperty(name="Drawings", type=Drawing)
active_drawing_index: IntProperty(name="Active Drawing Index")
class DrawingStyle(PropertyGroup):
name: StringProperty(name="Name")
raster_style: StringProperty(name="Raster Style")
render_type: EnumProperty(
items=[
("NONE", "None", ""),
("DEFAULT", "Default", ""),
("VIEWPORT", "Viewport", ""),
],
name="Render Type",
default="VIEWPORT",
)
vector_style: EnumProperty(items=getVectorStyles, name="Vector Style")
include_query: StringProperty(name="Include Query")
exclude_query: StringProperty(name="Exclude Query")
attributes: CollectionProperty(name="Attributes", type=StrProperty)
class DocProperties(PropertyGroup):
should_recut: BoolProperty(name="Should Recut", default=True)
should_recut_selected: BoolProperty(name="Should Recut Selected Only", default=False)
should_extract: BoolProperty(name="Should Extract", default=True)
drawings: CollectionProperty(name="Drawings", type=Drawing)
active_drawing_index: IntProperty(name="Active Drawing Index", update=refreshActiveDrawingIndex)
current_drawing_index: IntProperty(name="Current Drawing Index")
schedules: CollectionProperty(name="Schedules", type=Schedule)
active_schedule_index: IntProperty(name="Active Schedule Index")
titleblock: EnumProperty(items=getTitleblocks, name="Titleblock", update=refreshTitleblocks)
sheets: CollectionProperty(name="Sheets", type=Sheet)
active_sheet_index: IntProperty(name="Active Sheet Index")
ifc_files: CollectionProperty(name="IFCs", type=StrProperty)
drawing_styles: CollectionProperty(name="Drawing Styles", type=DrawingStyle)
should_draw_decorations: BoolProperty(name="Should Draw Decorations", update=toggleDecorations)
decorations_colour: FloatVectorProperty(
name="Decorations Colour", subtype="COLOR", default=(1, 0, 0, 1), min=0.0, max=1.0, size=4
)
class BIMCameraProperties(PropertyGroup):
view_name: StringProperty(name="View Name")
target_view: EnumProperty(
items=[
("PLAN_VIEW", "PLAN_VIEW", ""),
("ELEVATION_VIEW", "ELEVATION_VIEW", ""),
("SECTION_VIEW", "SECTION_VIEW", ""),
("REFLECTED_PLAN_VIEW", "REFLECTED_PLAN_VIEW", ""),
("MODEL_VIEW", "MODEL_VIEW", ""),
],
name="Target View",
default="PLAN_VIEW",
)
diagram_scale: EnumProperty(items=getDiagramScales, name="Drawing Scale")
custom_diagram_scale: StringProperty(name="Custom Scale")
raster_x: IntProperty(name="Raster X", default=1000)
raster_y: IntProperty(name="Raster Y", default=1000)
is_nts: BoolProperty(name="Is NTS")
cut_objects: EnumProperty(
items=[
(
".IfcWall|.IfcSlab|.IfcCurtainWall|.IfcStair|.IfcStairFlight|.IfcColumn|.IfcBeam|.IfcMember|.IfcCovering|.IfcSpace",
"Overall Plan / Section",
"",
),
(".IfcElement", "Detail Drawing", ""),
("CUSTOM", "Custom", ""),
],
name="Cut Objects",
)
cut_objects_custom: StringProperty(name="Custom Cut")
active_drawing_style_index: IntProperty(name="Active Drawing Style Index")
class BIMTextProperties(PropertyGroup):
font_size: EnumProperty(
items=[
("1.8", "1.8 - Small", ""),
("2.5", "2.5 - Regular", ""),
("3.5", "3.5 - Large", ""),
("5.0", "5.0 - Header", ""),
("7.0", "7.0 - Title", ""),
],
update=refreshFontSize,
name="Font Size",
)
symbol: EnumProperty(
items=[
("None", "None", ""),
("rectangle-tag", "Rectangle Tag", ""),
("door-tag", "Door Tag", ""),
],
update=refreshFontSize,
name="Symbol",
)
related_element: PointerProperty(name="Related Element", type=bpy.types.Object)
variables: CollectionProperty(name="Variables", type=Variable)
class BIMProperties(PropertyGroup):
schema_dir: StringProperty(default=os.path.join(cwd, "schema") + os.path.sep, name="Schema Directory")
data_dir: StringProperty(default=os.path.join(cwd, "data") + os.path.sep, name="Data Directory")
schema_dir: StringProperty(
default=os.path.join(cwd, "schema") + os.path.sep, name="Schema Directory", update=updateSchemaDir
)
data_dir: StringProperty(
default=os.path.join(cwd, "data") + os.path.sep, name="Data Directory", update=updateDataDir
)
ifc_file: StringProperty(name="IFC File", update=updateIfcFile)
id_map: StringProperty(name="ID Map")
guid_map: StringProperty(name="GUID Map")
@@ -509,18 +276,6 @@ class BIMMaterialProperties(PropertyGroup):
ifc_style_id: IntProperty(name="IFC Style ID")
class SweptSolid(PropertyGroup):
name: StringProperty(name="Name")
outer_curve: StringProperty(name="Outer Curve")
inner_curves: StringProperty(name="Inner Curves")
extrusion: StringProperty(name="Extrusion")
class RepresentationItem(PropertyGroup):
name: StringProperty(name="Name")
vgroup: StringProperty(name="Vertex Group")
class ItemSlotMap(PropertyGroup):
name: StringProperty(name="Item Element ID")
slot_index: IntProperty(name="Material Slot Index")
@@ -530,7 +285,6 @@ class BIMMeshProperties(PropertyGroup):
ifc_definition_id: IntProperty(name="IFC Definition ID")
is_native: BoolProperty(name="Is Native", default=False)
is_swept_solid: BoolProperty(name="Is Swept Solid")
swept_solids: CollectionProperty(name="Swept Solids", type=SweptSolid)
is_parametric: BoolProperty(name="Is Parametric", default=False)
ifc_definition: StringProperty(name="IFC Definition")
ifc_parameters: CollectionProperty(name="IFC Parameters", type=IfcParameter)
+2 -2
View File
@@ -10,8 +10,8 @@ cwd = os.path.dirname(os.path.realpath(__file__))
class IfcSchema:
def __init__(self):
self.schema_dir = Path(cwd).joinpath("schema") # TODO: make configurable
self.data_dir = Path(cwd).joinpath("data") # TODO: make configurable
self.schema_dir = Path(cwd).joinpath("schema")
self.data_dir = Path(cwd).joinpath("data")
# TODO: Make it less troublesome
self.products = [
"IfcElement",
-231
View File
@@ -5,93 +5,6 @@ from bpy.types import Panel
from bpy.props import StringProperty, BoolProperty
class BIM_PT_drawings(Panel):
bl_label = "SVG Drawings"
bl_idname = "BIM_PT_drawings"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_drawing")
row.operator("bim.refresh_drawing_list", icon="FILE_REFRESH", text="")
if props.drawings:
if props.active_drawing_index < len(props.drawings):
op = row.operator("bim.open_view", icon="URL", text="")
op.view = props.drawings[props.active_drawing_index].name
row.operator("bim.remove_drawing", icon="X", text="").index = props.active_drawing_index
layout.template_list("BIM_UL_generic", "", props, "drawings", props, "active_drawing_index")
row = layout.row()
row.operator("bim.add_ifc_file")
for index, ifc_file in enumerate(props.ifc_files):
row = layout.row(align=True)
row.prop(ifc_file, "name", text="IFC #{}".format(index + 1))
row.operator("bim.select_doc_ifc_file", icon="FILE_FOLDER", text="").index = index
row.operator("bim.remove_ifc_file", icon="X", text="").index = index
class BIM_PT_schedules(Panel):
bl_label = "ODS Schedules"
bl_idname = "BIM_PT_schedules"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_schedule")
if props.schedules:
row.operator("bim.build_schedule", icon="LINENUMBERS_ON", text="")
row.operator("bim.remove_schedule", icon="X", text="").index = props.active_schedule_index
layout.template_list("BIM_UL_generic", "", props, "schedules", props, "active_schedule_index")
row = layout.row()
row.prop(props.schedules[props.active_schedule_index], "file")
row.operator("bim.select_schedule_file", icon="FILE_FOLDER", text="")
class BIM_PT_sheets(Panel):
bl_label = "SVG Sheets"
bl_idname = "BIM_PT_sheets"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "output"
def draw(self, context):
layout = self.layout
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.prop(props, "titleblock", text="")
row.operator("bim.add_sheet")
if props.sheets:
row.operator("bim.open_sheet", icon="URL", text="")
row.operator("bim.remove_sheet", icon="X", text="").index = props.active_sheet_index
layout.template_list("BIM_UL_generic", "", props, "sheets", props, "active_sheet_index")
row = layout.row(align=True)
row.operator("bim.add_drawing_to_sheet")
row.operator("bim.add_schedule_to_sheet")
row = layout.row()
row.operator("bim.create_sheets")
class BIM_PT_section_plane(Panel):
bl_label = "Temporary Section Cutaways"
bl_idname = "BIM_PT_section_plane"
@@ -115,43 +28,6 @@ class BIM_PT_section_plane(Panel):
row.operator("bim.remove_section_plane")
class BIM_PT_text(Panel):
bl_label = "Text Paper Space"
bl_idname = "BIM_PT_text"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
@classmethod
def poll(cls, context):
return type(context.curve) is bpy.types.TextCurve
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = context.active_object.data.BIMTextProperties
row = layout.row()
row.operator("bim.propagate_text_data")
row = layout.row()
row.prop(props, "font_size")
row = layout.row()
row.prop(props, "symbol")
row = layout.row()
row.prop(props, "related_element")
row = layout.row()
row.operator("bim.add_variable")
for index, variable in enumerate(props.variables):
row = layout.row(align=True)
row.prop(variable, "name")
row.operator("bim.remove_variable", icon="X", text="").index = index
row = layout.row()
row.prop(variable, "prop_key")
class BIM_UL_generic(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if item:
@@ -160,17 +36,6 @@ class BIM_UL_generic(bpy.types.UIList):
layout.label(text="", translate=False)
class BIM_UL_drawinglist(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if item:
row = layout.row(align=True)
row.prop(item, "name", text="", emboss=False)
op = row.operator("bim.open_view_camera", icon="OUTLINER_OB_CAMERA", text="")
op.view_name = item.name
else:
layout.label(text="", translate=False)
class BIM_UL_topics(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
ob = data
@@ -224,102 +89,6 @@ class BIM_ADDON_preferences(bpy.types.AddonPreferences):
row.prop(self, "should_hide_empty_props")
class BIM_PT_annotation_utilities(Panel):
bl_idname = "BIM_PT_annotation_utilities"
bl_label = "Annotation"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
def draw(self, context):
layout = self.layout
row = layout.row(align=True)
row.operator("bim.clean_wireframes")
row = layout.row(align=True)
row.operator("bim.link_ifc")
row = layout.row(align=True)
row.operator("bim.add_grid")
row = layout.row(align=True)
row.operator("bim.add_sections_annotations")
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Dim", icon="ARROW_LEFTRIGHT")
op.obj_name = "Dimension"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Dim (Eq)", icon="ARROW_LEFTRIGHT")
op.obj_name = "Equal"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Text", icon="SMALL_CAPS")
op.data_type = "text"
op = row.operator("bim.add_annotation", text="Leader", icon="TRACKING_BACKWARDS")
op.obj_name = "Leader"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Stair Arrow", icon="SCREEN_BACK")
op.obj_name = "Stair"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Hidden", icon="CON_TRACKTO")
op.obj_name = "Hidden"
op.data_type = "mesh"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Level (Plan)", icon="SORTBYEXT")
op.obj_name = "Plan Level"
op.data_type = "curve"
op = row.operator("bim.add_annotation", text="Level (Section)", icon="TRIA_DOWN")
op.obj_name = "Section Level"
op.data_type = "curve"
row = layout.row(align=True)
op = row.operator("bim.add_annotation", text="Breakline", icon="FCURVE")
op.obj_name = "Break"
op.data_type = "mesh"
op = row.operator("bim.add_annotation", text="Misc", icon="MESH_MONKEY")
op.obj_name = "Misc"
op.data_type = "mesh"
props = bpy.context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_drawing")
row.operator("bim.refresh_drawing_list", icon="FILE_REFRESH", text="")
if props.drawings:
if props.active_drawing_index < len(props.drawings):
op = row.operator("bim.open_view", icon="URL", text="")
op.view = props.drawings[props.active_drawing_index].name
row.operator("bim.remove_drawing", icon="X", text="").index = props.active_drawing_index
layout.template_list("BIM_UL_drawinglist", "", props, "drawings", props, "active_drawing_index")
layout.prop(props, "should_draw_decorations")
layout.prop(props, "decorations_colour")
class BIM_PT_misc_utilities(Panel):
bl_idname = "BIM_PT_misc_utilities"
bl_label = "Miscellaneous"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "BlenderBIM"
def draw(self, context):
layout = self.layout
props = context.scene.BIMProperties
row = layout.row()
row.prop(props, "override_colour", text="")
row = layout.row(align=True)
row.operator("bim.set_override_colour")
row = layout.row(align=True)
row.operator("bim.set_viewport_shadow_from_sun")
row = layout.row(align=True)
row.operator("bim.snap_spaces_together")
def ifc_units(self, context):
scene = context.scene
props = context.scene.BIMProperties
+6 -3
View File
@@ -6,7 +6,7 @@ Converter for CityJSON files and IFC. Currently only supports one-way conversion
IFCCityJSON only came into being 14/04/2021. Be prepared for lots of bugs, unfinished implementations and little to no documentation!
## Dependencies
- [IfcOpenShell](https://github.com/IfcOpenShell/IfcOpenShell)
- [IfcOpenShell](https://github.com/IfcOpenShell/IfcOpenShell) (also IfcOpenShell api is needed)
- [CJIO](https://github.com/cityjson/cjio)
## Usage of IFCCityJSON
@@ -22,7 +22,7 @@ The example file that could be used is example/3D_BAG_example.json
- [ ] "MultiPoint"
- [ ] "MultiLineString"
- [x] "MultiSurface"
- [ ] "CompositeSurface"
- [x] "CompositeSurface"
- [x] "Solid": exterior shell
- [ ] "Solid": interior shell
- [x] "MultiSolid"
@@ -32,4 +32,7 @@ The example file that could be used is example/3D_BAG_example.json
## TODO
- [x] CityJSON Attributes as IFC properties in 'CityJSON_attributes' pset
- [x] Implement georeferencing
- [ ] Do not use template IFC for new IFC file, but make IFC file from scratch
- [x] Do not use template IFC for new IFC file, but make IFC file from scratch
- [x] Create mapping to IFC for all CityJSON object types & semantic surfaces
- [ ] Implement conversion of all geometries
- [ ] Implement conversion of all LODs instead of online the most detailed
+51 -18
View File
@@ -1,6 +1,7 @@
import ifcopenshell
import warnings
import ifcopenshell.api
from geometry import GeometryIO
from datetime import datetime
JSON_TO_IFC = {
"Building": ["IfcBuilding"],
@@ -9,23 +10,33 @@ JSON_TO_IFC = {
"Road": ["IfcCivilElement"],
"TransportSquare": ["IfcSpace"],
"TINRelief": ["IfcGeographicElement"],
"WaterBody": ["IfcGeographicElement"],
"WaterBody": ["IfcGeographicElement"], # Update for IFC4.3
"LandUse": ["IfcGeographicElement"],
"PlantCover": ["IfcGeographicElement"],
"SolitaryVegetationObject": ["IfcGeographicElement"],
"CityFurniture": ["IfcFurnishingElement"],
"GenericCityObject": ["IfcCivilElement"],
"Bridge": ["IfcCivilElement"],
"BridgePart": ["IfcCivilElement"],
"BridgeInstallation": ["IfcCivilElement"],
"BridgeConstructionElement": ["IfcCivilElement"],
"Tunnel": ["IfcCivilElement"],
"TunnelPart": ["IfcCivilElement"],
"TunnelInstallation": ["IfcCivilElement"],
"Bridge": ["IfcCivilElement"], # Update for IFC4.3
"BridgePart": ["IfcCivilElement"], # Update for IFC4.3
"BridgeInstallation": ["IfcCivilElement"], # Update for IFC4.3
"BridgeConstructionElement": ["IfcCivilElement"], # Update for IFC4.3
"Tunnel": ["IfcCivilElement"], # Update for IFC4.3
"TunnelPart": ["IfcCivilElement"], # Update for IFC4.3
"TunnelInstallation": ["IfcCivilElement"], # Update for IFC4.3
"CityObjectGroup": ["IfcCivilElement"],
"GroundSurface": ["IfcSlab"],
"GroundSurface": ["IfcSlab", {"PredefinedType": "BASESLAB"}],
"RoofSurface": ["IfcRoof"],
"WallSurface": ["IfcWall"]
"WallSurface": ["IfcWall"],
"ClosureSurface": ["IfcSpace"],
"OuterCeilingSurface": ["IfcCovering", {"PredefinedType": "CEILING"}],
"OuterFloorSurface": ["IfcSlab", {"PredefinedType": "FLOOR"}],
"Window": ["IfcWindow"],
"Door": ["IfcDoor"],
"WaterSurface": ["IfcGeographicElement"], # Update for IFC4.3
"WaterGroundSurface": ["IfcGeographicElement"], # Update for IFC4.3
"WaterClosureSurface": ["IfcGeographicElement"], # Update for IFC4.3
"TrafficArea": ["IfcCivilElement"], # Update for IFC4.3
"AuxiliaryTrafficArea": ["IfcCivilElement"] # Update for IFC4.3
}
class Cityjson2ifc:
@@ -73,14 +84,36 @@ class Cityjson2ifc:
crs = self.IFC_model.create_entity("IfcProjectedCrs", Name=f"epsg:{epsg}")
self.IFC_model.create_entity("IfcMapConversion", self.IFC_representation_context, **self.properties["local_translation"])
self.properties["owner_history"] = self.IFC_model.by_type("IfcOwnerHistory")[0]
def create_new_file(self):
self.IFC_model = ifcopenshell.open('example/template.ifc')
self.IFC_site = self.IFC_model.by_type('IfcSite')[0]
self.IFC_representation_sub_context = self.IFC_model.by_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT")[0]
self.IFC_representation_context = self.IFC_model.by_type("IFCGEOMETRICREPRESENTATIONCONTEXT")[0]
# self.IFC_model = ifcopenshell.file(schema='IFC4')
self.IFC_model = ifcopenshell.api.run("project.create_file")
self.IFC_project = ifcopenshell.api.run("root.create_entity", self.IFC_model, **{"ifc_class": "IfcProject"})
self.properties["owner_history"] = self.create_owner_history()
ifcopenshell.api.run("unit.assign_unit", self.IFC_model)
self.IFC_representation_context = ifcopenshell.api.run("context.add_context", self.IFC_model,
**{"context": "Model"})
self.IFC_representation_sub_context = ifcopenshell.api.run("context.add_context", self.IFC_model,
**{"context": "Model",
"subcontext": "Body", # LODs as subcontext
"target_view": "MODEL_VIEW"})
self.IFC_site = ifcopenshell.api.run("root.create_entity", self.IFC_model,
**{"ifc_class": "IfcSite",
"name": "My Site"})
def create_owner_history(self):
actor = self.IFC_model.createIfcActorRole("ENGINEER", None, None)
person = self.IFC_model.createIfcPerson("Oostwegel", None, "L.J.N.", None, None, None, (actor,))
organization = self.IFC_model.createIfcOrganization(
None,
"IfcOpenShell",
"IfcOpenShell, an open source (LGPL) software library that helps users and software developers to work with the IFC file format.",
)
p_o = self.IFC_model.createIfcPersonAndOrganization(person, organization)
application = self.IFC_model.createIfcApplication(organization, "v0.0.x", "ifccityjson", "ifccityjson")
timestamp = int(datetime.now().timestamp())
ownerHistory = self.IFC_model.createIfcOwnerHistory(p_o, application, "READWRITE", None, None, None, None, timestamp)
return ownerHistory
def write_file(self):
self.IFC_model.write(self.properties["file_destination"])
-39
View File
@@ -1,39 +0,0 @@
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');
FILE_NAME('template.ifc','2021-03-17T14:54:00+11:00',(),(),'IfcOpenShell 0.6.0b0','BlenderBIM 0.0.999999','Nobody');
FILE_SCHEMA(('IFC4'));
ENDSEC;
DATA;
#1=IFCPERSON('HSeldon','Seldon','Hari',$,$,$,$,$);
#2=IFCORGANIZATION('APTR','Aperture Science',$,$,$);
#3=IFCPERSONANDORGANIZATION(#1,#2,$);
#4=IFCACTORROLE(.USERDEFINED.,'CONTRIBUTOR',$);
#5=IFCTELECOMADDRESS(.USERDEFINED.,'The main webpage of the software collection.','WEBPAGE',$,$,$,$,'https://ifcopenshell.org',$);
#6=IFCTELECOMADDRESS(.USERDEFINED.,'The CJ2IFC webpage of the software collection.','WEBPAGE',$,$,$,$,'https://github.com/LaurensJN/IFC2JS',$);
#7=IFCTELECOMADDRESS(.USERDEFINED.,'The source code repository of the software collection.','REPOSITORY',$,$,$,$,'https://github.com/IfcOpenShell/IfcOpenShell.git',$);
#8=IFCORGANIZATION($,'IfcOpenShell','IfcOpenShell is an open source (LGPL) software library that helps users and software developers to work with the IFC file format.',(#4),(#5,#6,#7));
#9=IFCAPPLICATION(#8,'0.0.999999','CityJSON to IFC converter','CJ2IFC');
#10=IFCOWNERHISTORY(#3,#9,.READWRITE.,.ADDED.,1615934569,#3,#9,1615934569);
#11=IFCPROJECT('2yjpApQSX3ZAZudc2AGHb3',#10,'My Project',$,$,$,$,(#20,#27),#15);
#12=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);
#13=IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.);
#14=IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.);
#15=IFCUNITASSIGNMENT((#12,#13,#14));
#16=IFCCARTESIANPOINT((0.,0.,0.));
#17=IFCDIRECTION((0.,0.,1.));
#18=IFCDIRECTION((1.,0.,0.));
#19=IFCAXIS2PLACEMENT3D(#16,#17,#18);
#20=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#19,$);
#21=IFCGEOMETRICREPRESENTATIONSUBCONTEXT('Body','Model',*,*,*,*,#20,$,.MODEL_VIEW.,$);
#22=IFCOWNERHISTORY(#3,#9,.READWRITE.,.ADDED.,1615934569,#3,#9,1615934569);
#23=IFCSITE('1maxFQa9z7q8w50tN19Dw9',#22,'My Site',$,$,#30,$,$,$,$,$,$,$,$);
#24=IFCOWNERHISTORY(#3,#9,.READWRITE.,.ADDED.,1615934569,#3,#9,1615934569);
#25=IFCRELAGGREGATES('1GuJ2jz2TA49gFFSYhrqGa',#24,$,$,#11,(#23));
#26=IFCCARTESIANPOINT((0.,0.,0.));
#27=IFCDIRECTION((0.,0.,1.));
#28=IFCDIRECTION((1.,0.,0.));
#29=IFCAXIS2PLACEMENT3D(#26,#27,#28);
#30=IFCLOCALPLACEMENT($,#29);
ENDSEC;
END-ISO-10303-21;
+36 -18
View File
@@ -21,6 +21,8 @@ class GeometryIO:
return self.create_IFC_closed_shell(IFC_model, geometry)
elif geometry.type in ["CompositeSolid", "MultiSolid"]:
return self.create_IFC_composite_closed_shell(IFC_model, geometry)
elif geometry.type in ["CompositeSurface", "MultiSurface"]:
return self.create_IFC_surface(IFC_model, geometry)
else:
warnings.warn("Types other than solids are not yet supported")
return
@@ -28,23 +30,22 @@ class GeometryIO:
def create_IFC_composite_closed_shell(self, IFC_model, geometry):
shells = []
for shell in geometry.boundaries:
# exterior shell
outershell = shell[0]
faces = []
for face in outershell: # exterior shell
for triangle in face:
faces.append(self.create_IFC_face(IFC_model, triangle))
for face in outershell:
faces.append(self.create_IFC_face(IFC_model, face))
shells.append(IFC_model.create_entity("IfcClosedShell", faces))
IFC_geometry = IFC_model.create_entity("IfcShellBasedSurfaceModel", shells)
return IFC_geometry
def create_IFC_closed_shell(self, IFC_model, geometry):
# exterior shell
outershell = geometry.boundaries[0]
# print(geometry.surfaces[0]['surface_idx'][0])
faces = []
for face in outershell: # exterior shell
for triangle in face:
faces.append(self.create_IFC_face(IFC_model, triangle))
for face in outershell:
faces.append(self.create_IFC_face(IFC_model, face))
if len(geometry.boundaries) == 1:
shell = IFC_model.create_entity("IfcClosedShell", faces)
@@ -54,28 +55,45 @@ class GeometryIO:
# TODO: INTERIOR SHELL
warnings.warn("Solid interior shell not yet supported")
return
# for boundary in geometry.boundaries[1]: # interior shell
# for boundary in geometry.boundaries[1:]: # interior shells
# for face in boundary:
# for triangle in face:
# print(triangle)
# print(geometry.boundaries)
def create_IFC_surface(self, IFC_model, geometry, surface_id):
face_ids = geometry.surfaces[surface_id]["surface_idx"]
faces = []
def create_IFC_surface(self, IFC_model, geometry, surface_id=None):
faces = None
if surface_id is not None:
face_ids = geometry.surfaces[surface_id]["surface_idx"]
faces = list(map(lambda face_id: geometry.boundaries[face_id[0]][face_id[1]], face_ids))
else:
faces = geometry.boundaries
for shell, face_id in face_ids:
for triangle in geometry.boundaries[shell][face_id]:
faces.append(self.create_IFC_face(IFC_model, triangle))
IFC_faces = []
for face in faces:
IFC_faces.append(self.create_IFC_face(IFC_model, face))
shell = IFC_model.create_entity("IfcOpenShell", faces)
shell = IFC_model.create_entity("IfcOpenShell", IFC_faces)
IFC_geometry = IFC_model.create_entity("IfcShellBasedSurfaceModel", [shell])
return IFC_geometry
def create_IFC_face(self, IFC_model, face):
# exterior face
vertices = []
for vertex in face:
for vertex in face[0]:
vertices.append(self.vertices[tuple(vertex)])
polyloop = IFC_model.create_entity("IfcPolyLoop", vertices)
outerbound = IFC_model.create_entity("IfcFaceOuterBound", polyloop, True)
return IFC_model.create_entity("IfcFace", [outerbound])
# return if only exterior face
if len(face) == 1:
return IFC_model.create_entity("IfcFace", [outerbound])
# interior face
innerbounds = []
for interior_face in face[1:]:
for vertex in interior_face:
vertices.append(self.vertices[tuple(vertex)])
polyloop = IFC_model.create_entity("IfcPolyLoop", vertices)
innerbounds.append(IFC_model.create_entity("IfcFaceBound", polyloop, True))
return IFC_model.create_entity("IfcFace", [outerbound] + innerbounds)
+110 -51
View File
@@ -1058,43 +1058,78 @@ bool IfcGeom::Kernel::convert_openings_fast(const IfcSchema::IfcProduct* entity,
// Iterate over the shapes of the IfcProduct
for ( IfcGeom::IfcRepresentationShapeItems::const_iterator it3 = entity_shapes.begin(); it3 != entity_shapes.end(); ++ it3 ) {
TopoDS_Shape entity_shape_solid;
const TopoDS_Shape& entity_shape_unlocated = ensure_fit_for_subtraction(it3->Shape(),entity_shape_solid);
const gp_GTrsf& entity_shape_gtrsf = it3->Placement();
if (entity_shape_gtrsf.Form() == gp_Other) {
Logger::Message(Logger::LOG_WARNING, "Applying non uniform transformation to:", entity);
}
TopoDS_Shape entity_shape = apply_transformation(entity_shape_unlocated, entity_shape_gtrsf);
TopoDS_Shape result = entity_shape;
auto it = opening_vector.begin();
auto jt = it;
bool is_manifold = Kernel::is_manifold(it3->Shape());
for (;; ++it) {
if (it == opening_vector.end() || jt->first / it->first > 10.) {
TopTools_ListOfShape opening_list;
for (auto kt = jt; kt < it; ++kt) {
opening_list.Append(kt->second);
}
TopoDS_Shape intermediate_result;
if (boolean_operation(result, opening_list, BOPAlgo_CUT, intermediate_result)) {
result = intermediate_result;
} else {
Logger::Message(Logger::LOG_ERROR, "Opening subtraction failed for " + boost::lexical_cast<std::string>(std::distance(jt, it)) + " openings", entity);
}
jt = it;
}
if (it == opening_vector.end()) {
break;
}
if (!is_manifold) {
Logger::Warning("Non-manifold first operand");
}
cut_shapes.push_back(IfcGeom::IfcRepresentationShapeItem(it3->ItemId(), result, &it3->Style()));
for (int as_shell = 0; as_shell < 2; ++as_shell) {
TopoDS_Shape entity_shape_solid;
TopoDS_Shape entity_shape_unlocated;
if (as_shell) {
entity_shape_unlocated = it3->Shape();
} else {
entity_shape_unlocated = ensure_fit_for_subtraction(it3->Shape(), entity_shape_solid);
}
const gp_GTrsf& entity_shape_gtrsf = it3->Placement();
if (entity_shape_gtrsf.Form() == gp_Other) {
Logger::Message(Logger::LOG_WARNING, "Applying non uniform transformation to:", entity);
}
TopoDS_Shape entity_shape = apply_transformation(entity_shape_unlocated, entity_shape_gtrsf);
TopoDS_Shape result = entity_shape;
auto it = opening_vector.begin();
auto jt = it;
for (;; ++it) {
if (it == opening_vector.end() || jt->first / it->first > 10.) {
TopTools_ListOfShape opening_list;
for (auto kt = jt; kt < it; ++kt) {
opening_list.Append(kt->second);
}
TopoDS_Shape intermediate_result;
if (boolean_operation(result, opening_list, BOPAlgo_CUT, intermediate_result)) {
result = intermediate_result;
}
else {
Logger::Message(Logger::LOG_ERROR, "Opening subtraction failed for " + boost::lexical_cast<std::string>(std::distance(jt, it)) + " openings", entity);
}
jt = it;
}
if (it == opening_vector.end()) {
break;
}
}
int result_n_faces = count(result, TopAbs_FACE);
if (!is_manifold && as_shell == 0 && result_n_faces == 0) {
// If we have a non-manifold first operand and our first attempt
// on a Solid-Solid subtraction yielded a empty result (no faces)
// or a strange result, a larger number of faces with the original input
// included. Then retry (another iteration on the for-loop on as-shell)
// where we keep the first operand as is (a compound of faces probably,
// unless --orient-shells was activated in which case we're already lost).
if (!is_manifold) {
Logger::Warning("Retrying boolean operation on individual faces");
}
continue;
}
cut_shapes.push_back(IfcGeom::IfcRepresentationShapeItem(it3->ItemId(), result, &it3->Style()));
// For manifold first operands we're not even going to try if processing
// as loose faces gives a better result.
break;
}
}
return true;
}
@@ -4344,30 +4379,54 @@ bool IfcGeom::Kernel::boolean_operation(const TopoDS_Shape& a_, const TopTools_L
}
if (success) {
// when there are edges or vertex-edge distances close to the used fuzziness, the
// output is not trusted and the operation is attempted with a higher fuzziness.
int reason = 0;
double v;
if ((v = min_edge_length(r)) < fuzziness * 3.) {
reason = 0;
success = false;
} else if ((v = min_vertex_edge_distance(r, getValue(GV_PRECISION), fuzziness * 3.)) < fuzziness * 3.) {
reason = 1;
success = false;
} else if ((v = min_face_face_distance(r, 1.e-4)) < 1.e-4) {
reason = 2;
TopTools_IndexedMapOfShape faces;
TopExp::MapShapes(r, TopAbs_FACE, faces);
bool all_faces_included_in_result = true;
for (TopExp_Explorer exp(a, TopAbs_FACE); exp.More(); exp.Next()) {
auto& f = TopoDS::Face(exp.Current());
if (!faces.Contains(f)) {
all_faces_included_in_result = false;
break;
}
}
int result_n_faces = count(r, TopAbs_FACE);
int first_op_n_faces = count(a, TopAbs_FACE);
if (all_faces_included_in_result && result_n_faces > first_op_n_faces) {
success = false;
Logger::Notice("Boolean result discarded because subtractions results in only the addition of faces");
} else {
// when there are edges or vertex-edge distances close to the used fuzziness, the
// output is not trusted and the operation is attempted with a higher fuzziness.
int reason = 0;
double v;
if ((v = min_edge_length(r)) < fuzziness * 3.) {
reason = 0;
success = false;
}
else if ((v = min_vertex_edge_distance(r, getValue(GV_PRECISION), fuzziness * 3.)) < fuzziness * 3.) {
reason = 1;
success = false;
}
else if ((v = min_face_face_distance(r, 1.e-4)) < 1.e-4) {
reason = 2;
success = false;
}
if (!success) {
static const char* const reason_strings[] = { "edge length", "vertex-edge", "face-face" };
std::stringstream str;
str << "Boolean operation result failing " << reason_strings[reason] << " interference check, with fuzziness " << fuzziness << " with length " << v;
Logger::Notice(str.str());
}
}
if (success) {
result = r;
} else {
static const char* const reason_strings[] = { "edge length", "vertex-edge", "face-face" };
std::stringstream str;
str << "Boolean operation result failing " << reason_strings[reason] << " interference check, with fuzziness " << fuzziness << " with length " << v;
Logger::Notice(str.str());
}
} else {
Logger::Notice("Boolean operation yields non-manifold result");
}

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