/
__init__.py
728 lines (660 loc) · 24.6 KB
/
__init__.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
""" Domain-specific extensions to IfcOpenShell
A collection of code for commonly used IFC related tasks
"""
import ifcopenshell.api
import ifcopenshell.util.system
from molior.geometry import (
matrix_align,
add_2d,
subtract_2d,
x_product_3d,
subtract_3d,
normalise_3d,
)
run = ifcopenshell.api.run
def init(name="Homemaker Project", file=None):
"""Creates and sets up an ifc 'file' object"""
if file == None:
file = run("project.create_file")
# TODO skip each of these if already existing
run("owner.add_person", file)
run("owner.add_organisation", file)
run(
"root.create_entity",
file,
ifc_class="IfcProject",
name=name,
)
unit_assignment = run("unit.assign_unit", file)
unit_assignment.Units = [
run("unit.add_si_unit", file, unit_type="LENGTHUNIT"),
run("unit.add_si_unit", file, unit_type="AREAUNIT"),
run("unit.add_si_unit", file, unit_type="VOLUMEUNIT"),
run("unit.add_si_unit", file, unit_type="PLANEANGLEUNIT"),
]
create_default_contexts(file)
return file
def create_default_contexts(self):
get_context_by_name(
self,
context_identifier="Body",
parent_context_identifier="Model",
target_view="MODEL_VIEW",
)
get_context_by_name(
self,
context_identifier="Box",
parent_context_identifier="Model",
target_view="MODEL_VIEW",
)
get_context_by_name(
self,
context_identifier="Clearance",
parent_context_identifier="Model",
target_view="MODEL_VIEW",
)
get_context_by_name(
self,
context_identifier="Surface",
parent_context_identifier="Model",
target_view="SKETCH_VIEW",
)
get_context_by_name(
self,
context_identifier="Reference",
parent_context_identifier="Model",
target_view="GRAPH_VIEW",
)
get_context_by_name(
self,
context_identifier="Annotation",
parent_context_identifier="Plan",
target_view="PLAN_VIEW",
)
get_context_by_name(
self,
context_identifier="Annotation",
parent_context_identifier="Plan",
target_view="SECTION_VIEW",
)
get_context_by_name(
self,
context_identifier="Annotation",
parent_context_identifier="Plan",
target_view="ELEVATION_VIEW",
)
get_context_by_name(
self,
context_identifier="Axis",
parent_context_identifier="Model",
target_view="GRAPH_VIEW",
)
def create_storeys(self, parent, elevations):
"""Add Storey Spatial Elements to a Building, given a dictionary of elevations/name"""
if elevations == {}:
elevations[0.0] = 0
for elevation in sorted(elevations):
for storey in self.by_type("IfcBuildingStorey"):
if (
storey.Name == str(elevations[elevation])
and storey.Decomposes
and storey.Decomposes[0].RelatingObject == parent
):
continue
mystorey = run(
"root.create_entity",
self,
ifc_class="IfcBuildingStorey",
name=str(elevations[elevation]),
)
mystorey.Elevation = elevation
mystorey.Description = "Storey " + mystorey.Name
mystorey.LongName = mystorey.Description
mystorey.CompositionType = "ELEMENT"
run("aggregate.assign_object", self, product=mystorey, relating_object=parent)
run(
"geometry.edit_object_placement",
self,
product=mystorey,
matrix=matrix_align([0.0, 0.0, elevation], [1.0, 0.0, 0.0]),
)
def get_context_by_name(
self,
parent_context_identifier=None,
context_identifier=None,
target_view=None,
):
"""Retrieve or create a Representation Context"""
mycontext = get_context(
self,
parent_context_identifier,
subcontext=context_identifier,
target_view=target_view,
)
if mycontext:
return mycontext
if context_identifier in ["Model", "Plan", "NotDefined"]:
mycontext = get_context(self, context_identifier)
if mycontext:
return mycontext
return run("context.add_context", self, context_type=context_identifier)
parent_context = get_context_by_name(
self, context_identifier=parent_context_identifier
)
return run(
"context.add_context",
self,
context_identifier=context_identifier,
context_type=parent_context.ContextType,
parent=parent_context,
target_view=target_view,
)
# pasted from ifcopenshell.util.representation due to blender dependency
def get_context(ifc_file, context, subcontext=None, target_view=None):
if subcontext or target_view:
elements = ifc_file.by_type("IfcGeometricRepresentationSubContext")
else:
elements = ifc_file.by_type(
"IfcGeometricRepresentationContext", include_subtypes=False
)
for element in elements:
if context and element.ContextType != context:
continue
if subcontext and getattr(element, "ContextIdentifier") != subcontext:
continue
if target_view and getattr(element, "TargetView") != target_view:
continue
return element
def get_site_by_name(self, parent, name):
"""Add a Site to a Project, or retrieve if already there"""
for site in self.by_type("IfcSite"):
if (
site.Name == name
and site.Decomposes
and site.Decomposes[0].RelatingObject == parent
):
return site
site = run("root.create_entity", self, ifc_class="IfcSite", name=name)
# TODO allow setting location
site.RefLatitude = [53, 23, 0]
site.RefLongitude = [1, 28, 0]
site.RefElevation = 75.0
run("aggregate.assign_object", self, product=site, relating_object=parent)
return site
def get_building_by_name(self, parent, name):
"""Add a Building to a Site, or retrieve if already there"""
for building in self.by_type("IfcBuilding"):
if (
building.Name == name
and building.Decomposes
and building.Decomposes[0].RelatingObject == parent
):
return building
building = run("root.create_entity", self, ifc_class="IfcBuilding", name=name)
run("aggregate.assign_object", self, product=building, relating_object=parent)
return building
def get_structural_analysis_model_by_name(self, spatial_element, name):
"""Add a structural model to a building, or retrieve if already there"""
for model in self.by_type("IfcStructuralAnalysisModel"):
if (
model.Name == "Structure/" + name
and model.ServicesBuildings
and spatial_element in model.ServicesBuildings[0].RelatedBuildings
):
return model
model = run("structural.add_structural_analysis_model", self)
model.Name = "Structure/" + name
rel = run(
"root.create_entity",
self,
ifc_class="IfcRelServicesBuildings",
name=model.Name,
)
rel.RelatingSystem = model
rel.RelatedBuildings = [spatial_element]
return model
def get_library_by_name(self, library_name):
"""Retrieve a Project Library by name, creating it if necessary"""
for library in self.by_type("IfcProjectLibrary"):
if library.Name == library_name:
return library
library = run(
"root.create_entity", self, ifc_class="IfcProjectLibrary", name=library_name
)
run(
"project.assign_declaration",
self,
definition=library,
relating_context=self.by_type("IfcProject")[0],
)
return library
def get_material_by_name(self, style_object, stylename="default", name="Error"):
"""Retrieve an IfcMaterial by name, creating it if necessary"""
materials = {}
for material in self.by_type("IfcMaterial"):
materials[material.Name] = material
if name in materials:
mymaterial = materials[name]
else:
(found_stylename, library_file, element) = style_object.get_from_library(
stylename, "IfcMaterial", name
)
if element:
# add to current project from library file
mymaterial = run(
"project.append_asset", self, library=library_file, element=element
)
else:
# we need to create a new material
mymaterial = run("material.add_material", self, name=name)
return mymaterial
def get_parent_building(entity):
"""Retrieve whatever Building contains this entity, or None"""
if entity.is_a("IfcElement"):
parents = entity.ContainedInStructure
decomposes = entity.Decomposes
if not parents:
if not decomposes:
return None
parent = decomposes[0].RelatingObject
else:
parent = parents[0].RelatingStructure
elif entity.is_a("IfcSpatialElement"):
decomposes = entity.Decomposes
if not decomposes:
return None
parent = decomposes[0].RelatingObject
elif entity.is_a("IfcStructuralItem"):
assignments = entity.HasAssignments
if not assignments:
return None
parent = assignments[0].RelatingGroup
elif entity.is_a("IfcSystem"):
services = entity.ServicesBuildings
if not services:
return None
parent = services[0].RelatedBuildings[0]
else:
return None
if parent.is_a("IfcBuilding"):
return parent
return get_parent_building(parent)
def get_thickness(self, product):
"""Gets total thickness for extruded products and types"""
thickness = 0.0
for association in product.HasAssociations:
if association.is_a("IfcRelAssociatesMaterial"):
relating_material = association.RelatingMaterial
if relating_material.is_a("IfcMaterialLayerSet"):
for material_layer in relating_material.MaterialLayers:
thickness += material_layer.LayerThickness
return thickness
def create_closed_profile_from_points(self, points):
"""Creates a closed 2D profile from list of 2D points"""
# a closed polyline has first and last points coincident
if not points[-1] == points[0]:
points.append(points[0])
return self.createIfcArbitraryClosedProfileDef(
"AREA",
None,
self.createIfcPolyline(
[self.createIfcCartesianPoint(point) for point in points]
),
)
def create_extruded_area_solid(self, points, height, direction=[0.0, 0.0, 1.0]):
"""A simple vertically extruded profile"""
return self.createIfcExtrudedAreaSolid(
create_closed_profile_from_points(self, points),
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None
),
self.createIfcDirection(direction),
height,
)
def create_extruded_area_solid2(self, material_profile, start, direction, length):
return self.createIfcExtrudedAreaSolid(
material_profile.Profile,
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint(start),
self.createIfcDirection(subtract_3d([0.0, 0.0, 0.0], direction)),
self.createIfcDirection([direction[1], -direction[0], direction[2]]),
),
self.createIfcDirection([0.0, 0.0, -1.0]),
length,
)
def create_curve_bounded_plane(self, polygon, matrix):
"""Create a bounded shape in the Z=0 plane"""
return self.createIfcCurveBoundedPlane(
self.createIfcPlane(
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint(matrix[:, 3][0:3].tolist()),
self.createIfcDirection(matrix[:, 2][0:3].tolist()),
self.createIfcDirection(matrix[:, 0][0:3].tolist()),
)
),
self.createIfcPolyline(
[self.createIfcCartesianPoint(point) for point in polygon]
),
[],
)
def create_face_surface(self, polygon, normal):
"""Create a single-face shape"""
surface = self.createIfcPlane(
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint(polygon[0]),
self.createIfcDirection(normal),
self.createIfcDirection(normalise_3d(subtract_3d(polygon[1], polygon[0]))),
)
)
face_bound = self.createIfcFaceBound(
self.createIfcEdgeLoop(
[
self.createIfcOrientedEdge(None, None, edge, True)
for edge in [
self.createIfcEdge(
self.createIfcVertexPoint(
self.createIfcCartesianPoint(polygon[i - 1])
),
self.createIfcVertexPoint(
self.createIfcCartesianPoint(polygon[i])
),
)
for i in range(len(polygon))
]
]
),
True,
)
return self.createIfcFaceSurface([face_bound], surface, True)
def create_tessellation_from_mesh(self, vertices, faces):
"""Create a Tessellation from vertex coordinates and faces"""
pointlist = self.createIfcCartesianPointList3D(vertices)
indexedfaces = [
self.createIfcIndexedPolygonalFace([index + 1 for index in face])
for face in faces
]
return self.createIfcPolygonalFaceSet(pointlist, None, indexedfaces, None)
def clip_solid(self, solid, start, end):
"""Clip a wall using a half-space solid"""
vector = subtract_3d(end, start)
perp_plan = normalise_3d([0 - vector[1], vector[0], 0.0])
xprod = x_product_3d(vector, perp_plan)
polygon = [
add_2d(start[0:2], perp_plan[0:2]),
add_2d(end[0:2], perp_plan[0:2]),
subtract_2d(end[0:2], perp_plan[0:2]),
subtract_2d(start[0:2], perp_plan[0:2]),
add_2d(start[0:2], perp_plan[0:2]),
]
return self.createIfcBooleanClippingResult(
"DIFFERENCE",
solid,
self.createIfcPolygonalBoundedHalfSpace(
self.createIfcPlane(
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint(start),
self.createIfcDirection(xprod),
None,
)
),
False,
self.createIfcAxis2Placement3D(
self.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None
),
self.createIfcPolyline(
[self.createIfcCartesianPoint(point) for point in polygon]
),
),
)
def add_pset(self, product, name, properties):
"""Helper method to add an Ifc Pset"""
pset = run("pset.add_pset", self, product=product, name=name)
run(
"pset.edit_pset",
self,
pset=pset,
properties=properties,
)
def add_face_topology_epsets(self, entity, face, back_cell, front_cell):
if face:
face_index = face.Get("index")
if not face_index == None:
add_pset(self, entity, "EPset_Topology", {"FaceIndex": str(face_index)})
face_stylename = face.Get("stylename")
if not face_stylename == None:
add_pset(self, entity, "EPset_Topology", {"StyleName": str(face_stylename)})
if front_cell:
front_cell_index = front_cell.Get("index")
if not front_cell_index == None:
add_pset(
self,
entity,
"EPset_Topology",
{"FrontCellIndex": str(front_cell_index)},
)
if back_cell:
back_cell_index = back_cell.Get("index")
if not back_cell_index == None:
add_pset(
self,
entity,
"EPset_Topology",
{"BackCellIndex": str(back_cell_index)},
)
def add_topologic_epsets(self, entity, topology):
add_pset(self, entity, "EPset_Topologic_Dictionary", topology.DumpDictionary())
def add_cell_topology_epsets(self, entity, cell):
if cell:
cell_index = cell.Get("index")
if cell_index != None:
add_pset(self, entity, "EPset_Topology", {"CellIndex": cell_index})
cell_usage = cell.Get("usage")
if cell_usage != None:
add_pset(self, entity, "EPset_Topology", {"Usage": cell_usage})
def assign_storey_byindex(self, entity, building, index):
"""Assign object to a storey by index"""
storeys = {}
for storey in self.by_type("IfcBuildingStorey"):
if get_parent_building(storey) == building:
storeys[storey.Name] = storey
if entity.is_a("IfcSpatialElement"):
run(
"aggregate.assign_object",
self,
product=entity,
relating_object=storeys[str(index)],
)
else:
run(
"spatial.assign_container",
self,
product=entity,
relating_structure=storeys[str(index)],
)
return storeys[str(index)]
def assign_space_byindex(self, entity, building, index):
"""Assign object to a Space by index"""
spaces = {}
for space in self.by_type("IfcSpace"):
if get_parent_building(space) == building:
pset_topology = ifcopenshell.util.element.get_psets(space).get(
"EPset_Topology"
)
if pset_topology:
spaces[pset_topology["CellIndex"]] = space
if not str(index) in spaces:
return
if entity.is_a("IfcSpatialElement"):
run(
"aggregate.assign_object",
self,
product=entity,
relating_object=spaces[str(index)],
)
else:
run(
"spatial.assign_container",
self,
product=entity,
relating_structure=spaces[str(index)],
)
def get_type_object(
self,
style_object,
ifc_type="IfcBuildingElementProxyType",
stylename="default",
name="error",
):
"""Fetch a Type Object locally, or from an external IFC library"""
# let's see if there is an existing Type Product defined in the relevant library
library = get_library_by_name(self, stylename)
for declares in library.Declares:
for definition in declares.RelatedDefinitions:
if definition.is_a(ifc_type) and definition.Name == name:
return definition
# otherwise, load from IFC library file
(found_stylename, library_file, element) = style_object.get_from_library(
stylename, ifc_type, name
)
if element:
# add to current project from library file
definition = run(
"project.append_asset", self, library=library_file, element=element
)
else:
definition = run(
"root.create_entity",
self,
ifc_class=ifc_type,
name=name,
)
# add to internal library
run(
"project.assign_declaration",
self,
definition=definition,
relating_context=get_library_by_name(self, stylename),
)
return definition
def delete_ifc_product(self, product):
"""Recursively delete a product and its children"""
if not product:
return
if getattr(product, "IsDecomposedBy", None):
for child in product.IsDecomposedBy:
for child_object in child.RelatedObjects:
delete_ifc_product(self, child_object)
if getattr(product, "IsGroupedBy", None):
for child in product.IsGroupedBy:
for child_object in child.RelatedObjects:
delete_ifc_product(self, child_object)
if getattr(product, "Nests", None):
for child in product.Nests:
for child_product in child.RelatedObjects:
delete_ifc_product(self, child_product)
if product.is_a("IfcSpatialElement"):
for child in product.ContainsElements:
for child_product in child.RelatedElements:
delete_ifc_product(self, child_product)
if getattr(product, "FillsVoids", None):
run("void.remove_filling", self, element=product)
if product.is_a("IfcOpeningElement"):
if product.HasFillings:
for rel in product.HasFillings:
run("void.remove_filling", self, element=rel.RelatedBuildingElement)
else:
if product.VoidsElements:
run("void.remove_filling", self, element=product)
else:
if getattr(product, "HasOpenings", None):
for rel in product.HasOpenings:
run("void.remove_filling", self, element=rel.RelatedOpeningElement)
for port in ifcopenshell.util.system.get_ports(product):
run("root.remove_product", self, product=port)
run("root.remove_product", self, product=product)
def purge_unused(self):
"""Delete some unused entities"""
todo = True
while todo:
todo = False
for type_object in self.by_type("IfcTypeObject"):
if not type_object.Types or not type_object.Types[0].RelatedObjects:
# need this or it segfaults IfcOpenShell/IfcOpenShell#2697
run("material.unassign_material", self, product=type_object)
delete_ifc_product(self, type_object)
todo = True
for pset in self.by_type("IfcPropertySet"):
if (
not pset.DefinesType
and not pset.IsDefinedBy
and not pset.DefinesOccurrence
):
delete_ifc_product(self, pset)
todo = True
for rep in self.by_type("IfcMaterialDefinitionRepresentation"):
if not rep.RepresentedMaterial:
run("root.remove_product", self, product=rep)
todo = True
for ext in self.by_type("IfcExtendedProperties"):
if not ext.Properties:
run("root.remove_product", self, product=ext)
todo = True
for placement in self.by_type("IfcLocalPlacement"):
if not placement.PlacesObject and not placement.ReferencedByPlacements:
rel = placement.RelativePlacement
self.remove(rel.Location)
self.remove(rel.RefDirection)
if getattr(rel, "Axis", None):
self.remove(rel.Axis)
self.remove(rel)
run("root.remove_product", self, product=placement)
todo = True
for entity in self.by_type("IfcConnectionGeometry"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcBoundaryCondition"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcPresentationItem"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcProfileDef"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcRepresentation"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcGeometricRepresentationItem"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
for entity in self.by_type("IfcMaterialDefinition"):
if not self.get_inverse(entity):
run("root.remove_product", self, product=entity)
todo = True
# these are clearing up invalid results of root.remove_product
for rel in self.by_type("IfcRelConnectsStructuralMember"):
if not rel.RelatingStructuralMember:
run("root.remove_product", self, product=rel)
todo = True
for rel in self.by_type("IfcRelAssignsToProduct"):
if not rel.RelatingProduct:
run("root.remove_product", self, product=rel)
todo = True
for rel in self.by_type("IfcRelServicesBuildings"):
if not rel.RelatingSystem:
run("root.remove_product", self, product=rel)
todo = True
for rel in self.by_type("IfcRelAssignsToGroup"):
if not rel.RelatingGroup:
run("root.remove_product", self, product=rel)
todo = True
for rel in self.by_type("IfcRelDeclares"):
if not rel.RelatedDefinitions:
run("root.remove_product", self, product=rel)
todo = True