-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIfcElementedWallTest_2.py
693 lines (424 loc) · 20.8 KB
/
IfcElementedWallTest_2.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
#---------USEFUL LINKS FOR LEARNING-----------#
#-----SPECIAL NOTE------------
#Ensure you have the latest ifcopenshell or blender bim source code
# use git and Sigma Dimensions method for updating git and blenderbim addon sequentially
#---important-----core knowledge---------for IFC----------:
#https://technical.buildingsmart.org/standards/
# go here first for learning: https://blenderbim.org/docs-python/
# for Geometry creation you need to look at the raw source code as it is planned to be overhauled.
#Here: https://github.com/IfcOpenShell/IfcOpenShell/blob/v0.7.0/src/ifcopenshell-python/ifcopenshell/api/geometry/add_slab_representation.py
# go here for live testing of ifc script with google collab( thanks to Carlos Villagrasa Silanes):
# https://colab.research.google.com/drive/1ieceyxgaG5bY7ODoGxBAMaBlx1yLRRnN?usp=sharing#scrollTo=09YjXEmR6-Ey
#important link for finding out what ifc class to use : https://blenderbim.org/search-ifc-class.html
#base libraries for working with IFC files
import bpy
import ifcopenshell
import ifcopenshell.util
import ifcopenshell.util.element
from ifcopenshell.api import run
import os
#import other libraries from custom paths on computer
import sys
#used for wall matrix creation , location, orientation
import numpy as np
import math
from mathutils import Vector
"""
#used for reloading ifc file dynamically
import blenderbim.tool.ifcgit
import bpy
import logging
from blenderbim.bim import import_ifc
from blenderbim.bim.ifc import IfcStore
import blenderbim.tool as tool
import re
import os
"""
#libraries for shape_builder
# The shape_builder module depends on mathutils
from ifcopenshell.util.shape_builder import V
# Specify the path to your custom directory
custom_scripts_path = "C:\dev\python-ifc-learn\MyBlenderScripts"
# Check if the directory exists
if os.path.exists(custom_scripts_path):
# Add the custom directory to the sys.path
sys.path.append(custom_scripts_path)
# Now you can import modules or packages from the custom directory
from CustomScripts import luke_printer
from CustomScripts import myIfcSandbox
from CustomScripts import myTools
# Use the imported module or package
printer = luke_printer.LukeIsTheBestPrinter()
printer.print_luke_is_the_best()
sb = myIfcSandbox.sandbox()
sb.test_load()
ct = myTools.custom_tool()
ct.test_tool()
else:
print(f"Error: The directory {custom_scripts_path} does not exist.")
# this next part forces a reload in case you edit the source after you first start the blender session
import importlib
importlib.reload(luke_printer)
importlib.reload(myIfcSandbox)
importlib.reload(myTools)
# this is optional and allows you to call the functions without specifying the package name
#from luke_printer import *
#check if can make additional custom definitions from imported custom classs working for more defintions
#ct.makecube("luke's cube")
#check can use imported ifc_sandbox class instead of long script below - to reduce complexity of script for others.
sb.load_project(path_ifc = 'c:\dev\studTest.ifc')
#step 2 ------------------ Create new ifc file
model = ifcopenshell.file()
#comment below out as was stopping the purging of types
#IfcStore.file = model
# All projects must have one IFC Project element
project = run("root.create_entity", model, ifc_class="IfcProject", name="My Project")
# Geometry is optional in IFC, but because we want to use geometry in this example, let's define units
# Assigning without arguments defaults to metric units
run("unit.assign_unit", model)
# Let's create a modeling geometry context, so we can store 3D geometry (note: IFC supports 2D too!)
context = run("context.add_context", model, context_type="Model")
# In particular, in this example we want to store the 3D "body" geometry of objects, i.e. the body shape
body = run("context.add_context", model, context_type="Model",
context_identifier="Body", target_view="MODEL_VIEW", parent=context)
# Create a site, building, and storey. Many hierarchies are possible.
site = run("root.create_entity", model, ifc_class="IfcSite", name="My Site")
building = run("root.create_entity", model, ifc_class="IfcBuilding", name="Building A")
storey = run("root.create_entity", model, ifc_class="IfcBuildingStorey", name="Ground Floor")
#create an ifc group
wallgroup = run("root.create_entity",model, ifc_class = "IfcGroup", name = "myfirstgroup")
# Since the site is our top level location, assign it to the project
# Then place our building on the site, and our storey in the building
run("aggregate.assign_object", model, relating_object=project, product=site)
run("aggregate.assign_object", model, relating_object=site, product=building)
run("aggregate.assign_object", model, relating_object=building, product=storey)
#this doesn't add to the storey - why?
run("aggregate.assign_object", model, relating_object=storey, product=wallgroup)
# And/Or, if we plan to store 2D geometry, we need a "Plan" context
plan = run("context.add_context", model, context_type="Plan")
# A 2D annotation subcontext for plan views are important for door
# swings, window cuts, and symbols for equipment like GPOs, fire
# extinguishers, and so on.
run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="PLAN_VIEW", parent=plan)
#------------------------modify file-----------------------------------#
#global variables
studSpacing = 450
#----------------------------CREATE IFC CARTESIAN POINT----------------------#
#next goal is to create cartesian points and lines. below doesn't work yet
#myPoint = ("root.create_entity",model, ifc_class = "IfcCartesianPoint", name = "myPoint")
def createpoint(name, x,y,z):
#create a 2d annotation point
annoPt1 = run("root.create_entity", model, ifc_class = "IfcAnnotation", name = str(name))
#instead create ifc directly.
myPoint1 = model.createIfcCartesianPoint((x,y,z))
#may need to do something with si units
#create representation (can I use a single vertice as a mesh representation?)
vert1 = [(x,y,z)]
vert_rep = model.createIfcShapeRepresentation(
ContextOfItems=body,
RepresentationIdentifier="Body",
RepresentationType="Point",
Items= [myPoint1])
#assign representation
run("geometry.assign_representation", model, product = annoPt1, representation = vert_rep)
#create object placement
run("geometry.edit_object_placement",model, product = myPoint1)
#assign to container
run("spatial.assign_container", model, relating_structure = storey, product = annoPt1)
return myPoint1
#need to rotate studs to normal of curve
pt1 = createpoint("pt1",2000.,00.0,0.0)
pt2 = createpoint("pt2",1000.,3000.0,0.0)
ptlist = [pt1,pt2]
#create a line between the points
def createline(name, pt1,pt2):
#create a 2d annotation point
annoLine = run("root.create_entity", model, ifc_class = "IfcAnnotation", name = str(name))
#plane = lambda f: [f.createIfcPlane(f.createIfcAxis2Placement3D(f.createIfcCartesianPoint((0., 0., 0.))))]
#instead create ifc directly.
myLine = model.createIfcPolyLine(ptlist)
line_rep = model.createIfcShapeRepresentation(
ContextOfItems=body,
RepresentationIdentifier="Body",
RepresentationType="Curve2d",
Items= [myLine])
#assign representation
run("geometry.assign_representation", model, product = annoLine, representation = line_rep)
#create object placement
run("geometry.edit_object_placement",model, product = myLine)
#assign to container
run("spatial.assign_container", model, relating_structure = storey, product = annoLine)
createline("line1",pt1,pt2)
#------------now trying to get points of line so can build from line up--------------#
#test get points back from line created
def get_element_by_name(ifc_file, element_type, element_name):
elements = ifc_file.by_type(element_type)
for element in elements:
if hasattr(element, "Name") and element.Name == element_name:
return element
return None
# Replace "IfcWall" with the specific type of element you're looking for
element_type = "IfcAnnotation"
# Replace "YourWallName" with the name of the element you're looking for
element_name = "line1"
found_element = get_element_by_name(model, element_type, element_name)
if found_element:
print(f"Element found: {found_element}")
else:
print(f"Element with name {element_name} not found.")
# Assuming you have an IfcCurve instance, replace this with your actual instance
ifc_curve = model.by_type("IfcCurve")[0]
# Get the start and end points of the curve
if hasattr(ifc_curve, "Points"):
# IfcPolyline or IfcTrimmedCurve
points = ifc_curve.Points
start_point = points[0]
end_point = points[-1]
print("Start Point:", start_point)
print("End Point:", end_point)
elif hasattr(ifc_curve, "StartPoint") and hasattr(ifc_curve, "EndPoint"):
# IfcLine, IfcCircle, or similar
start_point = ifc_curve.StartPoint
end_point = ifc_curve.EndPoint
print("Start Point:", start_point)
print("End Point:", end_point)
else:
print("Could not determine curve type or endpoints.")
#----------------------- get coords------------------#
def get_coordinates_of_polyline(ifc_polyline):
coordinates = []
for point in ifc_polyline.Points:
x, y, z = point.Coordinates[:3] if point.Coordinates else (None, None, None)
coordinates.append((x, y, z))
return coordinates
def create_points_along_vector(start_point, end_point, stepSize):
direction_vector = [(end - start) / (stepSize) for start, end in zip(start_point, end_point)]
new_points = [
tuple(start + i * step for start, step in zip(start_point, direction_vector))
for i in range(stepSize)
]
return new_points
#function to get normal of curve to rotate stud to align with it.
def calculate_polyline_angle(ifc_polyline):
# Assuming you have a get_coordinates_of_polyline function
coordinates = get_coordinates_of_polyline(ifc_polyline)
if len(coordinates) != 2:
return None # Invalid number of points for a polyline
# Calculate the direction vector of the polyline
direction_vector = np.array(coordinates[1]) - np.array(coordinates[0])
# Normalize the direction vector
normalized_direction = direction_vector / np.linalg.norm(direction_vector)
# Calculate the angle in degrees
angle_in_radians = np.arccos(normalized_direction.dot([1, 0, 0])) # Assuming reference axis is [1, 0, 0]
angle_in_degrees = np.degrees(angle_in_radians)
return angle_in_degrees
# Replace "IfcPolyline" with the specific type of curve you're working with
ifc_polyline_type = "IfcPolyline"
# Assuming you have an IfcPolyline instance, replace this with your actual instance
ifc_polyline = model.by_type(ifc_polyline_type)[0]
def getEndPoints(ifc_polyline):
# Get coordinates of points in the polyline
point_coordinates = get_coordinates_of_polyline(ifc_polyline)
# Display the coordinates
for i, coordinates in enumerate(point_coordinates):
print(f"Point {i + 1}: {coordinates}")
# Assuming you have at least two points
start_point = point_coordinates[0]
end_point = point_coordinates[-1]
#get IfcPolyline end points cast as variables
point1 = Vector((start_point[0],start_point[1],start_point[2]))
point2 = Vector((end_point[0],end_point[1],end_point[2]))
#returns a tuple that you have to unpack later
return (point1, point2)
#Divide Curve into points
def divideCurve(ifc_polyline,studspacing):
# Get coordinates of points in the polyline
point_coordinates = get_coordinates_of_polyline(ifc_polyline)
# Display the coordinates
for i, coordinates in enumerate(point_coordinates):
print(f"Point {i + 1}: {coordinates}")
# Assuming you have at least two points
start_point = point_coordinates[0]
end_point = point_coordinates[-1]
#get IfcPolyline end points cast as variables
point1 = Vector((start_point[0],start_point[1],start_point[2]))
point2 = Vector((end_point[0],end_point[1],end_point[2]))
#get length of base line
curveLength = (point1 - point2).length
#divide by studspacing
numPts = curveLength / studspacing
#round to integer for division
rndnumPts = int(numPts)
# Create new points along the vector between start and end points
new_points = create_points_along_vector(start_point, end_point, stepSize=rndnumPts)
# Display the new points
for i, coordinates in enumerate(new_points):
print(f"New Point {i + 1}: {coordinates}")
return new_points
def getCurveLength(ifc_polyline):
# Get coordinates of points in the polyline
point_coordinates = get_coordinates_of_polyline(ifc_polyline)
# Display the coordinates
for i, coordinates in enumerate(point_coordinates):
print(f"Point {i + 1}: {coordinates}")
# Assuming you have at least two points
start_point = point_coordinates[0]
end_point = point_coordinates[-1]
#get IfcPolyline end points cast as variables
point1 = Vector((start_point[0],start_point[1],start_point[2]))
point2 = Vector((end_point[0],end_point[1],end_point[2]))
#get length of base line
curveLength = (point1 - point2).length
return curveLength
#use divide curve definition to make location for vertical studs based on a global parameter
studPoints = divideCurve(ifc_polyline, studSpacing)
#gets the normal of the line for use in stud creation later
normal = calculate_polyline_angle(ifc_polyline)
def moveit(element,x,y,z,normal):
matrix = np.eye(4)
# Rotate the matix 90 degrees anti-clockwise around the Z axis (i.e. in plan).
# Anti-clockwise is positive. Clockwise is negative.
matrix = ifcopenshell.util.placement.rotation(normal, "Z") @ matrix
# Set the X, Y, Z coordinates. Notice how we rotate first then translate.
# This is because the rotation origin is always at 0, 0, 0.
matrix[:,3][0:3] = (x, y, z)
# Set our wall's Object Placement using our matrix.
# `is_si=True` states that we are using SI units instead of project units.
run("geometry.edit_object_placement", model, product=element, matrix=matrix, is_si=True)
#-----------------create a vertical stud----------------#
def createstud(x,y,z,rotZ,rotX,rotY,length):
#Create a new ShapeBuilder Object - think i need an new object???
studBuilder = ifcopenshell.util.shape_builder.ShapeBuilder(model)
#create vertical stud
stud1 = run("root.create_entity",model, ifc_class = "IfcBuildingElementPart")
# Parameters to define our stud
studWidth = 45
studDepth = 90
studHeight = length
# Extrude a rectangle profile for the tabletop
studProfile = studBuilder.rectangle(size=V(studWidth, studDepth))
stud = studBuilder.extrude(studBuilder.profile(studProfile), studHeight, V(0, 0, z))
# Create a body representation
stud_rep = studBuilder.get_representation(context=body, items=stud)
#assign representation to table1
run("geometry.assign_representation",model, product = stud1, representation = stud_rep)
#add to container
run("spatial.assign_container", model, relating_structure = storey, product = stud1)
#need to allow for change of object placement
# Create a 4x4 identity matrix. This matrix is at the origin with no rotation.
matrix = np.eye(4)
# Rotate the matix 90 degrees anti-clockwise around the Z axis (i.e. in plan).
# Anti-clockwise is positive. Clockwise is negative.
if rotX == None:
pass
else:
matrix = ifcopenshell.util.placement.rotation(rotX, "X") @ matrix
# Rotate the matix 90 degrees anti-clockwise around the Z axis (i.e. in plan).
# Anti-clockwise is positive. Clockwise is negative.
if rotY == None:
pass
else:
matrix = ifcopenshell.util.placement.rotation(rotY, "Y") @ matrix
# Rotate the matix 90 degrees anti-clockwise around the Z axis (i.e. in plan).
# Anti-clockwise is positive. Clockwise is negative.
matrix = ifcopenshell.util.placement.rotation(rotZ, "Z") @ matrix
# Set the X, Y, Z coordinates. Notice how we rotate first then translate.
# This is because the rotation origin is always at 0, 0, 0.
matrix[:,3][0:3] = (x, y, z)
# Set our wall's Object Placement using our matrix.
# `is_si=True` states that we are using SI units instead of project units.
run("geometry.edit_object_placement", model, product=stud1, matrix=matrix, is_si=True)
#we may create the stud as a single object that is then instanced across the wall assembly
#rename it
stud1.Name = "stud"
#new definition for sill plates
"""
#will replace in future to fit a 2d annotation line
for i in range(10):
y = i * 0.45
createstud(0,y,0)
"""
for point in studPoints:
createstud(point[0]/1000,point[1]/1000,point[2]/1000,normal,None,None,2700-45)
#get length of line
#this may all work better as a swept profile along an axis
#get end points to use below using custom function
tupleEndPts = getEndPoints(ifc_polyline)
pt1 = tupleEndPts[0]
pt2 = tupleEndPts[1]
print(str(pt1))
curveLength = getCurveLength(ifc_polyline)
#create end stud
#create sill plate
createstud(pt2[0]/1000,pt2[1]/1000,0,normal,None,None,2700-45)
#create sill plate
createstud(pt1[0]/1000,pt1[1]/1000,0,normal,None,90,curveLength)
#create top plate
createstud(pt1[0]/1000,pt1[1]/1000,2.7,normal,None,90,curveLength)
#create an IfcElementAssembly Object
#create wall assemlby
wallAssem1 = run("root.create_entity",model, ifc_class = "IfcElementAssembly")
wallAssem1.Name = "myAssem"
#representation - join mesh?
#assign representation to table1
#run("geometry.assign_representation",model, product = stud1, representation = stud_rep)
#assign container
run("spatial.assign_container", model, relating_structure = storey, product = wallAssem1)
#we dont want to move the object placement we want to change the object origin
#moveit(wallAssem1,10,10,10,normal)
#need to get studs as a product (not contained in a def so cant access)
studtoadd = model.by_type("IfcBuildingElementPart")[0]
#create list of stud
Studs = model.by_type("IfcBuildingElementPart")
#print(Studs)
#loop through studs and add to assembly
#print(Studs)
for stud in Studs:
#maybe need to create an aggregator object from the aggregate class to use it definitions
run(
"aggregate.assign_object", model, product=stud, relating_object=wallAssem1
)
#parent to wallAssem1
#get list of studs in collection for parenting
collection_name = "IfcElementAssembly/myAssem"
collection = bpy.data.collections.get(collection_name)
if collection:
# Get all objects in the collection
collection_objects = collection.objects
# Filter out only the mesh objects
mesh_objects = [obj for obj in collection_objects if obj.type == 'MESH']
# Get a list of mesh names
mesh_names = [obj.name for obj in mesh_objects]
#create assembly structure in blender
for mesh in mesh_names:
#bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
#this needs to be a string or in below
child1 = bpy.data.objects.get(mesh)
parent1 = bpy.data.objects.get(collection_name)
child1.parent = parent1
#assembly = model.by_type("IfcElementAssembly")
#---------------manually create your own type-----------------
"""
#dont forget to create root element
customrect = run("root.create_entity",model, ifc_class = "IfcFurniture")
#create the representation for your custom object
rectangle = model.createIfcRectangleProfileDef(ProfileType="AREA", XDim=500, YDim=300)
direction = model.createIfcDirection((0., 0., 1.))
extrusion = model.createIfcExtrudedAreaSolid(SweptArea=rectangle, ExtrudedDirection=direction, Depth=500)
body = ifcopenshell.util.representation.get_context(model, "Model", "Body", "MODEL_VIEW")
custom_rep = model.createIfcShapeRepresentation(
ContextOfItems=body, RepresentationIdentifier="Body", RepresentationType="SweptSolid", Items=[extrusion])
#add representation to the if object element you instantiated above
run("geometry.assign_representation", model, product = customrect, representation = custom_rep)
#assign the ifc object to a container
run("spatial.assign_container", model, relating_structure = storey, product = customrect)
#rename it
customrect.Name = "YourNewRect"
#move it
#ct.move(customrect, -1, 0,0)
"""
#---------------this writes the file above to ifc file
#re write file
model.write('c:\dev\studTest.ifc')