| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
__title__ = "FreeCAD IFC importer" |
| 32 |
__author__ = "Yorik van Havre" |
| 33 |
__url__ = "https://www.freecad.org" |
| 34 |
|
| 35 |
import math |
| 36 |
import os |
| 37 |
import re |
| 38 |
import time |
| 39 |
import uuid |
| 40 |
|
| 41 |
from builtins import open as pyopen |
| 42 |
|
| 43 |
import FreeCAD |
| 44 |
import Arch |
| 45 |
import Draft |
| 46 |
import DraftVecUtils |
| 47 |
import Part |
| 48 |
|
| 49 |
from draftutils import params |
| 50 |
from draftutils.translate import translate |
| 51 |
|
| 52 |
|
| 53 |
subtractiveTypes = ["IfcOpeningElement"] |
| 54 |
SCHEMA = "http://www.steptools.com/support/stdev_docs/ifcbim/ifc4.exp" |
| 55 |
MAKETEMPFILES = False |
| 56 |
DEBUG = True |
| 57 |
SKIP = [ |
| 58 |
"IfcBuildingElementProxy", |
| 59 |
"IfcFlowTerminal", |
| 60 |
"IfcFurnishingElement", |
| 61 |
] |
| 62 |
IFCLINE_RE = re.compile(r"#(\d+)[ ]?=[ ]?(.*?)\((.*)\);[\\r]?$") |
| 63 |
APPLYFIX = True |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
supportedIfcTypes = [ |
| 68 |
"IfcSite", |
| 69 |
"IfcBuilding", |
| 70 |
"IfcBuildingStorey", |
| 71 |
"IfcBeam", |
| 72 |
"IfcBeamStandardCase", |
| 73 |
"IfcChimney", |
| 74 |
"IfcColumn", |
| 75 |
"IfcColumnStandardCase", |
| 76 |
"IfcCovering", |
| 77 |
"IfcCurtainWall", |
| 78 |
"IfcDoor", |
| 79 |
"IfcDoorStandardCase", |
| 80 |
"IfcMember", |
| 81 |
"IfcMemberStandardCase", |
| 82 |
"IfcPlate", |
| 83 |
"IfcPlateStandardCase", |
| 84 |
"IfcRailing", |
| 85 |
"IfcRamp", |
| 86 |
"IfcRampFlight", |
| 87 |
"IfcRoof", |
| 88 |
"IfcSlab", |
| 89 |
"IfcStair", |
| 90 |
"IfcStairFlight", |
| 91 |
"IfcWall", |
| 92 |
"IfcSpace", |
| 93 |
"IfcWallStandardCase", |
| 94 |
"IfcWindow", |
| 95 |
"IfcWindowStandardCase", |
| 96 |
"IfcBuildingElementProxy", |
| 97 |
"IfcPile", |
| 98 |
"IfcFooting", |
| 99 |
"IfcReinforcingBar", |
| 100 |
"IfcTendon", |
| 101 |
] |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
def open(filename, skip=None): |
| 106 |
"called when freecad opens a file" |
| 107 |
docname = os.path.splitext(os.path.basename(filename))[0] |
| 108 |
doc = FreeCAD.newDocument(docname) |
| 109 |
doc.Label = docname |
| 110 |
FreeCAD.ActiveDocument = doc |
| 111 |
getConfig() |
| 112 |
read(filename, skip) |
| 113 |
return doc |
| 114 |
|
| 115 |
|
| 116 |
def insert(filename, docname, skip=None): |
| 117 |
"called when freecad wants to import a file" |
| 118 |
try: |
| 119 |
doc = FreeCAD.getDocument(docname) |
| 120 |
except NameError: |
| 121 |
doc = FreeCAD.newDocument(docname) |
| 122 |
FreeCAD.ActiveDocument = doc |
| 123 |
getConfig() |
| 124 |
read(filename, skip) |
| 125 |
return doc |
| 126 |
|
| 127 |
|
| 128 |
def getConfig(): |
| 129 |
"Gets Arch IFC import preferences" |
| 130 |
global SKIP, CREATE_IFC_GROUPS, ASMESH, PREFIX_NUMBERS, FORCE_PYTHON_PARSER, SEPARATE_OPENINGS, SEPARATE_PLACEMENTS, JOINSOLIDS, AGGREGATE_WINDOWS |
| 131 |
IMPORT_IFC_FURNITURE = False |
| 132 |
ASMESH = ["IfcFurnishingElement"] |
| 133 |
CREATE_IFC_GROUPS = params.get_param_arch("createIfcGroups") |
| 134 |
FORCE_PYTHON_PARSER = params.get_param_arch("forceIfcPythonParser") |
| 135 |
DEBUG = params.get_param_arch("ifcDebug") |
| 136 |
SEPARATE_OPENINGS = params.get_param_arch("ifcSeparateOpenings") |
| 137 |
SEPARATE_PLACEMENTS = params.get_param_arch("ifcSeparatePlacements") |
| 138 |
PREFIX_NUMBERS = params.get_param_arch("ifcPrefixNumbers") |
| 139 |
JOINSOLIDS = params.get_param_arch("ifcJoinSolids") |
| 140 |
AGGREGATE_WINDOWS = params.get_param_arch("ifcAggregateWindows") |
| 141 |
skiplist = params.get_param_arch("ifcSkip") |
| 142 |
if skiplist: |
| 143 |
SKIP = skiplist.split(",") |
| 144 |
asmeshlist = params.get_param_arch("ifcAsMesh") |
| 145 |
if asmeshlist: |
| 146 |
ASMESH = asmeshlist.split(",") |
| 147 |
|
| 148 |
|
| 149 |
def getIfcOpenShell(): |
| 150 |
"locates and imports ifcopenshell" |
| 151 |
global IFCOPENSHELL5 |
| 152 |
global IfcImport |
| 153 |
IFCOPENSHELL5 = False |
| 154 |
try: |
| 155 |
import IfcImport |
| 156 |
except ImportError: |
| 157 |
try: |
| 158 |
import ifc_wrapper as IfcImport |
| 159 |
except ImportError: |
| 160 |
FreeCAD.Console.PrintMessage(translate("Arch", "Could not locate IfcOpenShell") + "\n") |
| 161 |
return False |
| 162 |
else: |
| 163 |
IFCOPENSHELL5 = True |
| 164 |
return True |
| 165 |
else: |
| 166 |
if hasattr(IfcImport, "IfcFile"): |
| 167 |
IFCOPENSHELL5 = True |
| 168 |
return True |
| 169 |
|
| 170 |
|
| 171 |
def read(filename, skip=None): |
| 172 |
"Parses an IFC file" |
| 173 |
|
| 174 |
|
| 175 |
t1 = time.time() |
| 176 |
|
| 177 |
processedIds = [] |
| 178 |
skipIds = skip |
| 179 |
if not skipIds: |
| 180 |
skipIds = [] |
| 181 |
elif isinstance(skipIds, int): |
| 182 |
skipIds = [skipIds] |
| 183 |
|
| 184 |
if getIfcOpenShell() and not FORCE_PYTHON_PARSER: |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
if DEBUG: |
| 189 |
global ifcObjects, ifcParents |
| 190 |
ifcObjects = {} |
| 191 |
ifcParents = {} |
| 192 |
if SEPARATE_OPENINGS: |
| 193 |
if not IFCOPENSHELL5: |
| 194 |
if hasattr(IfcImport, "DISABLE_OPENING_SUBTRACTIONS"): |
| 195 |
IfcImport.Settings(IfcImport.DISABLE_OPENING_SUBTRACTIONS, True) |
| 196 |
else: |
| 197 |
SKIP.append("IfcOpeningElement") |
| 198 |
useShapes = False |
| 199 |
if IFCOPENSHELL5: |
| 200 |
useShapes = True |
| 201 |
if hasattr(IfcImport, "clean"): |
| 202 |
IfcImport.clean() |
| 203 |
elif hasattr(IfcImport, "USE_BREP_DATA"): |
| 204 |
IfcImport.Settings(IfcImport.USE_BREP_DATA, True) |
| 205 |
useShapes = True |
| 206 |
else: |
| 207 |
if DEBUG: |
| 208 |
print("Warning: IfcOpenShell version very old, unable to handle Brep data") |
| 209 |
|
| 210 |
|
| 211 |
if IFCOPENSHELL5: |
| 212 |
global ifc |
| 213 |
ifc = IfcImport.open(filename) |
| 214 |
objects = ifc.by_type("IfcProduct") |
| 215 |
num_lines = len(objects) |
| 216 |
relations = ( |
| 217 |
ifc.by_type("IfcRelAggregates") |
| 218 |
+ ifc.by_type("IfcRelContainedInSpatialStructure") |
| 219 |
+ ifc.by_type("IfcRelVoidsElement") |
| 220 |
) |
| 221 |
if not objects: |
| 222 |
print("Error opening IFC file") |
| 223 |
return |
| 224 |
else: |
| 225 |
num_lines = sum(1 for line in pyopen(filename)) |
| 226 |
if not IfcImport.Init(filename): |
| 227 |
print("Error opening IFC file") |
| 228 |
return |
| 229 |
|
| 230 |
|
| 231 |
idx = 0 |
| 232 |
while True: |
| 233 |
objparentid = [] |
| 234 |
if IFCOPENSHELL5: |
| 235 |
obj = objects[idx] |
| 236 |
idx += 1 |
| 237 |
objid = int(str(obj).split("=")[0].strip("#")) |
| 238 |
objname = obj.get_argument(obj.get_argument_index("Name")) |
| 239 |
objtype = str(obj).split("=")[1].split("(")[0] |
| 240 |
for r in relations: |
| 241 |
if r.is_a("IfcRelAggregates"): |
| 242 |
for c in getAttr(r, "RelatedObjects"): |
| 243 |
if str(obj) == str(c): |
| 244 |
objparentid.append( |
| 245 |
int(str(getAttr(r, "RelatingObject")).split("=")[0].strip("#")) |
| 246 |
) |
| 247 |
elif r.is_a("IfcRelContainedInSpatialStructure"): |
| 248 |
for c in getAttr(r, "RelatedElements"): |
| 249 |
if str(obj) == str(c): |
| 250 |
objparentid.append( |
| 251 |
int( |
| 252 |
str(getAttr(r, "RelatingStructure")) |
| 253 |
.split("=")[0] |
| 254 |
.strip("#") |
| 255 |
) |
| 256 |
) |
| 257 |
elif r.is_a("IfcRelVoidsElement"): |
| 258 |
if str(obj) == str(getAttr(r, "RelatedOpeningElement")): |
| 259 |
objparentid.append( |
| 260 |
int( |
| 261 |
str(getAttr(r, "RelatingBuildingElement")) |
| 262 |
.split("=")[0] |
| 263 |
.strip("#") |
| 264 |
) |
| 265 |
) |
| 266 |
|
| 267 |
else: |
| 268 |
if hasattr(IfcImport, "GetBrepData"): |
| 269 |
obj = IfcImport.GetBrepData() |
| 270 |
else: |
| 271 |
obj = IfcImport.Get() |
| 272 |
objid = obj.id |
| 273 |
idx = objid |
| 274 |
objname = obj.name |
| 275 |
objtype = obj.type |
| 276 |
objparentid.append(obj.parent_id) |
| 277 |
if DEBUG: |
| 278 |
print( |
| 279 |
"[" + str(int((float(idx) / num_lines) * 100)) + "%] parsing ", |
| 280 |
objid, |
| 281 |
": ", |
| 282 |
objname, |
| 283 |
" of type ", |
| 284 |
objtype, |
| 285 |
) |
| 286 |
|
| 287 |
|
| 288 |
n = getCleanName(objname, objid, objtype) |
| 289 |
|
| 290 |
|
| 291 |
if objid in skipIds: |
| 292 |
if DEBUG: |
| 293 |
print(" skipping because object ID is in skip list") |
| 294 |
nobj = None |
| 295 |
|
| 296 |
|
| 297 |
elif objtype in SKIP: |
| 298 |
if DEBUG: |
| 299 |
print(" skipping because type is in skip list") |
| 300 |
nobj = None |
| 301 |
|
| 302 |
|
| 303 |
elif objid in processedIds: |
| 304 |
if DEBUG: |
| 305 |
print(" skipping because this object was already processed") |
| 306 |
|
| 307 |
else: |
| 308 |
|
| 309 |
shape = None |
| 310 |
if useShapes: |
| 311 |
shape = getShape(obj, objid) |
| 312 |
|
| 313 |
|
| 314 |
if objtype in ["IfcWallStandardCase", "IfcWall"]: |
| 315 |
nobj = makeWall(objid, shape, n) |
| 316 |
|
| 317 |
|
| 318 |
elif objtype in ["IfcWindow", "IfcDoor"]: |
| 319 |
nobj = makeWindow(objid, shape, n) |
| 320 |
|
| 321 |
|
| 322 |
elif objtype in ["IfcBeam", "IfcColumn", "IfcSlab", "IfcFooting"]: |
| 323 |
nobj = makeStructure(objid, shape, objtype, n) |
| 324 |
|
| 325 |
|
| 326 |
elif objtype in ["IfcRoof"]: |
| 327 |
nobj = makeRoof(objid, shape, n) |
| 328 |
|
| 329 |
|
| 330 |
elif objtype in ["IfcFurnishingElement"]: |
| 331 |
nobj = FreeCAD.ActiveDocument.addObject("Part::Feature", n) |
| 332 |
nobj.Shape = shape |
| 333 |
|
| 334 |
|
| 335 |
elif objtype in ["IfcSite"]: |
| 336 |
nobj = makeSite(objid, shape, n) |
| 337 |
|
| 338 |
|
| 339 |
elif objtype in ["IfcBuildingStorey"]: |
| 340 |
nobj = Arch.makeFloor(name=n) |
| 341 |
nobj.Label = n |
| 342 |
|
| 343 |
|
| 344 |
elif objtype in ["IfcBuilding"]: |
| 345 |
nobj = Arch.makeBuilding(name=n) |
| 346 |
nobj.Label = n |
| 347 |
|
| 348 |
|
| 349 |
elif objtype in ["IfcSpace"]: |
| 350 |
nobj = makeSpace(objid, shape, n) |
| 351 |
|
| 352 |
elif shape: |
| 353 |
|
| 354 |
if DEBUG: |
| 355 |
print("Fixme: Shape-containing object not handled: ", objid, " ", objtype) |
| 356 |
nobj = FreeCAD.ActiveDocument.addObject("Part::Feature", n) |
| 357 |
nobj.Label = n |
| 358 |
nobj.Shape = shape |
| 359 |
|
| 360 |
else: |
| 361 |
|
| 362 |
if DEBUG: |
| 363 |
print("Warning: Object without shape: ", objid, " ", objtype) |
| 364 |
if hasattr(obj, "mesh"): |
| 365 |
if not hasattr(obj.mesh, "verts"): |
| 366 |
obj = IfcImport.Get() |
| 367 |
me, pl = getMesh(obj) |
| 368 |
nobj = FreeCAD.ActiveDocument.addObject("Mesh::Feature", n) |
| 369 |
nobj.Label = n |
| 370 |
nobj.Mesh = me |
| 371 |
nobj.Placement = pl |
| 372 |
else: |
| 373 |
if DEBUG: |
| 374 |
print("Error: Skipping object without mesh: ", objid, " ", objtype) |
| 375 |
|
| 376 |
|
| 377 |
if objparentid: |
| 378 |
ifcParents[objid] = [] |
| 379 |
for p in objparentid: |
| 380 |
ifcParents[objid].append([p, not (objtype in subtractiveTypes)]) |
| 381 |
ifcObjects[objid] = nobj |
| 382 |
processedIds.append(objid) |
| 383 |
|
| 384 |
if IFCOPENSHELL5: |
| 385 |
if idx >= len(objects): |
| 386 |
break |
| 387 |
else: |
| 388 |
if not IfcImport.Next(): |
| 389 |
break |
| 390 |
|
| 391 |
|
| 392 |
parents_temp = dict(ifcParents) |
| 393 |
import ArchCommands |
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
while parents_temp: |
| 398 |
id, comps = parents_temp.popitem() |
| 399 |
for c in comps: |
| 400 |
parent_id = c[0] |
| 401 |
additive = c[1] |
| 402 |
|
| 403 |
if (id <= 0) or (parent_id <= 0): |
| 404 |
|
| 405 |
parent = None |
| 406 |
|
| 407 |
elif parent_id in ifcObjects: |
| 408 |
parent = ifcObjects[parent_id] |
| 409 |
|
| 410 |
if parent_id in ifcParents: |
| 411 |
for p in ifcParents[parent_id]: |
| 412 |
if p[1] == False: |
| 413 |
grandparent_id = p[0] |
| 414 |
if grandparent_id in ifcObjects: |
| 415 |
parent = ifcObjects[grandparent_id] |
| 416 |
else: |
| 417 |
|
| 418 |
if IFCOPENSHELL5: |
| 419 |
obj = ifc.by_id(parent_id) |
| 420 |
parentid = int(str(obj).split("=")[0].strip("#")) |
| 421 |
parentname = obj.get_argument(obj.get_argument_index("Name")) |
| 422 |
parenttype = str(obj).split("=")[1].split("(")[0] |
| 423 |
else: |
| 424 |
obj = IfcImport.GetObject(parent_id) |
| 425 |
parentid = obj.id |
| 426 |
parentname = obj.name |
| 427 |
parenttype = obj.type |
| 428 |
|
| 429 |
n = getCleanName(parentname, parentid, parenttype) |
| 430 |
if parentid <= 0: |
| 431 |
parent = None |
| 432 |
elif parenttype == "IfcBuildingStorey": |
| 433 |
parent = Arch.makeFloor(name=n) |
| 434 |
parent.Label = n |
| 435 |
elif parenttype == "IfcBuilding": |
| 436 |
parent = Arch.makeBuilding(name=n) |
| 437 |
parent.Label = n |
| 438 |
elif parenttype == "IfcSite": |
| 439 |
parent = Arch.makeSite(name=n) |
| 440 |
parent.Label = n |
| 441 |
elif parenttype == "IfcWindow": |
| 442 |
parent = Arch.makeWindow(name=n) |
| 443 |
parent.Label = n |
| 444 |
elif parenttype == "IfcProject": |
| 445 |
parent = None |
| 446 |
else: |
| 447 |
if DEBUG: |
| 448 |
print("Fixme: skipping unhandled parent: ", parentid, " ", parenttype) |
| 449 |
parent = None |
| 450 |
|
| 451 |
if not IFCOPENSHELL5: |
| 452 |
if parent_ifcobj.parent_id > 0: |
| 453 |
ifcParents[parentid] = [parent_ifcobj.parent_id, True] |
| 454 |
parents_temp[parentid] = [parent_ifcobj.parent_id, True] |
| 455 |
if parent and (not parentid in ifcObjects): |
| 456 |
ifcObjects[parentid] = parent |
| 457 |
|
| 458 |
|
| 459 |
if parent and (id in ifcObjects): |
| 460 |
if ifcObjects[id] and (ifcObjects[id].Name != parent.Name): |
| 461 |
if additive: |
| 462 |
if DEBUG: |
| 463 |
print("adding ", ifcObjects[id].Name, " to ", parent.Name) |
| 464 |
ArchCommands.addComponents(ifcObjects[id], parent) |
| 465 |
else: |
| 466 |
if DEBUG: |
| 467 |
print("removing ", ifcObjects[id].Name, " from ", parent.Name) |
| 468 |
ArchCommands.removeComponents(ifcObjects[id], parent) |
| 469 |
if not IFCOPENSHELL5: |
| 470 |
IfcImport.CleanUp() |
| 471 |
|
| 472 |
else: |
| 473 |
|
| 474 |
|
| 475 |
FreeCAD.Console.PrintWarning( |
| 476 |
translate( |
| 477 |
"Arch", "IfcOpenShell not found or disabled, falling back on internal parser." |
| 478 |
) |
| 479 |
+ "\n" |
| 480 |
) |
| 481 |
schema = getSchema() |
| 482 |
if schema: |
| 483 |
if DEBUG: |
| 484 |
print("opening", filename, "...") |
| 485 |
ifc = IfcDocument(filename, schema=schema) |
| 486 |
else: |
| 487 |
FreeCAD.Console.PrintWarning( |
| 488 |
translate("Arch", "IFC Schema not found, IFC import disabled.") + "\n" |
| 489 |
) |
| 490 |
return None |
| 491 |
t2 = time.time() |
| 492 |
if DEBUG: |
| 493 |
print("Successfully loaded", ifc, "in %s s" % ((t2 - t1))) |
| 494 |
|
| 495 |
|
| 496 |
for w in ifc.getEnt("IfcWallStandardCase"): |
| 497 |
nobj = makeWall(w) |
| 498 |
|
| 499 |
|
| 500 |
for w in ifc.getEnt("IfcWindow") + ifc.getEnt("IfcDoor"): |
| 501 |
nobj = makeWindow(w) |
| 502 |
|
| 503 |
|
| 504 |
for w in ( |
| 505 |
ifc.getEnt("IfcSlab") |
| 506 |
+ ifc.getEnt("IfcBeam") |
| 507 |
+ ifc.getEnt("IfcColumn") |
| 508 |
+ ifc.getEnt("IfcFooting") |
| 509 |
): |
| 510 |
nobj = makeStructure(w) |
| 511 |
|
| 512 |
|
| 513 |
for f in ifc.getEnt("IfcBuildingStorey"): |
| 514 |
group(f, ifc, "Floor") |
| 515 |
|
| 516 |
|
| 517 |
for b in ifc.getEnt("IfcBuilding"): |
| 518 |
group(b, ifc, "Building") |
| 519 |
|
| 520 |
|
| 521 |
for s in ifc.getEnt("IfcSite"): |
| 522 |
group(s, ifc, "Site") |
| 523 |
|
| 524 |
if DEBUG: |
| 525 |
print("done parsing. Recomputing...") |
| 526 |
FreeCAD.ActiveDocument.recompute() |
| 527 |
t3 = time.time() |
| 528 |
if DEBUG: |
| 529 |
print("done processing IFC file in %s s" % ((t3 - t1))) |
| 530 |
|
| 531 |
return None |
| 532 |
|
| 533 |
|
| 534 |
def getCleanName(name, ifcid, ifctype): |
| 535 |
"Get a clean name from an ifc object" |
| 536 |
|
| 537 |
n = name |
| 538 |
if not n: |
| 539 |
n = ifctype |
| 540 |
if PREFIX_NUMBERS: |
| 541 |
n = "ID" + str(ifcid) + " " + n |
| 542 |
|
| 543 |
|
| 544 |
return n |
| 545 |
|
| 546 |
|
| 547 |
def makeWall(entity, shape=None, name="Wall"): |
| 548 |
"makes a wall in the freecad document" |
| 549 |
try: |
| 550 |
if shape: |
| 551 |
|
| 552 |
if isinstance(shape, Part.Shape): |
| 553 |
body = FreeCAD.ActiveDocument.addObject("Part::Feature", name + "_body") |
| 554 |
body.Shape = shape |
| 555 |
else: |
| 556 |
body = FreeCAD.ActiveDocument.addObject("Mesh::Feature", name + "_body") |
| 557 |
body.Mesh = shape |
| 558 |
wall = Arch.makeWall(body, name=name) |
| 559 |
wall.Label = name |
| 560 |
if DEBUG: |
| 561 |
print(" made wall object ", entity, ":", wall) |
| 562 |
return wall |
| 563 |
|
| 564 |
|
| 565 |
if DEBUG: |
| 566 |
print("=====> making wall", entity.id) |
| 567 |
placement = wall = wire = body = width = height = None |
| 568 |
placement = getPlacement(entity.ObjectPlacement) |
| 569 |
if DEBUG: |
| 570 |
print(" got wall placement", entity.id, ":", placement) |
| 571 |
width = entity.getProperty("Width") |
| 572 |
height = entity.getProperty("Height") |
| 573 |
if width and height: |
| 574 |
if DEBUG: |
| 575 |
print(" got width, height ", entity.id, ":", width, "/", height) |
| 576 |
for r in entity.Representation.Representations: |
| 577 |
if r.RepresentationIdentifier == "Axis": |
| 578 |
wire = getWire(r.Items, placement) |
| 579 |
wall = Arch.makeWall( |
| 580 |
wire, width, height, align="Center", name="Wall" + str(entity.id) |
| 581 |
) |
| 582 |
else: |
| 583 |
if DEBUG: |
| 584 |
print(" no height or width properties found...") |
| 585 |
for r in entity.Representation.Representations: |
| 586 |
if r.RepresentationIdentifier == "Body": |
| 587 |
for b in r.Items: |
| 588 |
if b.type == "IFCEXTRUDEDAREASOLID": |
| 589 |
norm = getVector(b.ExtrudedDirection) |
| 590 |
norm.normalize() |
| 591 |
wire = getWire(b.SweptArea, placement) |
| 592 |
wall = Arch.makeWall( |
| 593 |
wire, width=0, height=b.Depth, name="Wall" + str(entity.id) |
| 594 |
) |
| 595 |
wall.Normal = norm |
| 596 |
if wall: |
| 597 |
if DEBUG: |
| 598 |
print(" made wall object ", entity.id, ":", wall) |
| 599 |
return wall |
| 600 |
if DEBUG: |
| 601 |
print(" error: skipping wall", entity.id) |
| 602 |
return None |
| 603 |
except Exception: |
| 604 |
if DEBUG: |
| 605 |
print(" error: skipping wall", entity) |
| 606 |
return None |
| 607 |
|
| 608 |
|
| 609 |
def makeWindow(entity, shape=None, name="Window"): |
| 610 |
"makes a window in the freecad document" |
| 611 |
try: |
| 612 |
if shape: |
| 613 |
|
| 614 |
if isinstance(shape, Part.Shape): |
| 615 |
window = Arch.makeWindow(name=name) |
| 616 |
window.Shape = shape |
| 617 |
window.Label = name |
| 618 |
if DEBUG: |
| 619 |
print(" made window object ", entity, ":", window) |
| 620 |
return window |
| 621 |
|
| 622 |
|
| 623 |
if DEBUG: |
| 624 |
print("=====> making window", entity.id) |
| 625 |
placement = window = wire = body = width = height = None |
| 626 |
placement = getPlacement(entity.ObjectPlacement) |
| 627 |
if DEBUG: |
| 628 |
print("got window placement", entity.id, ":", placement) |
| 629 |
width = entity.getProperty("Width") |
| 630 |
height = entity.getProperty("Height") |
| 631 |
for r in entity.Representation.Representations: |
| 632 |
if r.RepresentationIdentifier == "Body": |
| 633 |
for b in r.Items: |
| 634 |
if b.type == "IFCEXTRUDEDAREASOLID": |
| 635 |
wire = getWire(b.SweptArea, placement) |
| 636 |
window = Arch.makeWindow(wire, width=b.Depth, name=objtype + str(entity.id)) |
| 637 |
if window: |
| 638 |
if DEBUG: |
| 639 |
print(" made window object ", entity.id, ":", window) |
| 640 |
return window |
| 641 |
if DEBUG: |
| 642 |
print(" error: skipping window", entity.id) |
| 643 |
return None |
| 644 |
except Exception: |
| 645 |
if DEBUG: |
| 646 |
print(" error: skipping window", entity) |
| 647 |
return None |
| 648 |
|
| 649 |
|
| 650 |
def makeStructure(entity, shape=None, ifctype=None, name="Structure"): |
| 651 |
"makes a structure in the freecad document" |
| 652 |
try: |
| 653 |
if shape: |
| 654 |
|
| 655 |
if isinstance(shape, Part.Shape): |
| 656 |
body = FreeCAD.ActiveDocument.addObject("Part::Feature", name + "_body") |
| 657 |
body.Shape = shape |
| 658 |
else: |
| 659 |
body = FreeCAD.ActiveDocument.addObject("Mesh::Feature", name + "_body") |
| 660 |
body.Mesh = shape |
| 661 |
structure = Arch.makeStructure(body, name=name) |
| 662 |
structure.Label = name |
| 663 |
if ifctype == "IfcBeam": |
| 664 |
structure.Role = "Beam" |
| 665 |
elif ifctype == "IfcColumn": |
| 666 |
structure.Role = "Column" |
| 667 |
elif ifctype == "IfcSlab": |
| 668 |
structure.Role = "Slab" |
| 669 |
elif ifctype == "IfcFooting": |
| 670 |
structure.Role = "Foundation" |
| 671 |
if DEBUG: |
| 672 |
print( |
| 673 |
" made structure object ", entity, ":", structure, " (type: ", ifctype, ")" |
| 674 |
) |
| 675 |
return structure |
| 676 |
|
| 677 |
|
| 678 |
if DEBUG: |
| 679 |
print("=====> making struct", entity.id) |
| 680 |
placement = structure = wire = body = width = height = None |
| 681 |
placement = getPlacement(entity.ObjectPlacement) |
| 682 |
if DEBUG: |
| 683 |
print("got window placement", entity.id, ":", placement) |
| 684 |
width = entity.getProperty("Width") |
| 685 |
height = entity.getProperty("Height") |
| 686 |
for r in entity.Representation.Representations: |
| 687 |
if r.RepresentationIdentifier == "Body": |
| 688 |
for b in r.Items: |
| 689 |
if b.type == "IFCEXTRUDEDAREASOLID": |
| 690 |
wire = getWire(b.SweptArea, placement) |
| 691 |
structure = Arch.makeStructure( |
| 692 |
wire, height=b.Depth, name=objtype + str(entity.id) |
| 693 |
) |
| 694 |
if structure: |
| 695 |
if DEBUG: |
| 696 |
print(" made structure object ", entity.id, ":", structure) |
| 697 |
return structure |
| 698 |
if DEBUG: |
| 699 |
print(" error: skipping structure", entity.id) |
| 700 |
return None |
| 701 |
except Exception: |
| 702 |
if DEBUG: |
| 703 |
print(" error: skipping structure", entity) |
| 704 |
return None |
| 705 |
|
| 706 |
|
| 707 |
def makeSite(entity, shape=None, name="Site"): |
| 708 |
"makes a site in the freecad document" |
| 709 |
try: |
| 710 |
body = None |
| 711 |
if shape: |
| 712 |
|
| 713 |
if isinstance(shape, Part.Shape): |
| 714 |
body = FreeCAD.ActiveDocument.addObject("Part::Feature", name + "_body") |
| 715 |
body.Shape = shape |
| 716 |
else: |
| 717 |
body = FreeCAD.ActiveDocument.addObject("Mesh::Feature", name + "_body") |
| 718 |
body.Mesh = shape |
| 719 |
site = Arch.makeSite(name=name) |
| 720 |
site.Label = name |
| 721 |
if body: |
| 722 |
site.Terrain = body |
| 723 |
if DEBUG: |
| 724 |
print(" made site object ", entity, ":", site) |
| 725 |
return site |
| 726 |
except Exception: |
| 727 |
return None |
| 728 |
|
| 729 |
|
| 730 |
def makeSpace(entity, shape=None, name="Space"): |
| 731 |
"makes a space in the freecad document" |
| 732 |
try: |
| 733 |
if shape: |
| 734 |
|
| 735 |
if isinstance(shape, Part.Shape): |
| 736 |
space = Arch.makeSpace(name=name) |
| 737 |
space.Label = name |
| 738 |
body = FreeCAD.ActiveDocument.addObject("Part::Feature", name + "_body") |
| 739 |
body.Shape = shape |
| 740 |
space.Base = body |
| 741 |
body.ViewObject.hide() |
| 742 |
if DEBUG: |
| 743 |
print(" made space object ", entity, ":", space) |
| 744 |
return space |
| 745 |
except Exception: |
| 746 |
return None |
| 747 |
|
| 748 |
|
| 749 |
def makeRoof(entity, shape=None, name="Roof"): |
| 750 |
"makes a roof in the freecad document" |
| 751 |
try: |
| 752 |
if shape: |
| 753 |
|
| 754 |
if isinstance(shape, Part.Shape): |
| 755 |
roof = Arch.makeRoof(name=name) |
| 756 |
roof.Label = name |
| 757 |
roof.Shape = shape |
| 758 |
if DEBUG: |
| 759 |
print(" made roof object ", entity, ":", roof) |
| 760 |
return roof |
| 761 |
except Exception: |
| 762 |
return None |
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
def getMesh(obj): |
| 769 |
"gets mesh and placement from an IfcOpenShell object" |
| 770 |
if IFCOPENSHELL5: |
| 771 |
return None, None |
| 772 |
print("fixme: mesh data not yet supported") |
| 773 |
import Mesh |
| 774 |
|
| 775 |
meshdata = [] |
| 776 |
print(obj.mesh.faces) |
| 777 |
print(obj.mesh.verts) |
| 778 |
f = obj.mesh.faces |
| 779 |
v = obj.mesh.verts |
| 780 |
for i in range(0, len(f), 3): |
| 781 |
face = [] |
| 782 |
for j in range(3): |
| 783 |
vi = f[i + j] * 3 |
| 784 |
face.append([v[vi], v[vi + 1], v[vi + 2]]) |
| 785 |
meshdata.append(face) |
| 786 |
print(meshdata) |
| 787 |
me = Mesh.Mesh(meshdata) |
| 788 |
|
| 789 |
m = obj.matrix |
| 790 |
|
| 791 |
mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], |
| 792 |
m[1], m[4], m[7], m[10], |
| 793 |
m[2], m[5], m[8], m[11], |
| 794 |
0, 0, 0, 1) |
| 795 |
|
| 796 |
pl = FreeCAD.Placement(mat) |
| 797 |
return me, pl |
| 798 |
|
| 799 |
|
| 800 |
def getShape(obj, objid): |
| 801 |
"gets a shape from an IfcOpenShell object" |
| 802 |
|
| 803 |
import Part |
| 804 |
|
| 805 |
sh = Part.Shape() |
| 806 |
brep_data = None |
| 807 |
if IFCOPENSHELL5: |
| 808 |
try: |
| 809 |
if hasattr(IfcImport, "SEW_SHELLS"): |
| 810 |
ss = IfcImport.SEW_SHELLS |
| 811 |
else: |
| 812 |
ss = 0 |
| 813 |
if SEPARATE_OPENINGS and hasattr(IfcImport, "DISABLE_OPENING_SUBTRACTIONS"): |
| 814 |
if SEPARATE_PLACEMENTS and hasattr(IfcImport, "DISABLE_OBJECT_PLACEMENT"): |
| 815 |
brep_data = IfcImport.create_shape( |
| 816 |
obj, |
| 817 |
IfcImport.DISABLE_OPENING_SUBTRACTIONS |
| 818 |
| IfcImport.DISABLE_OBJECT_PLACEMENT |
| 819 |
| ss, |
| 820 |
) |
| 821 |
else: |
| 822 |
brep_data = IfcImport.create_shape( |
| 823 |
obj, IfcImport.DISABLE_OPENING_SUBTRACTIONS | ss |
| 824 |
) |
| 825 |
else: |
| 826 |
if SEPARATE_PLACEMENTS and hasattr(IfcImport, "DISABLE_OBJECT_PLACEMENT"): |
| 827 |
brep_data = IfcImport.create_shape(obj, IfcImport.DISABLE_OBJECT_PLACEMENT | ss) |
| 828 |
else: |
| 829 |
brep_data = IfcImport.create_shape(obj, ss) |
| 830 |
except Exception: |
| 831 |
print("Unable to retrieve shape data") |
| 832 |
else: |
| 833 |
brep_data = obj.mesh.brep_data |
| 834 |
if brep_data: |
| 835 |
try: |
| 836 |
if MAKETEMPFILES: |
| 837 |
import tempfile |
| 838 |
|
| 839 |
th, tf = tempfile.mkstemp(suffix=".brp") |
| 840 |
of = pyopen(tf, "wb") |
| 841 |
of.write(brep_data) |
| 842 |
of.close() |
| 843 |
os.close(th) |
| 844 |
sh = Part.read(tf) |
| 845 |
os.remove(tf) |
| 846 |
else: |
| 847 |
sh.importBrepFromString(brep_data) |
| 848 |
except Exception: |
| 849 |
print(" error: malformed shape") |
| 850 |
return None |
| 851 |
else: |
| 852 |
if IFCOPENSHELL5 and SEPARATE_PLACEMENTS: |
| 853 |
p = getPlacement(getAttr(obj, "ObjectPlacement")) |
| 854 |
if p: |
| 855 |
sh.Placement = p |
| 856 |
if not sh.Solids: |
| 857 |
|
| 858 |
if sh.Faces: |
| 859 |
try: |
| 860 |
if DEBUG: |
| 861 |
print(" malformed solid. Attempting to fix...") |
| 862 |
shell = Part.makeShell(sh.Faces) |
| 863 |
if shell: |
| 864 |
solid = Part.makeSolid(shell) |
| 865 |
if solid: |
| 866 |
sh = solid |
| 867 |
except Exception: |
| 868 |
if DEBUG: |
| 869 |
print(" failed to retrieve solid from object ", objid) |
| 870 |
else: |
| 871 |
if DEBUG: |
| 872 |
print(" object ", objid, " does not contain any geometry") |
| 873 |
if not IFCOPENSHELL5: |
| 874 |
m = obj.matrix |
| 875 |
|
| 876 |
mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], |
| 877 |
m[1], m[4], m[7], m[10], |
| 878 |
m[2], m[5], m[8], m[11], |
| 879 |
0, 0, 0, 1) |
| 880 |
|
| 881 |
sh.Placement = FreeCAD.Placement(mat) |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
if sh: |
| 886 |
if not sh.isNull(): |
| 887 |
return sh |
| 888 |
return None |
| 889 |
|
| 890 |
|
| 891 |
def getPlacement(entity): |
| 892 |
"returns a placement from the given entity" |
| 893 |
if not entity: |
| 894 |
return None |
| 895 |
if DEBUG: |
| 896 |
print(" getting placement ", entity) |
| 897 |
if IFCOPENSHELL5: |
| 898 |
if isinstance(entity, int): |
| 899 |
entity = ifc.by_id(entity) |
| 900 |
entitytype = str(entity).split("=")[1].split("(")[0].upper() |
| 901 |
entityid = int(str(entity).split("=")[0].strip("#")) |
| 902 |
else: |
| 903 |
entitytype = entity.type.upper() |
| 904 |
entityid = entity.id |
| 905 |
pl = None |
| 906 |
if entitytype == "IFCAXIS2PLACEMENT3D": |
| 907 |
x = getVector(getAttr(entity, "RefDirection")) |
| 908 |
z = getVector(getAttr(entity, "Axis")) |
| 909 |
if not (x) or not (z): |
| 910 |
return None |
| 911 |
y = z.cross(x) |
| 912 |
loc = getVector(getAttr(entity, "Location")) |
| 913 |
m = DraftVecUtils.getPlaneRotation(x, y, z) |
| 914 |
pl = FreeCAD.Placement(m) |
| 915 |
pl.move(loc) |
| 916 |
elif entitytype == "IFCLOCALPLACEMENT": |
| 917 |
pl = getPlacement(getAttr(entity, "PlacementRelTo")) |
| 918 |
relpl = getPlacement(getAttr(entity, "RelativePlacement")) |
| 919 |
if pl and relpl: |
| 920 |
pl = relpl.multiply(pl) |
| 921 |
elif relpl: |
| 922 |
pl = relpl |
| 923 |
elif entitytype == "IFCCARTESIANPOINT": |
| 924 |
loc = getVector(entity) |
| 925 |
pl = FreeCAD.Placement() |
| 926 |
pl.move(loc) |
| 927 |
if DEBUG: |
| 928 |
print(" made placement for ", entityid, ":", pl) |
| 929 |
return pl |
| 930 |
|
| 931 |
|
| 932 |
def getAttr(entity, attr): |
| 933 |
"returns the given attribute from the given entity" |
| 934 |
if IFCOPENSHELL5: |
| 935 |
if isinstance(entity, int): |
| 936 |
entity = ifc.by_id(entity) |
| 937 |
i = entity.get_argument_index(attr) |
| 938 |
return entity.get_argument(i) |
| 939 |
else: |
| 940 |
return getattr(entity, attr) |
| 941 |
|
| 942 |
|
| 943 |
def getVector(entity): |
| 944 |
"returns a vector from the given entity" |
| 945 |
if not entity: |
| 946 |
return None |
| 947 |
if DEBUG: |
| 948 |
print(" getting point from ", entity) |
| 949 |
if IFCOPENSHELL5: |
| 950 |
if isinstance(entity, int): |
| 951 |
entity = ifc.by_id(entity) |
| 952 |
entitytype = str(entity).split("=")[1].split("(")[0].upper() |
| 953 |
else: |
| 954 |
entitytype = entity.type.upper() |
| 955 |
if entitytype == "IFCDIRECTION": |
| 956 |
DirectionRatios = getAttr(entity, "DirectionRatios") |
| 957 |
if len(DirectionRatios) == 3: |
| 958 |
return FreeCAD.Vector(tuple(DirectionRatios)) |
| 959 |
else: |
| 960 |
return FreeCAD.Vector(tuple(DirectionRatios + [0])) |
| 961 |
elif entitytype == "IFCCARTESIANPOINT": |
| 962 |
Coordinates = getAttr(entity, "Coordinates") |
| 963 |
if len(Coordinates) == 3: |
| 964 |
return FreeCAD.Vector(tuple(Coordinates)) |
| 965 |
else: |
| 966 |
return FreeCAD.Vector(tuple(Coordinates + [0])) |
| 967 |
return None |
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
def getSchema(): |
| 974 |
"retrieves the express schema" |
| 975 |
custom = params.get_param_arch("CustomIfcSchema") |
| 976 |
if custom: |
| 977 |
if os.path.exists(custom): |
| 978 |
if DEBUG: |
| 979 |
print("Using custom schema: ", custom.split(os.sep)[-1]) |
| 980 |
return custom |
| 981 |
p = None |
| 982 |
p = os.path.join(FreeCAD.ConfigGet("UserAppData"), SCHEMA.split(os.sep)[-1]) |
| 983 |
if os.path.exists(p): |
| 984 |
return p |
| 985 |
import ArchCommands |
| 986 |
|
| 987 |
p = ArchCommands.download(SCHEMA) |
| 988 |
if p: |
| 989 |
return p |
| 990 |
return None |
| 991 |
|
| 992 |
|
| 993 |
def group(entity, ifc, mode=None): |
| 994 |
"gathers the children of the given entity" |
| 995 |
|
| 996 |
|
| 997 |
try: |
| 998 |
if DEBUG: |
| 999 |
print("=====> making group", entity.id) |
| 1000 |
placement = None |
| 1001 |
placement = getPlacement(entity.ObjectPlacement) |
| 1002 |
if DEBUG: |
| 1003 |
print("got cell placement", entity.id, ":", placement) |
| 1004 |
subelements = ifc.find("IFCRELCONTAINEDINSPATIALSTRUCTURE", "RelatingStructure", entity) |
| 1005 |
subelements.extend(ifc.find("IFCRELAGGREGATES", "RelatingObject", entity)) |
| 1006 |
elts = [] |
| 1007 |
for s in subelements: |
| 1008 |
if hasattr(s, "RelatedElements"): |
| 1009 |
s = s.RelatedElements |
| 1010 |
if not isinstance(s, list): |
| 1011 |
s = [s] |
| 1012 |
elts.extend(s) |
| 1013 |
elif hasattr(s, "RelatedObjects"): |
| 1014 |
s = s.RelatedObjects |
| 1015 |
if not isinstance(s, list): |
| 1016 |
s = [s] |
| 1017 |
elts.extend(s) |
| 1018 |
elif hasattr(s, "RelatedObject"): |
| 1019 |
s = s.RelatedObject |
| 1020 |
if not isinstance(s, list): |
| 1021 |
s = [s] |
| 1022 |
elts.extend(s) |
| 1023 |
print("found dependent elements: ", elts) |
| 1024 |
|
| 1025 |
groups = [ |
| 1026 |
["Wall", ["IfcWallStandardCase"], []], |
| 1027 |
["Window", ["IfcWindow", "IfcDoor"], []], |
| 1028 |
["Structure", ["IfcSlab", "IfcFooting", "IfcBeam", "IfcColumn"], []], |
| 1029 |
["Floor", ["IfcBuildingStorey"], []], |
| 1030 |
["Building", ["IfcBuilding"], []], |
| 1031 |
["Furniture", ["IfcFurnishingElement"], []], |
| 1032 |
] |
| 1033 |
|
| 1034 |
for e in elts: |
| 1035 |
for g in groups: |
| 1036 |
for t in g[1]: |
| 1037 |
if e.type.upper() == t.upper(): |
| 1038 |
if hasattr(FreeCAD.ActiveDocument, g[0] + str(e.id)): |
| 1039 |
g[2].append(FreeCAD.ActiveDocument.getObject(g[0] + str(e.id))) |
| 1040 |
print("groups:", groups) |
| 1041 |
|
| 1042 |
comps = [] |
| 1043 |
if CREATE_IFC_GROUPS: |
| 1044 |
if DEBUG: |
| 1045 |
wprint("creating subgroups") |
| 1046 |
for g in groups: |
| 1047 |
if g[2]: |
| 1048 |
if g[0] in ["Building", "Floor"]: |
| 1049 |
comps.extend(g[2]) |
| 1050 |
else: |
| 1051 |
fcg = FreeCAD.ActiveDocument.addObject( |
| 1052 |
"App::DocumentObjectGroup", g[0] + "s" |
| 1053 |
) |
| 1054 |
for o in g[2]: |
| 1055 |
fcg.addObject(o) |
| 1056 |
comps.append(fcg) |
| 1057 |
else: |
| 1058 |
for g in groups: |
| 1059 |
comps.extend(g[2]) |
| 1060 |
|
| 1061 |
label = entity.Name |
| 1062 |
name = mode + str(entity.id) |
| 1063 |
cell = None |
| 1064 |
if mode == "Site": |
| 1065 |
cell = Arch.makeSite(comps, name=name) |
| 1066 |
elif mode == "Floor": |
| 1067 |
cell = Arch.makeFloor(comps, name=name) |
| 1068 |
elif mode == "Building": |
| 1069 |
cell = Arch.makeBuilding(comps, name=name) |
| 1070 |
if label and cell: |
| 1071 |
cell.Label = label |
| 1072 |
except Exception: |
| 1073 |
if DEBUG: |
| 1074 |
print("error: skipping group ", entity.id) |
| 1075 |
|
| 1076 |
|
| 1077 |
def getWire(entity, placement=None): |
| 1078 |
"returns a wire (created in the freecad document) from the given entity" |
| 1079 |
|
| 1080 |
if DEBUG: |
| 1081 |
print("making Wire from :", entity) |
| 1082 |
if not entity: |
| 1083 |
return None |
| 1084 |
if entity.type == "IFCPOLYLINE": |
| 1085 |
pts = [] |
| 1086 |
for p in entity.Points: |
| 1087 |
pts.append(getVector(p)) |
| 1088 |
return Draft.getWire(pts, placement=placement) |
| 1089 |
elif entity.type == "IFCARBITRARYCLOSEDPROFILEDEF": |
| 1090 |
pts = [] |
| 1091 |
for p in entity.OuterCurve.Points: |
| 1092 |
pts.append(getVector(p)) |
| 1093 |
return Draft.getWire(pts, closed=True, placement=placement) |
| 1094 |
|
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
|
| 1099 |
def export(exportList, filename): |
| 1100 |
"called when freecad exports a file" |
| 1101 |
global ifcw |
| 1102 |
ifcw = None |
| 1103 |
try: |
| 1104 |
import IfcImport as ifcw |
| 1105 |
except ImportError: |
| 1106 |
try: |
| 1107 |
import ifc_wrapper as ifcw |
| 1108 |
except ImportError: |
| 1109 |
FreeCAD.Console.PrintError( |
| 1110 |
translate("Arch", "Error: IfcOpenShell is not installed") + "\n" |
| 1111 |
) |
| 1112 |
print( |
| 1113 |
"""importIFC: ifcOpenShell is not installed. IFC export is unavailable. |
| 1114 |
Note: IFC export currently requires an experimental version of IfcOpenShell |
| 1115 |
available from https://github.com/aothms/IfcOpenShell""" |
| 1116 |
) |
| 1117 |
return |
| 1118 |
|
| 1119 |
if (not hasattr(ifcw, "IfcFile")) and (not hasattr(ifcw, "file")): |
| 1120 |
FreeCAD.Console.PrintError( |
| 1121 |
translate("Arch", "Error: your IfcOpenShell version is too old") + "\n" |
| 1122 |
) |
| 1123 |
print( |
| 1124 |
"""importIFC: The version of IfcOpenShell installed on this system does not |
| 1125 |
have IFC export capabilities. IFC export currently requires an experimental |
| 1126 |
version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell""" |
| 1127 |
) |
| 1128 |
return |
| 1129 |
import Draft |
| 1130 |
import Arch |
| 1131 |
|
| 1132 |
|
| 1133 |
getConfig() |
| 1134 |
scaling = params.get_param_arch("IfcScalingFactor") |
| 1135 |
exporttxt = params.get_param_arch("IfcExportList") |
| 1136 |
forcebrep = params.get_param_arch("ifcExportAsBrep") |
| 1137 |
application = "FreeCAD" |
| 1138 |
ver = FreeCAD.Version() |
| 1139 |
version = ver[0] + "." + ver[1] + " build" + ver[2] |
| 1140 |
owner = FreeCAD.ActiveDocument.CreatedBy |
| 1141 |
company = FreeCAD.ActiveDocument.Company |
| 1142 |
project = FreeCAD.ActiveDocument.Name |
| 1143 |
ifc = IfcWriter(filename, project, owner, company, application, version) |
| 1144 |
txt = [] |
| 1145 |
|
| 1146 |
|
| 1147 |
objectslist = Draft.get_group_contents(exportList, walls=True, addgroups=True) |
| 1148 |
objectslist = Arch.pruneIncluded(objectslist, strict=True) |
| 1149 |
|
| 1150 |
sites = [] |
| 1151 |
buildings = [] |
| 1152 |
floors = [] |
| 1153 |
groups = {} |
| 1154 |
others = [] |
| 1155 |
for obj in objectslist: |
| 1156 |
otype = Draft.getType(obj) |
| 1157 |
if otype == "Site": |
| 1158 |
sites.append(obj) |
| 1159 |
elif otype == "Building": |
| 1160 |
buildings.append(obj) |
| 1161 |
elif otype == "Floor": |
| 1162 |
floors.append(obj) |
| 1163 |
elif otype == "Group": |
| 1164 |
groups[obj.Name] = [] |
| 1165 |
else: |
| 1166 |
others.append(obj) |
| 1167 |
objectslist = buildings + floors + others |
| 1168 |
if DEBUG: |
| 1169 |
print("adding ", len(objectslist), " objects") |
| 1170 |
|
| 1171 |
global unprocessed |
| 1172 |
unprocessed = [] |
| 1173 |
|
| 1174 |
|
| 1175 |
for obj in objectslist: |
| 1176 |
|
| 1177 |
otype = Draft.getType(obj) |
| 1178 |
name = str(obj.Label) |
| 1179 |
parent = Arch.getHost(obj) |
| 1180 |
gdata = None |
| 1181 |
fdata = None |
| 1182 |
placement = None |
| 1183 |
color = None |
| 1184 |
representation = None |
| 1185 |
descr = None |
| 1186 |
extra = None |
| 1187 |
|
| 1188 |
|
| 1189 |
if hasattr(obj, "Role"): |
| 1190 |
ifctype = obj.Role.replace(" ", "") |
| 1191 |
elif otype == "Foundation": |
| 1192 |
ifctype = "Footing" |
| 1193 |
elif otype == "Rebar": |
| 1194 |
ifctype = "ReinforcingBar" |
| 1195 |
elif otype == "Undefined": |
| 1196 |
ifctype = "BuildingElementProxy" |
| 1197 |
elif otype.startswith("Part::"): |
| 1198 |
ifctype = "BuildingElementProxy" |
| 1199 |
else: |
| 1200 |
ifctype = otype |
| 1201 |
|
| 1202 |
|
| 1203 |
brepflag = False |
| 1204 |
if hasattr(obj, "IfcAttributes"): |
| 1205 |
if "FlagForceBrep" in obj.IfcAttributes: |
| 1206 |
if obj.IfcAttributes["FlagForceBrep"] == "True": |
| 1207 |
brepflag = True |
| 1208 |
|
| 1209 |
if DEBUG: |
| 1210 |
print("Adding " + obj.Label + " as Ifc" + ifctype) |
| 1211 |
|
| 1212 |
|
| 1213 |
if obj.isDerivedFrom("App::DocumentObjectGroup"): |
| 1214 |
|
| 1215 |
|
| 1216 |
if parent: |
| 1217 |
parent = ifc.findByName("IfcBuilding", str(parent.Label)) |
| 1218 |
|
| 1219 |
if otype == "Site": |
| 1220 |
print(" Skipping (not implemented yet)") |
| 1221 |
elif otype == "Building": |
| 1222 |
ifc.addBuilding(name=name) |
| 1223 |
elif otype == "Floor": |
| 1224 |
ifc.addStorey(building=parent, name=name) |
| 1225 |
|
| 1226 |
elif obj.isDerivedFrom("Part::Feature"): |
| 1227 |
|
| 1228 |
|
| 1229 |
if FreeCAD.GuiUp: |
| 1230 |
color = obj.ViewObject.ShapeColor[:3] |
| 1231 |
|
| 1232 |
|
| 1233 |
if parent: |
| 1234 |
parent = ifc.findByName("IfcBuildingStorey", str(parent.Label)) |
| 1235 |
|
| 1236 |
|
| 1237 |
if (not forcebrep) and (not brepflag): |
| 1238 |
gdata = getIfcExtrusionData(obj, scaling, SEPARATE_OPENINGS) |
| 1239 |
|
| 1240 |
if not gdata: |
| 1241 |
fdata = getIfcBrepFacesData(obj, scaling) |
| 1242 |
|
| 1243 |
if not fdata: |
| 1244 |
if obj.isDerivedFrom("Part::Feature"): |
| 1245 |
print(" Error retrieving the shape of object ", obj.Label) |
| 1246 |
unprocessed.append(obj) |
| 1247 |
continue |
| 1248 |
else: |
| 1249 |
if DEBUG: |
| 1250 |
print(" No geometry") |
| 1251 |
else: |
| 1252 |
if DEBUG: |
| 1253 |
print(" Brep") |
| 1254 |
else: |
| 1255 |
if DEBUG: |
| 1256 |
print(" Extrusion") |
| 1257 |
if gdata: |
| 1258 |
|
| 1259 |
placement = ifc.addPlacement( |
| 1260 |
origin=gdata[3][0], xaxis=gdata[3][1], zaxis=gdata[3][2] |
| 1261 |
) |
| 1262 |
if gdata[0] == "polyline": |
| 1263 |
representation = ifc.addExtrudedPolyline(gdata[1], gdata[2], color=color) |
| 1264 |
elif gdata[0] == "circle": |
| 1265 |
representation = ifc.addExtrudedCircle(gdata[1], gdata[2], color=color) |
| 1266 |
elif gdata[0] == "ellipse": |
| 1267 |
representation = ifc.addExtrudedEllipse(gdata[1], gdata[2], color=color) |
| 1268 |
elif gdata[0] == "composite": |
| 1269 |
representation = ifc.addExtrudedCompositeCurve(gdata[1], gdata[2], color=color) |
| 1270 |
else: |
| 1271 |
print("debug: unknown extrusion type") |
| 1272 |
elif fdata: |
| 1273 |
representation = [ifc.addFacetedBrep(f, color=color) for f in fdata] |
| 1274 |
|
| 1275 |
|
| 1276 |
ifctype = "Ifc" + ifctype |
| 1277 |
if hasattr(obj, "Description"): |
| 1278 |
descr = obj.Description |
| 1279 |
if otype == "Wall": |
| 1280 |
if gdata: |
| 1281 |
if gdata[0] == "polyline": |
| 1282 |
ifctype = "IfcWallStandardCase" |
| 1283 |
elif otype == "Structure": |
| 1284 |
if ifctype in ["IfcSlab", "IfcFooting"]: |
| 1285 |
extra = ["NOTDEFINED"] |
| 1286 |
elif otype == "Window": |
| 1287 |
extra = [obj.Width.Value * scaling, obj.Height.Value * scaling] |
| 1288 |
elif otype == "Space": |
| 1289 |
extra = ["ELEMENT", "INTERNAL", getIfcElevation(obj)] |
| 1290 |
elif otype.startswith("Part::"): |
| 1291 |
extra = ["ELEMENT"] |
| 1292 |
if not ifctype in supportedIfcTypes: |
| 1293 |
if DEBUG: |
| 1294 |
print( |
| 1295 |
" Type ", |
| 1296 |
ifctype, |
| 1297 |
" is not supported yet. Exporting as IfcBuildingElementProxy instead", |
| 1298 |
) |
| 1299 |
ifctype = "IfcBuildingElementProxy" |
| 1300 |
extra = ["ELEMENT"] |
| 1301 |
|
| 1302 |
product = ifc.addProduct( |
| 1303 |
ifctype, |
| 1304 |
representation, |
| 1305 |
storey=parent, |
| 1306 |
placement=placement, |
| 1307 |
name=name, |
| 1308 |
description=descr, |
| 1309 |
extra=extra, |
| 1310 |
) |
| 1311 |
|
| 1312 |
if product: |
| 1313 |
|
| 1314 |
if SEPARATE_OPENINGS and gdata: |
| 1315 |
for o in obj.Subtractions: |
| 1316 |
print("Subtracting ", o.Label) |
| 1317 |
fdata = getIfcBrepFacesData(o, scaling, sub=True) |
| 1318 |
representation = [ifc.addFacetedBrep(f, color=color) for f in fdata] |
| 1319 |
p2 = ifc.addProduct( |
| 1320 |
"IfcOpeningElement", |
| 1321 |
representation, |
| 1322 |
storey=product, |
| 1323 |
placement=None, |
| 1324 |
name=str(o.Label), |
| 1325 |
description=None, |
| 1326 |
) |
| 1327 |
|
| 1328 |
|
| 1329 |
spacer = "" |
| 1330 |
for i in range(36 - len(obj.Label)): |
| 1331 |
spacer += " " |
| 1332 |
txt.append(obj.Label + spacer + ifctype) |
| 1333 |
|
| 1334 |
|
| 1335 |
for g in groups.keys(): |
| 1336 |
group = FreeCAD.ActiveDocument.getObject(g) |
| 1337 |
if group: |
| 1338 |
for o in group.Group: |
| 1339 |
if o.Name == obj.Name: |
| 1340 |
groups[g].append(product) |
| 1341 |
|
| 1342 |
else: |
| 1343 |
unprocessed.append(obj) |
| 1344 |
else: |
| 1345 |
if DEBUG: |
| 1346 |
print("Object type ", otype, " is not supported yet.") |
| 1347 |
|
| 1348 |
|
| 1349 |
for name, entities in groups.items(): |
| 1350 |
if entities: |
| 1351 |
o = FreeCAD.ActiveDocument.getObject(name) |
| 1352 |
if o: |
| 1353 |
if DEBUG: |
| 1354 |
print("Adding group ", o.Label, " with ", len(entities), " elements") |
| 1355 |
grp = ifc.addGroup(entities, o.Label) |
| 1356 |
|
| 1357 |
ifc.write() |
| 1358 |
|
| 1359 |
if exporttxt: |
| 1360 |
import os |
| 1361 |
import time |
| 1362 |
|
| 1363 |
txtstring = "List of objects exported by FreeCAD in file\n" |
| 1364 |
txtstring += filename + "\n" |
| 1365 |
txtstring += "On " + time.ctime() + "\n" |
| 1366 |
txtstring += "\n" |
| 1367 |
txtstring += str(len(txt)) + " objects exported:\n" |
| 1368 |
txtstring += "\n" |
| 1369 |
txtstring += "Nr Name Type\n" |
| 1370 |
txtstring += "\n" |
| 1371 |
for i in range(len(txt)): |
| 1372 |
idx = str(i + 1) |
| 1373 |
sp = "" |
| 1374 |
for j in range(8 - len(idx)): |
| 1375 |
sp += " " |
| 1376 |
txtstring += idx + sp + txt[i] + "\n" |
| 1377 |
txtfile = os.path.splitext(filename)[0] + ".txt" |
| 1378 |
f = pyopen(txtfile, "wb") |
| 1379 |
f.write(txtstring) |
| 1380 |
f.close() |
| 1381 |
|
| 1382 |
FreeCAD.ActiveDocument.recompute() |
| 1383 |
|
| 1384 |
if unprocessed: |
| 1385 |
print( |
| 1386 |
"\nWARNING: " |
| 1387 |
+ str(len(unprocessed)) |
| 1388 |
+ " objects were not exported (stored in importIFC.unprocessed):" |
| 1389 |
) |
| 1390 |
for o in unprocessed: |
| 1391 |
print(" " + o.Label) |
| 1392 |
|
| 1393 |
|
| 1394 |
def getTuples(data, scale=1, placement=None, normal=None, close=True): |
| 1395 |
"""getTuples(data,[scale,placement,normal,close]): returns a tuple or a list of tuples from a vector |
| 1396 |
or from the vertices of a shape. Scale can indicate a scale factor""" |
| 1397 |
rnd = False |
| 1398 |
import Part |
| 1399 |
|
| 1400 |
if isinstance(data, FreeCAD.Vector): |
| 1401 |
if placement: |
| 1402 |
data = placement.multVec(data) |
| 1403 |
if rnd: |
| 1404 |
data = DraftVecUtils.rounded(data) |
| 1405 |
return (data.x * scale, data.y * scale, data.z * scale) |
| 1406 |
elif isinstance(data, Part.Shape): |
| 1407 |
t = [] |
| 1408 |
if len(data.Wires) == 1: |
| 1409 |
import Part |
| 1410 |
import DraftGeomUtils |
| 1411 |
|
| 1412 |
data = Part.Wire(Part.__sortEdges__(data.Wires[0].Edges)) |
| 1413 |
verts = data.Vertexes |
| 1414 |
try: |
| 1415 |
c = data.CenterOfMass |
| 1416 |
v1 = verts[0].Point.sub(c) |
| 1417 |
v2 = verts[1].Point.sub(c) |
| 1418 |
if DraftVecUtils.angle(v2, v1, normal) >= 0: |
| 1419 |
|
| 1420 |
verts.reverse() |
| 1421 |
except Exception: |
| 1422 |
pass |
| 1423 |
for v in verts: |
| 1424 |
pt = v.Point |
| 1425 |
if placement: |
| 1426 |
if not placement.isIdentity(): |
| 1427 |
pt = placement.multVec(pt) |
| 1428 |
if rnd: |
| 1429 |
pt = DraftVecUtils.rounded(pt) |
| 1430 |
t.append((pt.x * scale, pt.y * scale, pt.z * scale)) |
| 1431 |
|
| 1432 |
if close: |
| 1433 |
t.append(t[0]) |
| 1434 |
else: |
| 1435 |
print("Arch.getTuples(): Wrong profile data") |
| 1436 |
return t |
| 1437 |
|
| 1438 |
|
| 1439 |
def getIfcExtrusionData(obj, scale=1, nosubs=False): |
| 1440 |
"""getIfcExtrusionData(obj,[scale,nosubs]): returns a closed path (a list of tuples), a tuple expressing an extrusion |
| 1441 |
vector, and a list of 3 tuples for base position, x axis and z axis. Or returns None, if a base loop and |
| 1442 |
an extrusion direction cannot be extracted. Scale can indicate a scale factor.""" |
| 1443 |
|
| 1444 |
CURVEMODE = "PARAMETER" |
| 1445 |
|
| 1446 |
if hasattr(obj, "Additions"): |
| 1447 |
if obj.Additions: |
| 1448 |
|
| 1449 |
return None |
| 1450 |
if hasattr(obj, "Subtractions") and not nosubs: |
| 1451 |
if obj.Subtractions: |
| 1452 |
return None |
| 1453 |
if hasattr(obj, "Proxy"): |
| 1454 |
if hasattr(obj.Proxy, "getProfiles"): |
| 1455 |
p = obj.Proxy.getProfiles(obj, noplacement=True) |
| 1456 |
v = obj.Proxy.getExtrusionVector(obj, noplacement=True) |
| 1457 |
if (len(p) == 1) and v: |
| 1458 |
p = p[0] |
| 1459 |
r = FreeCAD.Placement() |
| 1460 |
|
| 1461 |
r = obj.Proxy.getPlacement(obj) |
| 1462 |
|
| 1463 |
|
| 1464 |
d = [ |
| 1465 |
r.Base, |
| 1466 |
DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(1, 0, 0))), |
| 1467 |
DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(0, 0, 1))), |
| 1468 |
] |
| 1469 |
|
| 1470 |
|
| 1471 |
import Part |
| 1472 |
|
| 1473 |
if len(p.Edges) == 1: |
| 1474 |
if isinstance(p.Edges[0].Curve, Part.Circle): |
| 1475 |
|
| 1476 |
r1 = p.Edges[0].Curve.Radius * scale |
| 1477 |
return ( |
| 1478 |
"circle", |
| 1479 |
[getTuples(p.Edges[0].Curve.Center, scale), r1], |
| 1480 |
getTuples(v, scale), |
| 1481 |
d, |
| 1482 |
) |
| 1483 |
elif isinstance(p.Edges[0].Curve, Part.Ellipse): |
| 1484 |
|
| 1485 |
r1 = p.Edges[0].Curve.MajorRadius * scale |
| 1486 |
r2 = p.Edges[0].Curve.MinorRadius * scale |
| 1487 |
return ( |
| 1488 |
"ellipse", |
| 1489 |
[getTuples(p.Edges[0].Curve.Center, scale), r1, r2], |
| 1490 |
getTuples(v, scale), |
| 1491 |
d, |
| 1492 |
) |
| 1493 |
curves = False |
| 1494 |
for e in p.Edges: |
| 1495 |
if isinstance(e.Curve, Part.Circle): |
| 1496 |
curves = True |
| 1497 |
elif not isinstance(e.Curve, Part.LineSegment): |
| 1498 |
print("Arch.getIfcExtrusionData: Warning: unsupported edge type in profile") |
| 1499 |
if curves: |
| 1500 |
|
| 1501 |
ecurves = [] |
| 1502 |
last = None |
| 1503 |
import DraftGeomUtils |
| 1504 |
|
| 1505 |
edges = Part.__sortEdges__(p.Edges) |
| 1506 |
for e in edges: |
| 1507 |
if isinstance(e.Curve, Part.Circle): |
| 1508 |
follow = True |
| 1509 |
if last: |
| 1510 |
if not DraftVecUtils.equals(last, e.Vertexes[0].Point): |
| 1511 |
follow = False |
| 1512 |
last = e.Vertexes[0].Point |
| 1513 |
else: |
| 1514 |
last = e.Vertexes[-1].Point |
| 1515 |
else: |
| 1516 |
last = e.Vertexes[-1].Point |
| 1517 |
p1 = math.degrees( |
| 1518 |
-DraftVecUtils.angle(e.Vertexes[0].Point.sub(e.Curve.Center)) |
| 1519 |
) |
| 1520 |
p2 = math.degrees( |
| 1521 |
-DraftVecUtils.angle(e.Vertexes[-1].Point.sub(e.Curve.Center)) |
| 1522 |
) |
| 1523 |
da = DraftVecUtils.angle( |
| 1524 |
e.valueAt(e.FirstParameter + 0.1).sub(e.Curve.Center), |
| 1525 |
e.Vertexes[0].Point.sub(e.Curve.Center), |
| 1526 |
) |
| 1527 |
if p1 < 0: |
| 1528 |
p1 = 360 + p1 |
| 1529 |
if p2 < 0: |
| 1530 |
p2 = 360 + p2 |
| 1531 |
if da > 0: |
| 1532 |
follow = not (follow) |
| 1533 |
if CURVEMODE == "CARTESIAN": |
| 1534 |
|
| 1535 |
p1 = getTuples(e.Vertexes[0].Point, scale) |
| 1536 |
p2 = getTuples(e.Vertexes[-1].Point, scale) |
| 1537 |
ecurves.append( |
| 1538 |
[ |
| 1539 |
"arc", |
| 1540 |
getTuples(e.Curve.Center, scale), |
| 1541 |
e.Curve.Radius * scale, |
| 1542 |
[p1, p2], |
| 1543 |
follow, |
| 1544 |
CURVEMODE, |
| 1545 |
] |
| 1546 |
) |
| 1547 |
else: |
| 1548 |
verts = [vertex.Point for vertex in e.Vertexes] |
| 1549 |
if last: |
| 1550 |
if not DraftVecUtils.equals(last, verts[0]): |
| 1551 |
verts.reverse() |
| 1552 |
last = e.Vertexes[0].Point |
| 1553 |
else: |
| 1554 |
last = e.Vertexes[-1].Point |
| 1555 |
else: |
| 1556 |
last = e.Vertexes[-1].Point |
| 1557 |
ecurves.append(["line", [getTuples(vert, scale) for vert in verts]]) |
| 1558 |
return "composite", ecurves, getTuples(v, scale), d |
| 1559 |
else: |
| 1560 |
|
| 1561 |
return "polyline", getTuples(p, scale), getTuples(v, scale), d |
| 1562 |
return None |
| 1563 |
|
| 1564 |
|
| 1565 |
def getIfcBrepFacesData(obj, scale=1, sub=False, tessellation=1): |
| 1566 |
"""getIfcBrepFacesData(obj,[scale,tessellation]): returns a list(0) of lists(1) of lists(2) of lists(3), |
| 1567 |
list(3) being a list of vertices defining a loop, list(2) describing a face from one or |
| 1568 |
more loops, list(1) being the whole solid made of several faces, list(0) being the list |
| 1569 |
of solids inside the object. Scale can indicate a scaling factor. Tessellation is the tessellation |
| 1570 |
factor to apply on curved faces.""" |
| 1571 |
shape = None |
| 1572 |
if sub: |
| 1573 |
if hasattr(obj, "Proxy"): |
| 1574 |
if hasattr(obj.Proxy, "getSubVolume"): |
| 1575 |
shape = obj.Proxy.getSubVolume(obj) |
| 1576 |
if not shape: |
| 1577 |
if hasattr(obj, "Shape"): |
| 1578 |
if obj.Shape: |
| 1579 |
if not obj.Shape.isNull(): |
| 1580 |
|
| 1581 |
shape = obj.Shape |
| 1582 |
elif hasattr(obj, "Terrain"): |
| 1583 |
if obj.Terrain: |
| 1584 |
if hasattr(obj.Terrain, "Shape"): |
| 1585 |
if obj.Terrain.Shape: |
| 1586 |
if not obj.Terrain.Shape.isNull(): |
| 1587 |
if obj.Terrain.Shape.isValid(): |
| 1588 |
shape = obj.Terrain.Shape |
| 1589 |
if shape: |
| 1590 |
import Part |
| 1591 |
|
| 1592 |
sols = [] |
| 1593 |
if shape.Solids: |
| 1594 |
dataset = shape.Solids |
| 1595 |
else: |
| 1596 |
dataset = shape.Shells |
| 1597 |
print("Warning! object contains no solids") |
| 1598 |
for sol in shape.Solids: |
| 1599 |
s = [] |
| 1600 |
curves = False |
| 1601 |
for face in sol.Faces: |
| 1602 |
for e in face.Edges: |
| 1603 |
if not isinstance(e.Curve, Part.LineSegment): |
| 1604 |
curves = True |
| 1605 |
if curves: |
| 1606 |
tris = sol.tessellate(tessellation) |
| 1607 |
for tri in tris[1]: |
| 1608 |
f = [] |
| 1609 |
for i in tri: |
| 1610 |
f.append(getTuples(tris[0][i], scale)) |
| 1611 |
s.append([f]) |
| 1612 |
else: |
| 1613 |
for face in sol.Faces: |
| 1614 |
f = [] |
| 1615 |
f.append( |
| 1616 |
getTuples(face.OuterWire, scale, normal=face.normalAt(0, 0), close=False) |
| 1617 |
) |
| 1618 |
for wire in face.Wires: |
| 1619 |
if wire.hashCode() != face.OuterWire.hashCode(): |
| 1620 |
f.append( |
| 1621 |
getTuples( |
| 1622 |
wire, |
| 1623 |
scale, |
| 1624 |
normal=DraftVecUtils.neg(face.normalAt(0, 0)), |
| 1625 |
close=False, |
| 1626 |
) |
| 1627 |
) |
| 1628 |
s.append(f) |
| 1629 |
sols.append(s) |
| 1630 |
return sols |
| 1631 |
return None |
| 1632 |
|
| 1633 |
|
| 1634 |
def getIfcElevation(obj): |
| 1635 |
"""getIfcElevation(obj): Returns the lowest height (Z coordinate) of this object""" |
| 1636 |
if obj.isDerivedFrom("Part::Feature"): |
| 1637 |
b = obj.Shape.BoundBox |
| 1638 |
return b.ZMin |
| 1639 |
return 0 |
| 1640 |
|
| 1641 |
|
| 1642 |
def explore(filename=None): |
| 1643 |
"explore the contents of an ifc file in a Qt dialog" |
| 1644 |
if not filename: |
| 1645 |
from PySide import QtGui |
| 1646 |
|
| 1647 |
filename = QtGui.QFileDialog.getOpenFileName( |
| 1648 |
QtGui.QApplication.activeWindow(), "Open IFC file", None, "IFC files (*.ifc *.IFC)" |
| 1649 |
) |
| 1650 |
if filename: |
| 1651 |
filename = filename[0] |
| 1652 |
if filename: |
| 1653 |
getConfig() |
| 1654 |
schema = getSchema() |
| 1655 |
d = explorer(filename, schema) |
| 1656 |
d.show() |
| 1657 |
return d |
| 1658 |
|
| 1659 |
|
| 1660 |
|
| 1661 |
|
| 1662 |
|
| 1663 |
class IfcSchema: |
| 1664 |
SIMPLETYPES = ["INTEGER", "REAL", "STRING", "NUMBER", "LOGICAL", "BOOLEAN"] |
| 1665 |
NO_ATTR = ["WHERE", "INVERSE", "WR2", "WR3", "WR4", "WR5", "UNIQUE", "DERIVE"] |
| 1666 |
|
| 1667 |
def __init__(self, filename): |
| 1668 |
self.filename = filename |
| 1669 |
if not os.path.exists(filename): |
| 1670 |
filename = FreeCAD.getUserMacroDir(True) + os.sep + filename |
| 1671 |
if not os.path.exists(filename): |
| 1672 |
raise ImportError("no IFCSchema file found!") |
| 1673 |
|
| 1674 |
self.file = open(self.filename) |
| 1675 |
self.data = self.file.read() |
| 1676 |
self.types = self.readTypes() |
| 1677 |
self.entities = self.readEntities() |
| 1678 |
if DEBUG: |
| 1679 |
print( |
| 1680 |
"Parsed from schema %s: %s entities and %s types" |
| 1681 |
% (self.filename, len(self.entities), len(self.types)) |
| 1682 |
) |
| 1683 |
|
| 1684 |
def readTypes(self): |
| 1685 |
""" |
| 1686 |
Parse all the possible types from the schema, |
| 1687 |
returns a dictionary Name -> Type |
| 1688 |
""" |
| 1689 |
types = {} |
| 1690 |
for m in re.finditer("TYPE (.*) = (.*);", self.data): |
| 1691 |
typename, typetype = m.groups() |
| 1692 |
if typetype in self.SIMPLETYPES: |
| 1693 |
types[typename] = typetype |
| 1694 |
else: |
| 1695 |
types[typename] = "#" + typetype |
| 1696 |
|
| 1697 |
return types |
| 1698 |
|
| 1699 |
def readEntities(self): |
| 1700 |
""" |
| 1701 |
Parse all the possible entities from the schema, |
| 1702 |
returns a dictionary of the form: |
| 1703 |
{ name: { |
| 1704 |
"supertype": supertype, |
| 1705 |
"attributes": [{ key: value }, ..] |
| 1706 |
}} |
| 1707 |
""" |
| 1708 |
entities = {} |
| 1709 |
|
| 1710 |
|
| 1711 |
|
| 1712 |
for m in re.finditer("ENTITY (.*?)END_ENTITY;", self.data, re.DOTALL): |
| 1713 |
entity = {} |
| 1714 |
raw_entity_str = m.groups()[0] |
| 1715 |
|
| 1716 |
entity["name"] = re.search(r"(.*?)[;|\s]", raw_entity_str).groups()[0].upper() |
| 1717 |
|
| 1718 |
subtypeofmatch = re.search(r".*SUBTYPE OF \((.*?)\);", raw_entity_str) |
| 1719 |
entity["supertype"] = subtypeofmatch.groups()[0].upper() if subtypeofmatch else None |
| 1720 |
|
| 1721 |
|
| 1722 |
|
| 1723 |
inner_str = re.search(";(.*?)$", raw_entity_str, re.DOTALL).groups()[0] |
| 1724 |
|
| 1725 |
attrs_str = min([inner_str.partition("\r\n " + a)[0] for a in self.NO_ATTR]) |
| 1726 |
attrs = [] |
| 1727 |
for am in re.finditer("(.*?) : (.*?);", attrs_str, re.DOTALL): |
| 1728 |
name, attr_type = [s.replace("\r\n\t", "") for s in am.groups()] |
| 1729 |
attrs.append((name, attr_type)) |
| 1730 |
|
| 1731 |
entity["attributes"] = attrs |
| 1732 |
entities[entity["name"]] = entity |
| 1733 |
|
| 1734 |
return entities |
| 1735 |
|
| 1736 |
def getAttributes(self, name): |
| 1737 |
""" |
| 1738 |
Get all attributes af an entity, including supertypes |
| 1739 |
""" |
| 1740 |
ent = self.entities[name] |
| 1741 |
|
| 1742 |
attrs = [] |
| 1743 |
while ent is not None: |
| 1744 |
this_ent_attrs = copy.copy(ent["attributes"]) |
| 1745 |
this_ent_attrs.reverse() |
| 1746 |
attrs.extend(this_ent_attrs) |
| 1747 |
ent = self.entities.get(ent["supertype"], None) |
| 1748 |
|
| 1749 |
attrs.reverse() |
| 1750 |
return attrs |
| 1751 |
|
| 1752 |
def capitalize(self, name): |
| 1753 |
"returns a capitalized version of a type" |
| 1754 |
if name.upper() in self.data.upper(): |
| 1755 |
i1 = self.data.upper().index(name.upper()) |
| 1756 |
i2 = i1 + len(name) |
| 1757 |
name = self.data[i1:i2] |
| 1758 |
return name |
| 1759 |
|
| 1760 |
|
| 1761 |
class IfcFile: |
| 1762 |
""" |
| 1763 |
Parses an ifc file given by filename, entities can be retrieved by name and id |
| 1764 |
The whole file is stored in a dictionary (in memory) |
| 1765 |
""" |
| 1766 |
|
| 1767 |
entsById = {} |
| 1768 |
entsByName = {} |
| 1769 |
|
| 1770 |
def __init__(self, filename, schema): |
| 1771 |
self.filename = filename |
| 1772 |
self.schema = IfcSchema(schema) |
| 1773 |
self.file = open(self.filename) |
| 1774 |
self.entById, self.entsByName, self.header = self.read() |
| 1775 |
self.file.close() |
| 1776 |
if DEBUG: |
| 1777 |
print("Parsed from file %s: %s entities" % (self.filename, len(self.entById))) |
| 1778 |
|
| 1779 |
def getEntityById(self, id): |
| 1780 |
return self.entById.get(id, None) |
| 1781 |
|
| 1782 |
def getEntitiesByName(self, name): |
| 1783 |
return self.entsByName.get(name, None) |
| 1784 |
|
| 1785 |
def read(self): |
| 1786 |
""" |
| 1787 |
Returns 2 dictionaries, entById and entsByName |
| 1788 |
""" |
| 1789 |
entById = {} |
| 1790 |
entsByName = {} |
| 1791 |
header = "HEADER " |
| 1792 |
readheader = False |
| 1793 |
for line in self.file: |
| 1794 |
e = self.parseLine(line) |
| 1795 |
if e: |
| 1796 |
entById[int(e["id"])] = e |
| 1797 |
ids = e.get(e["name"], []) |
| 1798 |
ids.append(e["id"]) |
| 1799 |
entsByName[e["name"]] = list(set(ids)) |
| 1800 |
elif "HEADER" in line: |
| 1801 |
readheader = True |
| 1802 |
elif readheader: |
| 1803 |
if "ENDSEC" in line: |
| 1804 |
readheader = False |
| 1805 |
else: |
| 1806 |
header += line |
| 1807 |
|
| 1808 |
return [entById, entsByName, header] |
| 1809 |
|
| 1810 |
def parseLine(self, line): |
| 1811 |
""" |
| 1812 |
Parse a line |
| 1813 |
""" |
| 1814 |
m = IFCLINE_RE.search(line) |
| 1815 |
if m: |
| 1816 |
id, name, attrs = m.groups() |
| 1817 |
id = id.strip() |
| 1818 |
name = name.strip() |
| 1819 |
attrs = attrs.strip() |
| 1820 |
else: |
| 1821 |
return False |
| 1822 |
|
| 1823 |
return {"id": id, "name": name, "attributes": self.parseAttributes(name, attrs)} |
| 1824 |
|
| 1825 |
def parseAttributes(self, ent_name, attrs_str): |
| 1826 |
""" |
| 1827 |
Parse the attributes of a line |
| 1828 |
""" |
| 1829 |
parts = [] |
| 1830 |
lastpos = 0 |
| 1831 |
|
| 1832 |
while lastpos < len(attrs_str): |
| 1833 |
newpos = self.nextString(attrs_str, lastpos) |
| 1834 |
parts.extend(self.parseAttribute(attrs_str[lastpos : newpos - 1])) |
| 1835 |
lastpos = newpos |
| 1836 |
|
| 1837 |
schema_attributes = self.schema.getAttributes(ent_name) |
| 1838 |
|
| 1839 |
assert len(schema_attributes) == len( |
| 1840 |
parts |
| 1841 |
), "Expected %s attributes, got %s (entity: %s" % ( |
| 1842 |
len(schema_attributes), |
| 1843 |
len(parts), |
| 1844 |
ent_name, |
| 1845 |
) |
| 1846 |
|
| 1847 |
attribute_names = [a[0] for a in schema_attributes] |
| 1848 |
|
| 1849 |
return dict(zip(attribute_names, parts)) |
| 1850 |
|
| 1851 |
def parseAttribute(self, attr_str): |
| 1852 |
""" |
| 1853 |
Map a single attribute to a python type (recursively) |
| 1854 |
""" |
| 1855 |
parts = [] |
| 1856 |
lastpos = 0 |
| 1857 |
while lastpos < len(attr_str): |
| 1858 |
newpos = self.nextString(attr_str, lastpos) |
| 1859 |
s = attr_str[lastpos : newpos - 1] |
| 1860 |
if s[0] == "(" and s[-1] == ")": |
| 1861 |
parts.append(self.parseAttribute(s[1:-1])) |
| 1862 |
else: |
| 1863 |
try: |
| 1864 |
parts.append(float(s)) |
| 1865 |
except ValueError: |
| 1866 |
if s[0] == "'" and s[-1] == "'": |
| 1867 |
parts.append(s[1:-1]) |
| 1868 |
elif s == "$": |
| 1869 |
parts.append(None) |
| 1870 |
else: |
| 1871 |
parts.append(s) |
| 1872 |
|
| 1873 |
lastpos = newpos |
| 1874 |
|
| 1875 |
return parts |
| 1876 |
|
| 1877 |
def nextString(self, s, start): |
| 1878 |
""" |
| 1879 |
Parse the data part of a line |
| 1880 |
""" |
| 1881 |
parens = 0 |
| 1882 |
quotes = 0 |
| 1883 |
|
| 1884 |
for pos in range(start, len(s)): |
| 1885 |
c = s[pos] |
| 1886 |
if c == "," and parens == 0 and quotes == 0: |
| 1887 |
return pos + 1 |
| 1888 |
elif c == "(" and quotes == 0: |
| 1889 |
parens += 1 |
| 1890 |
elif c == ")" and quotes == 0: |
| 1891 |
parens -= 1 |
| 1892 |
elif c == "'" and quotes == 0: |
| 1893 |
quotes = 1 |
| 1894 |
elif c == "'" and quotes == 1: |
| 1895 |
quotes = 0 |
| 1896 |
|
| 1897 |
return len(s) + 1 |
| 1898 |
|
| 1899 |
|
| 1900 |
class IfcEntity: |
| 1901 |
"a container for an IFC entity" |
| 1902 |
|
| 1903 |
def __init__(self, ent, doc=None): |
| 1904 |
self.data = ent |
| 1905 |
self.id = int(ent["id"]) |
| 1906 |
self.type = ent["name"].upper().strip(",[]()") |
| 1907 |
self.attributes = ent["attributes"] |
| 1908 |
self.doc = doc |
| 1909 |
|
| 1910 |
def __repr__(self): |
| 1911 |
return str(self.id) + " : " + self.type + " " + str(self.attributes) |
| 1912 |
|
| 1913 |
def getProperties(self): |
| 1914 |
return self.doc.find("IFCRELDEFINESBYPROPERTIES", "RelatedObjects", self) |
| 1915 |
|
| 1916 |
def getProperty(self, propName): |
| 1917 |
"finds the value of the given property or quantity in this object, if exists" |
| 1918 |
propsets = self.doc.find("IFCRELDEFINESBYPROPERTIES", "RelatedObjects", self) |
| 1919 |
if not propsets: |
| 1920 |
return None |
| 1921 |
propset = [] |
| 1922 |
for p in propsets: |
| 1923 |
if hasattr(p.RelatingPropertyDefinition, "HasProperties"): |
| 1924 |
propset.extend(p.RelatingPropertyDefinition.HasProperties) |
| 1925 |
elif hasattr(p.RelatingPropertyDefinition, "Quantities"): |
| 1926 |
propset.extend(p.RelatingPropertyDefinition.Quantities) |
| 1927 |
for prop in propset: |
| 1928 |
if prop.Name == propName: |
| 1929 |
print("found valid", prop) |
| 1930 |
if hasattr(prop, "LengthValue"): |
| 1931 |
return prop.LengthValue |
| 1932 |
elif hasattr(prop, "AreaValue"): |
| 1933 |
return prop.AreaValue |
| 1934 |
elif hasattr(prop, "VolumeValue"): |
| 1935 |
return prop.VolumeValue |
| 1936 |
elif hasattr(prop, "NominalValue"): |
| 1937 |
return prop.NominalValue |
| 1938 |
return None |
| 1939 |
|
| 1940 |
def getAttribute(self, attr): |
| 1941 |
"returns the value of the given attribute, if exists" |
| 1942 |
if hasattr(self, attr): |
| 1943 |
return self.__dict__[attr] |
| 1944 |
return None |
| 1945 |
|
| 1946 |
|
| 1947 |
class IfcDocument: |
| 1948 |
"an object representing an IFC document" |
| 1949 |
|
| 1950 |
def __init__(self, filename, schema="IFC2X3_TC1.exp"): |
| 1951 |
f = IfcFile(filename, schema) |
| 1952 |
self.filename = filename |
| 1953 |
self.data = f.entById |
| 1954 |
self.Entities = {0: f.header} |
| 1955 |
for k, e in self.data.items(): |
| 1956 |
eid = int(e["id"]) |
| 1957 |
self.Entities[eid] = IfcEntity(e, self) |
| 1958 |
if DEBUG: |
| 1959 |
print(len(self.Entities), "entities created. Creating attributes...") |
| 1960 |
for k, ent in self.Entities.items(): |
| 1961 |
if DEBUG: |
| 1962 |
print("attributing entity ", ent) |
| 1963 |
if hasattr(ent, "attributes"): |
| 1964 |
for k, v in ent.attributes.items(): |
| 1965 |
if DEBUG: |
| 1966 |
print("parsing attribute: ", k, " value ", v) |
| 1967 |
if isinstance(v, str): |
| 1968 |
val = self.__clean__(v) |
| 1969 |
elif isinstance(v, list): |
| 1970 |
val = [] |
| 1971 |
for item in v: |
| 1972 |
if isinstance(item, str): |
| 1973 |
val.append(self.__clean__(item)) |
| 1974 |
else: |
| 1975 |
val.append(item) |
| 1976 |
else: |
| 1977 |
val = v |
| 1978 |
setattr(ent, k.strip(), val) |
| 1979 |
if DEBUG: |
| 1980 |
print("Document successfully created") |
| 1981 |
|
| 1982 |
def __clean__(self, value): |
| 1983 |
"turns an attribute value into something usable" |
| 1984 |
try: |
| 1985 |
val = value.strip(" ()'") |
| 1986 |
if val[:3].upper() == "IFC": |
| 1987 |
if "IFCTEXT" in val.upper(): |
| 1988 |
l = val.split("'") |
| 1989 |
if len(l) == 3: |
| 1990 |
val = l[1] |
| 1991 |
elif "IFCBOOLEAN" in value.upper(): |
| 1992 |
l = val.split(".") |
| 1993 |
if len(l) == 3: |
| 1994 |
val = l[1] |
| 1995 |
if val.upper() == "F": |
| 1996 |
val = False |
| 1997 |
elif val.upper() == "T": |
| 1998 |
val = True |
| 1999 |
elif "IFCREAL" in val.upper(): |
| 2000 |
l = val.split("(") |
| 2001 |
if len(l) == 2: |
| 2002 |
val = float(l[1].strip(")")) |
| 2003 |
else: |
| 2004 |
if "#" in val: |
| 2005 |
if "," in val: |
| 2006 |
val = val.split(",") |
| 2007 |
l = [] |
| 2008 |
for subval in val: |
| 2009 |
if "#" in subval: |
| 2010 |
s = subval.strip(" #") |
| 2011 |
if DEBUG: |
| 2012 |
print("referencing ", s, " : ", self.getEnt(int(s))) |
| 2013 |
l.append(self.getEnt(int(s))) |
| 2014 |
val = l |
| 2015 |
else: |
| 2016 |
val = val.strip() |
| 2017 |
val = val.replace("#", "") |
| 2018 |
if DEBUG: |
| 2019 |
print("referencing ", val, " : ", self.getEnt(int(val))) |
| 2020 |
val = self.getEnt(int(val)) |
| 2021 |
if not val: |
| 2022 |
val = value |
| 2023 |
except Exception: |
| 2024 |
if DEBUG: |
| 2025 |
print("error parsing attribute", value) |
| 2026 |
val = value |
| 2027 |
return val |
| 2028 |
|
| 2029 |
def __repr__(self): |
| 2030 |
return "IFC Document: " + self.filename + ", " + str(len(self.Entities)) + " entities " |
| 2031 |
|
| 2032 |
def getEnt(self, ref): |
| 2033 |
"gets an entity by id number, or a list of entities by type" |
| 2034 |
if isinstance(ref, int): |
| 2035 |
if ref in self.Entities: |
| 2036 |
return self.Entities[ref] |
| 2037 |
elif isinstance(ref, str): |
| 2038 |
l = [] |
| 2039 |
ref = ref.upper() |
| 2040 |
for k, ob in self.Entities.items(): |
| 2041 |
if hasattr(ob, "type"): |
| 2042 |
if ob.type == ref: |
| 2043 |
l.append(ob) |
| 2044 |
return l |
| 2045 |
return None |
| 2046 |
|
| 2047 |
def search(self, pat): |
| 2048 |
"searches entities types for partial match" |
| 2049 |
l = [] |
| 2050 |
pat = pat.upper() |
| 2051 |
for k, ob in self.Entities.items(): |
| 2052 |
if hasattr(ob, "type"): |
| 2053 |
if pat in ob.type: |
| 2054 |
if not ob.type in l: |
| 2055 |
l.append(ob.type) |
| 2056 |
return l |
| 2057 |
|
| 2058 |
def find(self, pat1, pat2=None, pat3=None): |
| 2059 |
"""finds objects in the current IFC document. |
| 2060 |
arguments can be of the following form: |
| 2061 |
- (pattern): returns object types matching the given pattern (same as search) |
| 2062 |
- (type,property,value): finds, in all objects of type "type", those whose |
| 2063 |
property "property" has the given value |
| 2064 |
""" |
| 2065 |
if pat3: |
| 2066 |
bobs = self.getEnt(pat1) |
| 2067 |
obs = [] |
| 2068 |
for bob in bobs: |
| 2069 |
if hasattr(bob, pat2): |
| 2070 |
if bob.getAttribute(pat2) == pat3: |
| 2071 |
obs.append(bob) |
| 2072 |
return obs |
| 2073 |
elif pat1: |
| 2074 |
ll = self.search(pat1) |
| 2075 |
obs = [] |
| 2076 |
for l in ll: |
| 2077 |
obs.extend(self.getEnt(l)) |
| 2078 |
return obs |
| 2079 |
return None |
| 2080 |
|
| 2081 |
|
| 2082 |
def explorer(filename, schema="IFC2X3_TC1.exp"): |
| 2083 |
"returns a PySide dialog showing the contents of an IFC file" |
| 2084 |
from PySide import QtGui |
| 2085 |
|
| 2086 |
ifc = IfcDocument(filename, schema) |
| 2087 |
schema = IfcSchema(schema) |
| 2088 |
tree = QtGui.QTreeWidget() |
| 2089 |
tree.setColumnCount(3) |
| 2090 |
tree.setWordWrap(True) |
| 2091 |
tree.header().setDefaultSectionSize(60) |
| 2092 |
tree.header().resizeSection(0, 60) |
| 2093 |
tree.header().resizeSection(1, 30) |
| 2094 |
tree.header().setStretchLastSection(True) |
| 2095 |
tree.headerItem().setText(0, "ID") |
| 2096 |
tree.headerItem().setText(1, "") |
| 2097 |
tree.headerItem().setText(2, "Item and Properties") |
| 2098 |
bold = QtGui.QFont() |
| 2099 |
bold.setBold(True) |
| 2100 |
|
| 2101 |
|
| 2102 |
|
| 2103 |
for i in ifc.Entities.keys(): |
| 2104 |
e = ifc.Entities[i] |
| 2105 |
item = QtGui.QTreeWidgetItem(tree) |
| 2106 |
if hasattr(e, "id"): |
| 2107 |
item.setText(0, str(e.id)) |
| 2108 |
if e.type in ["IFCWALL", "IFCWALLSTANDARDCASE"]: |
| 2109 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Wall_Tree.svg")) |
| 2110 |
elif e.type in ["IFCCOLUMN", "IFCBEAM", "IFCSLAB", "IFCFOOTING"]: |
| 2111 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Structure_Tree.svg")) |
| 2112 |
elif e.type in ["IFCSITE"]: |
| 2113 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Site_Tree.svg")) |
| 2114 |
elif e.type in ["IFCBUILDING"]: |
| 2115 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Building_Tree.svg")) |
| 2116 |
elif e.type in ["IFCSTOREY"]: |
| 2117 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Floor_Tree.svg")) |
| 2118 |
elif e.type in ["IFCWINDOW"]: |
| 2119 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Window_Tree.svg")) |
| 2120 |
elif e.type in ["IFCROOF"]: |
| 2121 |
item.setIcon(1, QtGui.QIcon(":icons/Arch_Roof_Tree.svg")) |
| 2122 |
elif e.type in ["IFCEXTRUDEDAREASOLID", "IFCCLOSEDSHELL"]: |
| 2123 |
item.setIcon(1, QtGui.QIcon(":/icons/Part_3D_object.svg")) |
| 2124 |
elif e.type in ["IFCFACE"]: |
| 2125 |
item.setIcon(1, QtGui.QIcon(":icons/Draft_SwitchMode.svg")) |
| 2126 |
elif e.type in ["IFCARBITRARYCLOSEDPROFILEDEF", "IFCPOLYLOOP"]: |
| 2127 |
item.setIcon(1, QtGui.QIcon(":icons/Draft_Draft.svg")) |
| 2128 |
item.setText(2, str(schema.capitalize(e.type))) |
| 2129 |
item.setFont(2, bold) |
| 2130 |
for a in e.attributes.keys(): |
| 2131 |
if hasattr(e, a): |
| 2132 |
if not a.upper() in ["ID", "GLOBALID"]: |
| 2133 |
v = getattr(e, a) |
| 2134 |
if isinstance(v, IfcEntity): |
| 2135 |
t = "Entity #" + str(v.id) + ": " + str(v.type) |
| 2136 |
elif isinstance(v, list): |
| 2137 |
t = "" |
| 2138 |
else: |
| 2139 |
t = str(v) |
| 2140 |
t = " " + str(a) + " : " + str(t) |
| 2141 |
item = QtGui.QTreeWidgetItem(tree) |
| 2142 |
item.setText(2, str(t)) |
| 2143 |
if isinstance(v, list): |
| 2144 |
for vi in v: |
| 2145 |
if isinstance(vi, IfcEntity): |
| 2146 |
t = "Entity #" + str(vi.id) + ": " + str(vi.type) |
| 2147 |
else: |
| 2148 |
t = vi |
| 2149 |
t = " " + str(t) |
| 2150 |
item = QtGui.QTreeWidgetItem(tree) |
| 2151 |
item.setText(2, str(t)) |
| 2152 |
|
| 2153 |
d = QtGui.QDialog() |
| 2154 |
d.setObjectName("IfcExplorer") |
| 2155 |
d.setWindowTitle("IFC Explorer") |
| 2156 |
d.resize(640, 480) |
| 2157 |
layout = QtGui.QVBoxLayout(d) |
| 2158 |
layout.addWidget(tree) |
| 2159 |
return d |
| 2160 |
|
| 2161 |
|
| 2162 |
|
| 2163 |
|
| 2164 |
|
| 2165 |
class _tempEntityHolder: |
| 2166 |
"""a temporary object to store entity references |
| 2167 |
to be made into something nicer later...""" |
| 2168 |
|
| 2169 |
def __init__(self): |
| 2170 |
self.refs = [] |
| 2171 |
|
| 2172 |
|
| 2173 |
holder = _tempEntityHolder() |
| 2174 |
|
| 2175 |
|
| 2176 |
def uid(): |
| 2177 |
"""returns a suitable GlobalID""" |
| 2178 |
u = str(uuid.uuid4())[:22] |
| 2179 |
u = u.replace("-", "_") |
| 2180 |
return u |
| 2181 |
|
| 2182 |
|
| 2183 |
def now(string=False): |
| 2184 |
"returns a suitable Ifc Time" |
| 2185 |
if string: |
| 2186 |
return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) |
| 2187 |
else: |
| 2188 |
return int(time.time()) |
| 2189 |
|
| 2190 |
|
| 2191 |
def getPropertyNames(entity): |
| 2192 |
"""getPropertyNames(entity): Returns a dictionary with |
| 2193 |
the numbers and names of the pythonproperties available for |
| 2194 |
this entity""" |
| 2195 |
ents = {} |
| 2196 |
if hasattr(entity, "get_argument_count"): |
| 2197 |
l = entity.get_argument_count() |
| 2198 |
else: |
| 2199 |
l = len(entity) |
| 2200 |
for i in range(l): |
| 2201 |
ents[i] = entity.get_argument_name(i) |
| 2202 |
return ents |
| 2203 |
|
| 2204 |
|
| 2205 |
def getTuple(vec): |
| 2206 |
"""getTuple(vec): returns a tuple from other coordinate |
| 2207 |
structures: tuple, list, 3d vector, or occ vertex""" |
| 2208 |
|
| 2209 |
def fmt(t): |
| 2210 |
t = float(t) |
| 2211 |
t = round(t, Draft.precision()) |
| 2212 |
return t |
| 2213 |
|
| 2214 |
if isinstance(vec, tuple): |
| 2215 |
return tuple([fmt(v) for v in vec]) |
| 2216 |
elif isinstance(vec, list): |
| 2217 |
return tuple([fmt(v) for v in vec]) |
| 2218 |
elif hasattr(vec, "x") and hasattr(vec, "y") and hasattr(vec, "z"): |
| 2219 |
return (fmt(vec.x), fmt(vec.y), fmt(vec.z)) |
| 2220 |
elif hasattr(vec, "X") and hasattr(vec, "Y") and hasattr(vec, "Z"): |
| 2221 |
return (fmt(vec.X), fmt(vec.Y), fmt(vec.Z)) |
| 2222 |
|
| 2223 |
|
| 2224 |
def getValueAndDirection(vec): |
| 2225 |
"""getValueAndDirection(vec): returns a length and a tuple |
| 2226 |
representing a normalized vector from a tuple""" |
| 2227 |
pre = Draft.precision() |
| 2228 |
vec = getTuple(vec) |
| 2229 |
length = round(math.sqrt(vec[0] ** 2 + vec[1] ** 2 + vec[2] ** 2), pre) |
| 2230 |
ratio = 1 / length |
| 2231 |
x = round(vec[0] * ratio, pre) |
| 2232 |
y = round(vec[1] * ratio, pre) |
| 2233 |
z = round(vec[2] * ratio, pre) |
| 2234 |
normal = (x, y, z) |
| 2235 |
return length, normal |
| 2236 |
|
| 2237 |
|
| 2238 |
def create(ifcdoc=None, ifcname=None, arguments=[]): |
| 2239 |
"""create(ifcdoc,ifcname,[arguments]):creates an entity |
| 2240 |
of the given name in the given document and optionally |
| 2241 |
gives it an ordered list of arguments""" |
| 2242 |
if hasattr(ifcw, "Entity"): |
| 2243 |
entity = ifcw.Entity(ifcname) |
| 2244 |
else: |
| 2245 |
entity = ifcw.entity_instance(ifcname) |
| 2246 |
if ifcdoc: |
| 2247 |
ifcdoc.add(entity) |
| 2248 |
|
| 2249 |
holder.refs.append(entity) |
| 2250 |
if not isinstance(arguments, list): |
| 2251 |
arguments = [arguments] |
| 2252 |
for i in range(len(arguments)): |
| 2253 |
arg = arguments[i] |
| 2254 |
if isinstance(arg, tuple): |
| 2255 |
if len(arg) in [2, 3]: |
| 2256 |
if hasattr(ifcw, "Doubles"): |
| 2257 |
arg = ifcw.Doubles(arg) |
| 2258 |
else: |
| 2259 |
arg = ifcw.doubles(arg) |
| 2260 |
entity.set_argument(i, arg) |
| 2261 |
return entity |
| 2262 |
|
| 2263 |
|
| 2264 |
class IfcWriter(object): |
| 2265 |
"""IfcWriter([filepath,name,owner,organization,application,version]) |
| 2266 |
Creates an empty IFC document.""" |
| 2267 |
|
| 2268 |
def __init__( |
| 2269 |
self, |
| 2270 |
filepath="", |
| 2271 |
name="", |
| 2272 |
owner="", |
| 2273 |
organization="", |
| 2274 |
application="Python IFC exporter", |
| 2275 |
version="0.0", |
| 2276 |
): |
| 2277 |
if hasattr(ifcw, "IfcFile"): |
| 2278 |
self._fileobject = ifcw.IfcFile() |
| 2279 |
else: |
| 2280 |
self._fileobject = ifcw.file() |
| 2281 |
self._person = create( |
| 2282 |
self._fileobject, "IfcPerson", [None, None, "", None, None, None, None, None] |
| 2283 |
) |
| 2284 |
self._org = create(self._fileobject, "IfcOrganization", [None, "", None, None, None]) |
| 2285 |
pno = create(self._fileobject, "IfcPersonAndOrganization", [self._person, self._org, None]) |
| 2286 |
app = create(self._fileobject, "IfcApplication", [self._org, version, application, uid()]) |
| 2287 |
self._owner = create( |
| 2288 |
self._fileobject, "IfcOwnerHistory", [pno, app, None, "ADDED", None, pno, app, now()] |
| 2289 |
) |
| 2290 |
axp = self.addPlacement(local=False) |
| 2291 |
dim0 = create(self._fileobject, "IfcDirection", getTuple((0, 1, 0))) |
| 2292 |
self._repcontext = create( |
| 2293 |
self._fileobject, |
| 2294 |
"IfcGeometricRepresentationContext", |
| 2295 |
["Plan", "Model", 3, 1.0e-05, axp, dim0], |
| 2296 |
) |
| 2297 |
dim1 = create(self._fileobject, "IfcDimensionalExponents", [0, 0, 0, 0, 0, 0, 0]) |
| 2298 |
dim2 = create(self._fileobject, "IfcSIUnit", [dim1, "LENGTHUNIT", "MILLI", "METRE"]) |
| 2299 |
dim3 = create(self._fileobject, "IfcSIUnit", [dim1, "AREAUNIT", None, "SQUARE_METRE"]) |
| 2300 |
dim4 = create(self._fileobject, "IfcSIUnit", [dim1, "VOLUMEUNIT", None, "CUBIC_METRE"]) |
| 2301 |
dim6 = create(self._fileobject, "IfcSIUnit", [dim1, "PLANEANGLEUNIT", None, "RADIAN"]) |
| 2302 |
dim7 = create(None, "IfcPlaneAngleMeasure", [1.745e-2]) |
| 2303 |
dim8 = create(self._fileobject, "IfcMeasureWithUnit", [dim7, dim6]) |
| 2304 |
dim9 = create( |
| 2305 |
self._fileobject, "IfcConversionBasedUnit", [dim1, "PLANEANGLEUNIT", "DEGREE", dim8] |
| 2306 |
) |
| 2307 |
units = create(self._fileobject, "IfcUnitAssignment", [[dim2, dim3, dim4, dim9]]) |
| 2308 |
self.Project = create( |
| 2309 |
self._fileobject, |
| 2310 |
"IfcProject", |
| 2311 |
[uid(), self._owner, None, None, None, None, None, [self._repcontext], units], |
| 2312 |
) |
| 2313 |
self.Site = None |
| 2314 |
self._storeyRelations = {} |
| 2315 |
self.BuildingProducts = [] |
| 2316 |
self.Storeys = [] |
| 2317 |
self.Buildings = [] |
| 2318 |
self.FilePath = filepath |
| 2319 |
self.Owner = owner |
| 2320 |
self.Organization = organization |
| 2321 |
self.Name = name |
| 2322 |
|
| 2323 |
def __repr__(self): |
| 2324 |
return "IFC document " + self.Name |
| 2325 |
|
| 2326 |
def __setattr__(self, key, value): |
| 2327 |
if value: |
| 2328 |
if key == "Owner": |
| 2329 |
self._person.set_argument(2, str(value)) |
| 2330 |
elif key == "Organization": |
| 2331 |
self._org.set_argument(1, str(value)) |
| 2332 |
elif key == "Name": |
| 2333 |
self.Project.set_argument(2, str(value)) |
| 2334 |
self.__dict__.__setitem__(key, value) |
| 2335 |
|
| 2336 |
def findByName(self, ifctype, name): |
| 2337 |
"finds an entity of a given ifctype by name" |
| 2338 |
objs = self._fileobject.by_type(ifctype) |
| 2339 |
for obj in objs: |
| 2340 |
if hasattr(obj, "get_argument_count"): |
| 2341 |
l = obj.get_argument_count() |
| 2342 |
else: |
| 2343 |
l = len(obj) |
| 2344 |
for i in range(l): |
| 2345 |
if obj.get_argument_name(i) == "Name": |
| 2346 |
if obj.get_argument(i) == name: |
| 2347 |
return obj |
| 2348 |
return None |
| 2349 |
|
| 2350 |
def write(self, fp=None): |
| 2351 |
"writes the document to its file" |
| 2352 |
if fp: |
| 2353 |
path = fp |
| 2354 |
else: |
| 2355 |
path = self.FilePath |
| 2356 |
if path: |
| 2357 |
try: |
| 2358 |
self._fileobject.write(path) |
| 2359 |
if APPLYFIX: |
| 2360 |
print("IfcWriter: Applying fix...") |
| 2361 |
self._fix(path) |
| 2362 |
except Exception: |
| 2363 |
print("IfcWriter: Error writing to " + path) |
| 2364 |
else: |
| 2365 |
print("IfcWriter: Successfully written to " + path) |
| 2366 |
else: |
| 2367 |
print("IfcWriter: Error: File path is not defined, unable to save") |
| 2368 |
|
| 2369 |
def _fix(self, path): |
| 2370 |
"hack to fix early bugs in ifcopenshell" |
| 2371 |
import os |
| 2372 |
|
| 2373 |
if os.path.exists(path): |
| 2374 |
f = pyopen(path, "rb") |
| 2375 |
lines = [] |
| 2376 |
for l in f.readlines(): |
| 2377 |
if "(=IFC" in l: |
| 2378 |
|
| 2379 |
l = l.replace("(=IFC", "(IFC") |
| 2380 |
elif "IFCSIUNIT" in l: |
| 2381 |
|
| 2382 |
l = l.replace("IFCSIUNIT(#12,", "IFCSIUNIT(*,") |
| 2383 |
lines.append(l) |
| 2384 |
f.close() |
| 2385 |
f = pyopen(path, "wb") |
| 2386 |
for l in lines: |
| 2387 |
f.write(l) |
| 2388 |
f.close() |
| 2389 |
|
| 2390 |
def union(self, solids): |
| 2391 |
"""union(solids): creates a boolean union between all the solids of the list""" |
| 2392 |
if len(solids) == 1: |
| 2393 |
return solids[0] |
| 2394 |
else: |
| 2395 |
s1 = solids.pop(0) |
| 2396 |
s2 = solids.pop(0) |
| 2397 |
base = create(self._fileobject, "IfcBooleanResult", ["UNION", s1, s2]) |
| 2398 |
for s in solids: |
| 2399 |
base = create(self._fileobject, "IfcBooleanResult", ["UNION", base, s]) |
| 2400 |
return base |
| 2401 |
|
| 2402 |
def addPlacement( |
| 2403 |
self, |
| 2404 |
reference=None, |
| 2405 |
origin=(0, 0, 0), |
| 2406 |
xaxis=(1, 0, 0), |
| 2407 |
zaxis=(0, 0, 1), |
| 2408 |
local=True, |
| 2409 |
flat=False, |
| 2410 |
): |
| 2411 |
"""addPlacement([reference,origin,xaxis,zaxis,local]): adds a placement. origin, |
| 2412 |
xaxis and zaxis can be either tuples or 3d vectors. If local is False, a global |
| 2413 |
placement is returned, otherwise a local one.""" |
| 2414 |
if flat: |
| 2415 |
xvc = create(self._fileobject, "IfcDirection", getTuple(xaxis)[:2]) |
| 2416 |
ovc = create(self._fileobject, "IfcCartesianPoint", getTuple(origin)[:2]) |
| 2417 |
gpl = create(self._fileobject, "IfcAxis2Placement2D", [ovc, xvc]) |
| 2418 |
else: |
| 2419 |
xvc = create(self._fileobject, "IfcDirection", getTuple(xaxis)) |
| 2420 |
zvc = create(self._fileobject, "IfcDirection", getTuple(zaxis)) |
| 2421 |
ovc = create(self._fileobject, "IfcCartesianPoint", getTuple(origin)) |
| 2422 |
gpl = create(self._fileobject, "IfcAxis2Placement3D", [ovc, zvc, xvc]) |
| 2423 |
if local: |
| 2424 |
lpl = create(self._fileobject, "IfcLocalPlacement", [reference, gpl]) |
| 2425 |
return lpl |
| 2426 |
else: |
| 2427 |
return gpl |
| 2428 |
|
| 2429 |
def addSite( |
| 2430 |
self, |
| 2431 |
placement=None, |
| 2432 |
name="Site", |
| 2433 |
description=None, |
| 2434 |
latitude=None, |
| 2435 |
longitude=None, |
| 2436 |
elevation=None, |
| 2437 |
landtitlenumber=None, |
| 2438 |
address=None, |
| 2439 |
): |
| 2440 |
"""makeSite(ifcdoc,project,owner,[placement,name,description]): creates a site |
| 2441 |
in the given ifc document""" |
| 2442 |
if self.Site: |
| 2443 |
return |
| 2444 |
if not placement: |
| 2445 |
placement = self.addPlacement() |
| 2446 |
self.Site = create( |
| 2447 |
self._fileobject, |
| 2448 |
"IfcSite", |
| 2449 |
[ |
| 2450 |
uid(), |
| 2451 |
self._owner, |
| 2452 |
str(name), |
| 2453 |
description, |
| 2454 |
None, |
| 2455 |
placement, |
| 2456 |
None, |
| 2457 |
None, |
| 2458 |
"ELEMENT", |
| 2459 |
latitude, |
| 2460 |
longitude, |
| 2461 |
elevation, |
| 2462 |
landtitlenumber, |
| 2463 |
address, |
| 2464 |
], |
| 2465 |
) |
| 2466 |
self._relate(self.Project, self.Site) |
| 2467 |
|
| 2468 |
def addBuilding(self, placement=None, name="Default building", description=None): |
| 2469 |
"""addBuilding([placement,name,description]): adds a building""" |
| 2470 |
if not placement: |
| 2471 |
placement = self.addPlacement() |
| 2472 |
if not self.Site: |
| 2473 |
self.addSite() |
| 2474 |
bdg = create( |
| 2475 |
self._fileobject, |
| 2476 |
"IfcBuilding", |
| 2477 |
[ |
| 2478 |
uid(), |
| 2479 |
self._owner, |
| 2480 |
str(name), |
| 2481 |
description, |
| 2482 |
None, |
| 2483 |
placement, |
| 2484 |
None, |
| 2485 |
None, |
| 2486 |
"ELEMENT", |
| 2487 |
None, |
| 2488 |
None, |
| 2489 |
None, |
| 2490 |
], |
| 2491 |
) |
| 2492 |
self._relate(self.Site, bdg) |
| 2493 |
self.Buildings.append(bdg) |
| 2494 |
return bdg |
| 2495 |
|
| 2496 |
def addStorey(self, building=None, placement=None, name="Default storey", description=None): |
| 2497 |
"""addStorey([building,placement,name,description]): adds a storey""" |
| 2498 |
if not placement: |
| 2499 |
placement = self.addPlacement() |
| 2500 |
sto = create( |
| 2501 |
self._fileobject, |
| 2502 |
"IfcBuildingStorey", |
| 2503 |
[ |
| 2504 |
uid(), |
| 2505 |
self._owner, |
| 2506 |
str(name), |
| 2507 |
description, |
| 2508 |
None, |
| 2509 |
placement, |
| 2510 |
None, |
| 2511 |
None, |
| 2512 |
"ELEMENT", |
| 2513 |
None, |
| 2514 |
], |
| 2515 |
) |
| 2516 |
if not building: |
| 2517 |
if self.Buildings: |
| 2518 |
building = self.Buildings[0] |
| 2519 |
else: |
| 2520 |
building = self.addBuilding() |
| 2521 |
self._relate(building, sto) |
| 2522 |
self.Storeys.append(sto) |
| 2523 |
return sto |
| 2524 |
|
| 2525 |
def addGroup(self, entities, name="Default group", description=None): |
| 2526 |
"""addGroup(entities,[name,description]): adds a group with the given entities""" |
| 2527 |
if not isinstance(entities, list): |
| 2528 |
entities = [entities] |
| 2529 |
gro = create( |
| 2530 |
self._fileobject, "IfcGroup", [uid(), self._owner, str(name), description, None] |
| 2531 |
) |
| 2532 |
rel = create( |
| 2533 |
self._fileobject, |
| 2534 |
"IfcRelAssignsToGroup", |
| 2535 |
[uid(), self._owner, str(name) + "-relation", None, entities, "PRODUCT", gro], |
| 2536 |
) |
| 2537 |
return gro |
| 2538 |
|
| 2539 |
def _relate(self, container, entities): |
| 2540 |
"""relate(container,entities): relates the given entities to the given |
| 2541 |
container""" |
| 2542 |
if not isinstance(entities, list): |
| 2543 |
entities = [entities] |
| 2544 |
if container.is_a("IfcBuildingStorey"): |
| 2545 |
sid = container.get_argument(0) |
| 2546 |
if sid in self._storeyRelations: |
| 2547 |
prods = self._storeyRelations[sid].get_argument(4) |
| 2548 |
self._storeyRelations[sid].set_argument(4, prods + entities) |
| 2549 |
else: |
| 2550 |
rel = create( |
| 2551 |
self._fileobject, |
| 2552 |
"IfcRelContainedInSpatialStructure", |
| 2553 |
[uid(), self._owner, "StoreyLink", "", entities, container], |
| 2554 |
) |
| 2555 |
self._storeyRelations[sid] = rel |
| 2556 |
else: |
| 2557 |
if entities[0].is_a("IfcOpeningElement"): |
| 2558 |
create( |
| 2559 |
self._fileobject, |
| 2560 |
"IfcRelVoidsElement", |
| 2561 |
[uid(), self._owner, "Opening", "", container, entities[0]], |
| 2562 |
) |
| 2563 |
else: |
| 2564 |
create( |
| 2565 |
self._fileobject, |
| 2566 |
"IfcRelAggregates", |
| 2567 |
[uid(), self._owner, "Relationship", "", container, entities], |
| 2568 |
) |
| 2569 |
|
| 2570 |
def addProduct( |
| 2571 |
self, |
| 2572 |
elttype, |
| 2573 |
shapes, |
| 2574 |
storey=None, |
| 2575 |
placement=None, |
| 2576 |
name="Unnamed element", |
| 2577 |
description=None, |
| 2578 |
extra=None, |
| 2579 |
): |
| 2580 |
"""addProduct(elttype,representations,[storey,placement,name,description,extra]): creates an element of the given type |
| 2581 |
(IfcWall, IfcBeam, etc...) with the given attributes, plus the given extra attributes.""" |
| 2582 |
elttype = str(elttype) |
| 2583 |
if not extra: |
| 2584 |
extra = [] |
| 2585 |
if not description: |
| 2586 |
description = None |
| 2587 |
if not placement: |
| 2588 |
placement = self.addPlacement() |
| 2589 |
representations = self.addRepresentations(shapes) |
| 2590 |
prd = create(self._fileobject, "IfcProductDefinitionShape", [None, None, representations]) |
| 2591 |
try: |
| 2592 |
elt = create( |
| 2593 |
self._fileobject, |
| 2594 |
elttype, |
| 2595 |
[uid(), self._owner, name, description, None, placement, prd, None] + extra, |
| 2596 |
) |
| 2597 |
except Exception: |
| 2598 |
print( |
| 2599 |
"unable to create an ", |
| 2600 |
elttype, |
| 2601 |
" with attributes: ", |
| 2602 |
[uid(), self._owner, str(name), description, None, placement, prd, None] + extra, |
| 2603 |
) |
| 2604 |
try: |
| 2605 |
if hasattr(ifcw, "Entity"): |
| 2606 |
o = ifcw.Entity(elttype) |
| 2607 |
else: |
| 2608 |
o = ifcw.entity_instance(elttype) |
| 2609 |
print("supported attributes are: ") |
| 2610 |
print(getPropertyNames(o)) |
| 2611 |
except Exception: |
| 2612 |
print("unable to create an element of type '" + elttype + "'") |
| 2613 |
print("WARNING: skipping object '" + name + "' of type " + elttype) |
| 2614 |
return None |
| 2615 |
self.BuildingProducts.append(elt) |
| 2616 |
if not storey: |
| 2617 |
if self.Storeys: |
| 2618 |
storey = self.Storeys[0] |
| 2619 |
else: |
| 2620 |
storey = self.addStorey() |
| 2621 |
self._relate(storey, elt) |
| 2622 |
return elt |
| 2623 |
|
| 2624 |
def addRepresentations(self, shapes): |
| 2625 |
"""addRepresentations(shapes,[solidType]): creates a representation from the given shape""" |
| 2626 |
solidType = "Brep" |
| 2627 |
if not isinstance(shapes, list): |
| 2628 |
if shapes.is_a("IfcExtrudedAreaSolid"): |
| 2629 |
solidType = "SweptSolid" |
| 2630 |
shapes = [shapes] |
| 2631 |
reps = [ |
| 2632 |
create( |
| 2633 |
self._fileobject, |
| 2634 |
"IfcShapeRepresentation", |
| 2635 |
[self._repcontext, "Body", solidType, [shape for shape in shapes]], |
| 2636 |
) |
| 2637 |
] |
| 2638 |
return reps |
| 2639 |
|
| 2640 |
def addColor(self, rgb, rep): |
| 2641 |
"""addColor(rgb,rep): adds a RGB color definition tuple (float,float,float) to a given representation""" |
| 2642 |
col = create(self._fileobject, "IfcColourRgb", [None] + list(rgb)) |
| 2643 |
ssr = create( |
| 2644 |
self._fileobject, |
| 2645 |
"IfcSurfaceStyleRendering", |
| 2646 |
[col, None, None, None, None, None, None, None, "FLAT"], |
| 2647 |
) |
| 2648 |
iss = create(self._fileobject, "IfcSurfaceStyle", [None, "BOTH", [ssr]]) |
| 2649 |
psa = create(self._fileobject, "IfcPresentationStyleAssignment", [[iss]]) |
| 2650 |
isi = create(self._fileobject, "IfcStyledItem", [rep, [psa], None]) |
| 2651 |
return isi |
| 2652 |
|
| 2653 |
def addProfile(self, ifctype, data, curvetype="AREA"): |
| 2654 |
"""addProfile(ifctype,data): creates a 2D profile of the given type, with the given |
| 2655 |
data as arguments, which must be formatted correctly according to the type.""" |
| 2656 |
|
| 2657 |
|
| 2658 |
|
| 2659 |
|
| 2660 |
|
| 2661 |
|
| 2662 |
|
| 2663 |
|
| 2664 |
|
| 2665 |
if ifctype == "IfcPolyline": |
| 2666 |
pts = [create(self._fileobject, "IfcCartesianPoint", getTuple(p)[:2]) for p in data] |
| 2667 |
pol = create(self._fileobject, "IfcPolyline", [pts]) |
| 2668 |
profile = create( |
| 2669 |
self._fileobject, "IfcArbitraryClosedProfileDef", [curvetype, None, pol] |
| 2670 |
) |
| 2671 |
elif ifctype == "IfcCompositeCurve": |
| 2672 |
curves = [] |
| 2673 |
for curve in data: |
| 2674 |
cur = None |
| 2675 |
if curve[0] == "line": |
| 2676 |
pts = [ |
| 2677 |
create(self._fileobject, "IfcCartesianPoint", getTuple(p)[:2]) |
| 2678 |
for p in curve[1] |
| 2679 |
] |
| 2680 |
cur = create(self._fileobject, "IfcPolyline", [pts]) |
| 2681 |
elif curve[0] == "arc": |
| 2682 |
pla = self.addPlacement(origin=curve[1], local=False, flat=True) |
| 2683 |
cir = create(self._fileobject, "IfcCircle", [pla, curve[2]]) |
| 2684 |
if curve[5] == "CARTESIAN": |
| 2685 |
|
| 2686 |
trim1 = create(None, "IfcCartesianPoint", getTuple(curve[3][0])[:2]) |
| 2687 |
trim2 = create(None, "IfcCartesianPoint", getTuple(curve[3][1])[:2]) |
| 2688 |
else: |
| 2689 |
trim1 = create(None, "IfcParameterValue", [curve[3][0]]) |
| 2690 |
trim2 = create(None, "IfcParameterValue", [curve[3][1]]) |
| 2691 |
cur = create( |
| 2692 |
self._fileobject, |
| 2693 |
"IfcTrimmedCurve", |
| 2694 |
[cir, [trim1], [trim2], curve[4], curve[5]], |
| 2695 |
) |
| 2696 |
if cur: |
| 2697 |
seg = create( |
| 2698 |
self._fileobject, "IfcCompositeCurveSegment", ["CONTINUOUS", True, cur] |
| 2699 |
) |
| 2700 |
curves.append(seg) |
| 2701 |
ccu = create(self._fileobject, "IfcCompositeCurve", [curves, False]) |
| 2702 |
profile = create( |
| 2703 |
self._fileobject, "IfcArbitraryClosedProfileDef", [curvetype, None, ccu] |
| 2704 |
) |
| 2705 |
else: |
| 2706 |
if not isinstance(data, list): |
| 2707 |
data = [data] |
| 2708 |
p = self.addPlacement(local=False, flat=True) |
| 2709 |
profile = create(self._fileobject, ifctype, [curvetype, None, p] + data) |
| 2710 |
return profile |
| 2711 |
|
| 2712 |
def addExtrusion(self, profile, extrusion, placement=None): |
| 2713 |
"""addExtrusion(profile,extrusion,[placement]): makes an |
| 2714 |
extrusion of the given polyline with the given extrusion vector""" |
| 2715 |
if not placement: |
| 2716 |
placement = self.addPlacement(local=False) |
| 2717 |
value, norm = getValueAndDirection(extrusion) |
| 2718 |
edir = create(self._fileobject, "IfcDirection", [norm]) |
| 2719 |
solid = create(self._fileobject, "IfcExtrudedAreaSolid", [profile, placement, edir, value]) |
| 2720 |
return solid |
| 2721 |
|
| 2722 |
def addExtrudedPolyline(self, points, extrusion, placement=None, color=None): |
| 2723 |
"""addExtrudedPolyline(points,extrusion,[placement,color]): makes an extruded polyline |
| 2724 |
from the given points and the given extrusion vector""" |
| 2725 |
pol = self.addProfile("IfcPolyline", points) |
| 2726 |
if not placement: |
| 2727 |
placement = self.addPlacement(local=False) |
| 2728 |
exp = self.addExtrusion(pol, extrusion, placement) |
| 2729 |
if color: |
| 2730 |
self.addColor(color, exp) |
| 2731 |
return exp |
| 2732 |
|
| 2733 |
def addExtrudedCircle(self, data, extrusion, placement=None, color=None): |
| 2734 |
"""addExtrudedCircle(data,extrusion,[placement,color]): makes an extruded circle |
| 2735 |
from the given data (center,radius) and the given extrusion vector""" |
| 2736 |
cir = self.addProfile("IfcCircleProfileDef", data[1]) |
| 2737 |
if not placement: |
| 2738 |
placement = self.addPlacement(origin=data[0], local=False) |
| 2739 |
exp = self.addExtrusion(cir, extrusion, placement) |
| 2740 |
if color: |
| 2741 |
self.addColor(color, exp) |
| 2742 |
return exp |
| 2743 |
|
| 2744 |
def addExtrudedEllipse(self, data, extrusion, placement=None, color=None): |
| 2745 |
"""addExtrudedEllipse(data,extrusion,[placement,color]): makes an extruded ellipse |
| 2746 |
from the given data (center,radiusx,radiusy) and the given extrusion vector""" |
| 2747 |
cir = self.addProfile("IfcEllipseProfileDef", [data[1], data[2]]) |
| 2748 |
if not placement: |
| 2749 |
placement = self.addPlacement(origin=data[0], local=False) |
| 2750 |
exp = self.addExtrusion(cir, extrusion, placement) |
| 2751 |
if color: |
| 2752 |
self.addColor(color, exp) |
| 2753 |
return exp |
| 2754 |
|
| 2755 |
def addExtrudedCompositeCurve(self, curves, extrusion, placement=None, color=None): |
| 2756 |
"""addExtrudedCompositeCurve(curves,extrusion,[placement,color]): makes an extruded polyline |
| 2757 |
from the given curves and the given extrusion vector""" |
| 2758 |
if not placement: |
| 2759 |
placement = self.addPlacement(local=False) |
| 2760 |
ccu = self.addProfile("IfcCompositeCurve", curves) |
| 2761 |
exp = self.addExtrusion(ccu, extrusion, placement) |
| 2762 |
if color: |
| 2763 |
self.addColor(color, exp) |
| 2764 |
return exp |
| 2765 |
|
| 2766 |
def addFace(self, face): |
| 2767 |
"""addFace(face): creates a face from the given face data (a list of lists of points). |
| 2768 |
The first is the outer wire, the next are optional inner wires. They must be reversed in order |
| 2769 |
""" |
| 2770 |
ifb = [] |
| 2771 |
idx = 0 |
| 2772 |
for f in face: |
| 2773 |
pts = [] |
| 2774 |
for p in f: |
| 2775 |
|
| 2776 |
if p in self.fpoints: |
| 2777 |
|
| 2778 |
|
| 2779 |
pts.append(self.frefs[self.fpoints.index(p)]) |
| 2780 |
else: |
| 2781 |
pt = create(self._fileobject, "IfcCartesianPoint", getTuple(p)) |
| 2782 |
pts.append(pt) |
| 2783 |
self.fpoints.append(p) |
| 2784 |
self.frefs.append(pt) |
| 2785 |
|
| 2786 |
loop = create(self._fileobject, "IfcPolyLoop", [pts]) |
| 2787 |
if idx == 0: |
| 2788 |
fb = create(self._fileobject, "IfcFaceOuterBound", [loop, True]) |
| 2789 |
else: |
| 2790 |
fb = create(self._fileobject, "IfcFaceBound", [loop, True]) |
| 2791 |
ifb.append(fb) |
| 2792 |
idx += 1 |
| 2793 |
iface = create(self._fileobject, "IfcFace", [ifb]) |
| 2794 |
return iface |
| 2795 |
|
| 2796 |
def addFacetedBrep(self, faces, color=None): |
| 2797 |
"""addFacetedBrep(self,faces,[color]): creates a faceted brep object from the given list |
| 2798 |
of faces (each face is a list of lists of points, inner wires are reversed)""" |
| 2799 |
self.fpoints = [] |
| 2800 |
self.frefs = [] |
| 2801 |
|
| 2802 |
|
| 2803 |
ifaces = [self.addFace(face) for face in faces] |
| 2804 |
sh = create(self._fileobject, "IfcClosedShell", [ifaces]) |
| 2805 |
brp = create(self._fileobject, "IfcFacetedBrep", [sh]) |
| 2806 |
if color: |
| 2807 |
self.addColor(color, brp) |
| 2808 |
return brp |