/
exportIFC.py
2083 lines (1899 loc) · 86.3 KB
/
exportIFC.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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ***************************************************************************
# * *
# * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
from __future__ import print_function
__title__ = "FreeCAD IFC export"
__author__ = "Yorik van Havre","Jonathan Wiedemann","Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import six
import os
import time
import tempfile
import math
import FreeCAD
import Part
import Draft
import Arch
import DraftVecUtils
import ArchIFCSchema
import exportIFCHelper
from DraftGeomUtils import vec
from importIFCHelper import dd2dms
from importIFCHelper import decode
## @package exportIFC
# \ingroup ARCH
# \brief IFC file format exporter
#
# This module provides tools to export IFC files.
if open.__module__ in ['__builtin__','io']:
pyopen = open
# pyopen is used in exporter to open a file in Arch
# ************************************************************************************************
# ********** templates and other definitions ****
# specific FreeCAD <-> IFC slang translations
translationtable = {
"Foundation":"Footing",
"Floor":"BuildingStorey",
"Rebar":"ReinforcingBar",
"HydroEquipment":"SanitaryTerminal",
"ElectricEquipment":"ElectricAppliance",
"Furniture":"FurnishingElement",
"Stair Flight":"StairFlight",
"Curtain Wall":"CurtainWall",
"Pipe Segment":"PipeSegment",
"Pipe Fitting":"PipeFitting"
}
# the base IFC template for export
ifctemplate = """ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');
FILE_NAME('$filename','$timestamp',('$owner','$email'),('$company'),'IfcOpenShell','IfcOpenShell','');
FILE_SCHEMA(('$ifcschema'));
ENDSEC;
DATA;
#1=IFCPERSON($,$,'$owner',$,$,$,$,$);
#2=IFCORGANIZATION($,'$company',$,$,$);
#3=IFCPERSONANDORGANIZATION(#1,#2,$);
#4=IFCAPPLICATION(#2,'$version','FreeCAD','118df2cf_ed21_438e_a41');
#5=IFCOWNERHISTORY(#3,#4,$,.ADDED.,$now,#3,#4,$now);
#6=IFCDIRECTION((1.,0.,0.));
#7=IFCDIRECTION((0.,0.,1.));
#8=IFCCARTESIANPOINT((0.,0.,0.));
#9=IFCAXIS2PLACEMENT3D(#8,#7,#6);
#10=IFCDIRECTION((0.,1.,0.));
#12=IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0);
#13=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);
#14=IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.);
#15=IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.);
#16=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);
#17=IFCMEASUREWITHUNIT(IFCPLANEANGLEMEASURE(0.017453292519943295),#16);
#18=IFCCONVERSIONBASEDUNIT(#12,.PLANEANGLEUNIT.,'DEGREE',#17);
#19=IFCUNITASSIGNMENT((#13,#14,#15,#18));
ENDSEC;
END-ISO-10303-21;
"""
# ************************************************************************************************
# ********** get the prefs, available in import and export ****************
def getPreferences():
"""retrieves IFC preferences"""
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
if FreeCAD.GuiUp and p.GetBool("ifcShowDialog",False):
import FreeCADGui
FreeCADGui.showPreferences("Import-Export",0)
preferences = {
'DEBUG': p.GetBool("ifcDebug",False),
'CREATE_CLONES': p.GetBool("ifcCreateClones",True),
'FORCE_BREP': p.GetBool("ifcExportAsBrep",False),
'STORE_UID': p.GetBool("ifcStoreUid",True),
'SERIALIZE': p.GetBool("ifcSerialize",False),
'EXPORT_2D': p.GetBool("ifcExport2D",True),
'FULL_PARAMETRIC': p.GetBool("IfcExportFreeCADProperties",False),
'ADD_DEFAULT_SITE': p.GetBool("IfcAddDefaultSite",False),
'ADD_DEFAULT_STOREY': p.GetBool("IfcAddDefaultStorey",False),
'ADD_DEFAULT_BUILDING': p.GetBool("IfcAddDefaultBuilding",True)
}
return preferences
# ************************************************************************************************
# ********** export IFC ****************
def export(exportList,filename,colors=None,preferences=None):
"""export(exportList,filename,colors=None,preferences=None) -- exports FreeCAD contents to an IFC file.
colors is an optional dictionary of objName:shapeColorTuple or objName:diffuseColorList elements
to be used in non-GUI mode if you want to be able to export colors."""
if preferences is None:
preferences = getPreferences()
try:
global ifcopenshell
import ifcopenshell
except:
FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
FreeCAD.Console.PrintMessage("Visit https://www.freecadweb.org/wiki/Arch_IFC to learn how to install it\n")
return
version = FreeCAD.Version()
owner = FreeCAD.ActiveDocument.CreatedBy
email = ''
if ("@" in owner) and ("<" in owner):
s = owner.split("<")
owner = s[0].strip()
email = s[1].strip(">")
global template
template = ifctemplate.replace("$version",version[0]+"."+version[1]+" build "+version[2])
getstd = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("getStandardType",False)
if hasattr(ifcopenshell,"schema_identifier"):
schema = ifcopenshell.schema_identifier
elif hasattr(ifcopenshell,"version") and (float(ifcopenshell.version[:3]) >= 0.6):
# v0.6 allows to set our own schema
schema = ["IFC4", "IFC2X3"][FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetInt("IfcVersion",0)]
else:
schema = "IFC2X3"
if preferences['DEBUG']: print("Exporting an",schema,"file...")
template = template.replace("$ifcschema",schema)
template = template.replace("$owner",owner)
template = template.replace("$company",FreeCAD.ActiveDocument.Company)
template = template.replace("$email",email)
template = template.replace("$now",str(int(time.time())))
template = template.replace("$filename",os.path.basename(filename))
template = template.replace("$timestamp",str(time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())))
if hasattr(ifcopenshell,"version"):
template = template.replace("IfcOpenShell","IfcOpenShell "+ifcopenshell.version)
templatefilehandle,templatefile = tempfile.mkstemp(suffix=".ifc")
of = pyopen(templatefile,"w")
if six.PY2:
template = template.encode("utf8")
of.write(template)
of.close()
os.close(templatefilehandle)
global ifcfile, surfstyles, clones, sharedobjects, profiledefs, shapedefs
ifcfile = ifcopenshell.open(templatefile)
history = ifcfile.by_type("IfcOwnerHistory")[0]
objectslist = Draft.getGroupContents(exportList,walls=True,addgroups=True)
annotations = []
for obj in objectslist:
if obj.isDerivedFrom("Part::Part2DObject"):
annotations.append(obj)
elif obj.isDerivedFrom("App::Annotation") or (Draft.getType(obj) == "DraftText"):
annotations.append(obj)
elif obj.isDerivedFrom("Part::Feature"):
if obj.Shape:
if obj.Shape.Edges and (not obj.Shape.Faces):
annotations.append(obj)
# clean objects list of unwanted types
objectslist = [obj for obj in objectslist if obj not in annotations]
objectslist = Arch.pruneIncluded(objectslist,strict=True)
objectslist = [obj for obj in objectslist if Draft.getType(obj) not in ["Dimension","Material","MaterialContainer","WorkingPlaneProxy"]]
if preferences['FULL_PARAMETRIC']:
objectslist = Arch.getAllChildren(objectslist)
contextCreator = exportIFCHelper.ContextCreator(ifcfile, objectslist)
context = contextCreator.model_view_subcontext
project = contextCreator.project
objectslist = [obj for obj in objectslist if obj != contextCreator.project_object]
if Draft.getObjectsOfType(objectslist, "Site"): # we assume one site and one representation context only
trueNorthX = math.tan(-Draft.getObjectsOfType(objectslist, "Site")[0].Declination.getValueAs(FreeCAD.Units.Radian))
contextCreator.model_context.TrueNorth.DirectionRatios = (trueNorthX, 1.)
products = {} # { Name: IfcEntity, ... }
subproducts = {} # { Name: IfcEntity, ... } for storing additions/subtractions and other types of subcomponents of a product
surfstyles = {} # { (r,g,b): IfcEntity, ... }
clones = {} # { Basename:[Clonename1,Clonename2,...] }
sharedobjects = {} # { BaseName: IfcRepresentationMap }
count = 1
groups = {} # { Host: [Child,Child,...] }
profiledefs = {} # { ProfileDefString:profiledef,...}
shapedefs = {} # { ShapeDefString:[shapes],... }
spatialelements = {} # {Name:IfcEntity, ... }
# reusable entity system
global ifcbin
ifcbin = exportIFCHelper.recycler(ifcfile)
# build clones table
if preferences['CREATE_CLONES']:
for o in objectslist:
b = Draft.getCloneBase(o,strict=True)
if b:
clones.setdefault(b.Name,[]).append(o.Name)
#print("clones table: ",clones)
#print(objectslist)
# testing if more than one site selected (forbidden in IFC)
# TODO: Moult: This is not forbidden in IFC.
if len(Draft.getObjectsOfType(objectslist,"Site")) > 1:
FreeCAD.Console.PrintError("More than one site is selected, which is forbidden by IFC standards. Please export only one site by IFC file.\n")
return
# products
for obj in objectslist:
# getting generic data
name = obj.Label
if six.PY2:
name = name.encode("utf8")
description = obj.Description if hasattr(obj,"Description") else ""
if six.PY2:
description = description.encode("utf8")
# getting uid
uid = None
if hasattr(obj,"IfcData"):
if "IfcUID" in obj.IfcData.keys():
uid = str(obj.IfcData["IfcUID"])
if not uid:
uid = ifcopenshell.guid.new()
# storing the uid for further use
if preferences['STORE_UID'] and hasattr(obj,"IfcData"):
d = obj.IfcData
d["IfcUID"] = uid
obj.IfcData = d
ifctype = getIfcTypeFromObj(obj)
if ifctype == "IfcGroup":
groups[obj.Name] = [o.Name for o in obj.Group]
continue
# export grids
if ifctype in ["IfcAxis","IfcAxisSystem","IfcGrid"]:
ifcaxes = []
ifcpols = []
if ifctype == "IfcAxis":
# make sure this axis is not included in something else already
standalone = True
for p in obj.InList:
if hasattr(p,"Axes") and (obj in p.Axes):
if p in objectslist:
axgroups = []
standalone = False
break
if standalone:
axgroups = [obj.Proxy.getAxisData(obj)]
else:
axgroups = obj.Proxy.getAxisData(obj)
if not axgroups:
continue
ifctype = "IfcGrid"
for axg in axgroups:
ifcaxg = []
for ax in axg:
p1 = ifcbin.createIfcCartesianPoint(tuple(FreeCAD.Vector(ax[0]).multiply(0.001)[:2]))
p2 = ifcbin.createIfcCartesianPoint(tuple(FreeCAD.Vector(ax[1]).multiply(0.001)[:2]))
pol = ifcbin.createIfcPolyline([p1,p2])
ifcpols.append(pol)
axis = ifcfile.createIfcGridAxis(ax[2],pol,True)
ifcaxg.append(axis)
if len(ifcaxes) < 3:
ifcaxes.append(ifcaxg)
else:
ifcaxes[2] = ifcaxes[2]+ifcaxg # IfcGrid can have max 3 axes systems
u = None
v = None
w = None
if ifcaxes:
u = ifcaxes[0]
if len(ifcaxes) > 1:
v = ifcaxes[1]
if len(ifcaxes) > 2:
w = ifcaxes[2]
if u and v:
if preferences['DEBUG']: print(str(count).ljust(3)," : ", ifctype, " (",str(len(ifcpols)),"axes ) : ",name)
xvc = ifcbin.createIfcDirection((1.0,0.0,0.0))
zvc = ifcbin.createIfcDirection((0.0,0.0,1.0))
ovc = ifcbin.createIfcCartesianPoint((0.0,0.0,0.0))
gpl = ifcbin.createIfcAxis2Placement3D(ovc,zvc,xvc)
plac = ifcbin.createIfcLocalPlacement(gpl)
cset = ifcfile.createIfcGeometricCurveSet(ifcpols)
#subc = ifcfile.createIfcGeometricRepresentationSubContext('FootPrint','Model',context,None,"MODEL_VIEW",None,None,None,None,None)
srep = ifcfile.createIfcShapeRepresentation(context,'FootPrint',"GeometricCurveSet",ifcpols)
pdef = ifcfile.createIfcProductDefinitionShape(None,None,[srep])
grid = ifcfile.createIfcGrid(uid,history,name,description,None,plac,pdef,u,v,w)
products[obj.Name] = grid
count += 1
continue
if ifctype not in ArchIFCSchema.IfcProducts.keys():
ifctype = "IfcBuildingElementProxy"
# getting the "Force BREP" flag
brepflag = False
if hasattr(obj,"IfcData"):
if "FlagForceBrep" in obj.IfcData.keys():
if obj.IfcData["FlagForceBrep"] == "True":
brepflag = True
# getting the representation
representation,placement,shapetype = getRepresentation(
ifcfile,
context,
obj,
forcebrep=(brepflag or preferences['FORCE_BREP']),
colors=colors,
preferences=preferences
)
if getstd:
if isStandardCase(obj,ifctype):
ifctype += "StandardCase"
if preferences['DEBUG']: print(str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name)
# setting the arguments
kwargs = {
"GlobalId": uid,
"OwnerHistory": history,
"Name": name,
"Description": description,
"ObjectPlacement": placement,
"Representation": representation
}
if ifctype == "IfcSite":
kwargs.update({
"RefLatitude":dd2dms(obj.Latitude),
"RefLongitude":dd2dms(obj.Longitude),
"RefElevation":obj.Elevation.Value/1000.0,
"SiteAddress":buildAddress(obj,ifcfile),
"CompositionType": "ELEMENT"
})
if schema == "IFC2X3":
kwargs = exportIFC2X3Attributes(obj, kwargs)
else:
kwargs = exportIfcAttributes(obj, kwargs)
# creating the product
#print(obj.Label," : ",ifctype," : ",kwargs)
product = getattr(ifcfile,"create"+ifctype)(**kwargs)
products[obj.Name] = product
if ifctype in ["IfcBuilding","IfcBuildingStorey","IfcSite","IfcSpace"]:
spatialelements[obj.Name] = product
# additions
if hasattr(obj,"Additions") and (shapetype in ["extrusion","no shape"]):
for o in obj.Additions:
r2,p2,c2 = getRepresentation(ifcfile,context,o,colors=colors,preferences=preferences)
if preferences['DEBUG']: print(" adding ",c2," : ",o.Label)
l = o.Label
if six.PY2:
l = l.encode("utf8")
prod2 = ifcfile.createIfcBuildingElementProxy(
ifcopenshell.guid.new(),
history,
l,
None,
None,
p2,
r2,
None,
"ELEMENT"
)
subproducts[o.Name] = prod2
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'Addition',
'',
product,
[prod2]
)
# subtractions
guests = []
for o in obj.InList:
if hasattr(o,"Hosts"):
for co in o.Hosts:
if co == obj:
if o not in guests:
guests.append(o)
if hasattr(obj,"Subtractions") and (shapetype in ["extrusion","no shape"]):
for o in obj.Subtractions + guests:
r2,p2,c2 = getRepresentation(ifcfile,context,o,subtraction=True,colors=colors,preferences=preferences)
if preferences['DEBUG']: print(" subtracting ",c2," : ",o.Label)
l = o.Label
if six.PY2:
l = l.encode("utf8")
prod2 = ifcfile.createIfcOpeningElement(
ifcopenshell.guid.new(),
history,
l,
None,
None,
p2,
r2,
None
)
subproducts[o.Name] = prod2
ifcfile.createIfcRelVoidsElement(
ifcopenshell.guid.new(),
history,
'Subtraction',
'',
product,
prod2
)
# properties
ifcprop = False
if hasattr(obj,"IfcProperties"):
if obj.IfcProperties:
ifcprop = True
if isinstance(obj.IfcProperties,dict):
# IfcProperties is a dictionary (FreeCAD 0.18)
psets = {}
for key,value in obj.IfcProperties.items():
pset, pname, ptype, pvalue = getPropertyData(key,value,preferences)
if pvalue is None:
if preferences['DEBUG']: print(" property ", pname," ignored because no value found.")
continue
p = ifcbin.createIfcPropertySingleValue(str(pname),str(ptype),pvalue)
psets.setdefault(pset,[]).append(p)
for pname,props in psets.items():
pset = ifcfile.createIfcPropertySet(
ifcopenshell.guid.new(),
history,
pname,
None,
props
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],
pset
)
elif obj.IfcProperties.TypeId == 'Spreadsheet::Sheet':
# IfcProperties is a spreadsheet (deprecated)
sheet = obj.IfcProperties
propertiesDic = {}
categories = []
n = 2
cell = True
while cell is True:
if hasattr(sheet,'A'+str(n)):
cat = sheet.get('A'+str(n))
key = sheet.get('B'+str(n))
tp = sheet.get('C'+str(n))
if hasattr(sheet,'D'+str(n)):
val = sheet.get('D'+str(n))
else:
val = ''
if six.PY2 and isinstance(key, six.text_type):
key = key.encode("utf8")
else:
key = str(key)
if six.PY2 and isinstance(tp, six.text_type):
tp = tp.encode("utf8")
else:
tp = str(tp)
#tp = tp.encode("utf8")
if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
val = val.encode("utf8")
elif tp == "IfcBoolean":
if val == 'True':
val = True
else:
val = False
elif tp == "IfcInteger":
val = int(val)
else:
val = float(val)
unit = None
#unit = sheet.get('E'+str(n))
if cat in categories:
propertiesDic[cat].append({"key":key,"tp":tp,"val":val,"unit":unit})
else:
propertiesDic[cat] = [{"key":key,"tp":tp,"val":val,"unit":unit}]
categories.append(cat)
n += 1
else:
cell = False
for cat in propertiesDic:
props = []
for prop in propertiesDic[cat]:
if preferences['DEBUG']:
print("key",prop["key"],type(prop["key"]))
print("tp",prop["tp"],type(prop["tp"]))
print("val",prop["val"],type(prop["val"]))
if tp.lower().startswith("ifc"):
props.append(ifcbin.createIfcPropertySingleValue(prop["key"],prop["tp"],prop["val"]))
else:
print("Unable to create a property of type:",tp)
if props:
pset = ifcfile.createIfcPropertySet(
ifcopenshell.guid.new(),
history,cat,
None,
props
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],
pset
)
if hasattr(obj,"IfcData"):
if obj.IfcData:
ifcprop = True
#if preferences['DEBUG'] : print(" adding ifc attributes")
props = []
for key in obj.IfcData:
if not (key in ["attributes", "complex_attributes", "IfcUID", "FlagForceBrep"]):
# (deprecated) properties in IfcData dict are stored as "key":"type(value)"
r = obj.IfcData[key].strip(")").split("(")
if len(r) == 1:
tp = "IfcText"
val = r[0]
else:
tp = r[0]
val = "(".join(r[1:])
val = val.strip("'")
val = val.strip('"')
#if preferences['DEBUG']: print(" property ",key," : ",val.encode("utf8"), " (", str(tp), ")")
if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
if six.PY2:
val = val.encode("utf8")
elif tp == "IfcBoolean":
if val == ".T.":
val = True
else:
val = False
elif tp == "IfcInteger":
val = int(val)
else:
val = float(val)
props.append(ifcbin.createIfcPropertySingleValue(str(key),str(tp),val))
if props:
pset = ifcfile.createIfcPropertySet(
ifcopenshell.guid.new(),
history,
'PropertySet',
None,
props
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],
pset
)
if not ifcprop:
#if preferences['DEBUG'] : print("no ifc properties to export")
pass
# Quantities
if hasattr(obj,"IfcData"):
quantities = []
if ("ExportHeight" in obj.IfcData) and obj.IfcData["ExportHeight"] and hasattr(obj,"Height"):
quantities.append(ifcfile.createIfcQuantityLength('Height',None,None,obj.Height.Value/1000.0))
if ("ExportWidth" in obj.IfcData) and obj.IfcData["ExportWidth"] and hasattr(obj,"Width"):
quantities.append(ifcfile.createIfcQuantityLength('Width',None,None,obj.Width.Value/1000.0))
if ("ExportLength" in obj.IfcData) and obj.IfcData["ExportLength"] and hasattr(obj,"Length"):
quantities.append(ifcfile.createIfcQuantityLength('Length',None,None,obj.Length.Value/1000.0))
if ("ExportHorizontalArea" in obj.IfcData) and obj.IfcData["ExportHorizontalArea"] and hasattr(obj,"HorizontalArea"):
quantities.append(ifcfile.createIfcQuantityArea('HorizontalArea',None,None,obj.HorizontalArea.Value/1000000.0))
if ("ExportVerticalArea" in obj.IfcData) and obj.IfcData["ExportVerticalArea"] and hasattr(obj,"VerticalArea"):
quantities.append(ifcfile.createIfcQuantityArea('VerticalArea',None,None,obj.VerticalArea.Value/1000000.0))
if ("ExportVolume" in obj.IfcData) and obj.IfcData["ExportVolume"] and obj.isDerivedFrom("Part::Feature"):
quantities.append(ifcfile.createIfcQuantityVolume('Volume',None,None,obj.Shape.Volume/1000000000.0))
if quantities:
eltq = ifcfile.createIfcElementQuantity(
ifcopenshell.guid.new(),
history,
"ElementQuantities",
None,
"FreeCAD",quantities
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],eltq
)
if preferences['FULL_PARAMETRIC']:
# exporting all the object properties
FreeCADProps = []
FreeCADGuiProps = []
FreeCADProps.append(ifcbin.createIfcPropertySingleValue("FreeCADType","IfcText",obj.TypeId))
FreeCADProps.append(ifcbin.createIfcPropertySingleValue("FreeCADName","IfcText",obj.Name))
sets = [("App",obj)]
if hasattr(obj,"Proxy"):
if obj.Proxy:
FreeCADProps.append(ifcbin.createIfcPropertySingleValue("FreeCADAppObject","IfcText",str(obj.Proxy.__class__)))
if FreeCAD.GuiUp:
if obj.ViewObject:
sets.append(("Gui",obj.ViewObject))
if hasattr(obj.ViewObject,"Proxy"):
if obj.ViewObject.Proxy:
FreeCADGuiProps.append(
ifcbin.createIfcPropertySingleValue(
"FreeCADGuiObject",
"IfcText",
str(obj.ViewObject.Proxy.__class__)
)
)
for realm,ctx in sets:
if ctx:
for prop in ctx.PropertiesList:
if not(prop in ["IfcProperties","IfcData","Shape","Proxy","ExpressionEngine","AngularDeflection","BoundingBox"]):
try:
ptype = ctx.getTypeIdOfProperty(prop)
except AttributeError:
ptype = "Unknown"
itype = None
ivalue = None
if ptype in ["App::PropertyString","App::PropertyEnumeration"]:
itype = "IfcText"
ivalue = getattr(ctx,prop)
elif ptype == "App::PropertyInteger":
itype = "IfcInteger"
ivalue = getattr(ctx,prop)
elif ptype == "App::PropertyFloat":
itype = "IfcReal"
ivalue = float(getattr(ctx,prop))
elif ptype == "App::PropertyBool":
itype = "IfcBoolean"
ivalue = getattr(ctx,prop)
elif ptype in ["App::PropertyVector","App::PropertyPlacement"]:
itype = "IfcText"
ivalue = str(getattr(ctx,prop))
elif ptype in ["App::PropertyLength","App::PropertyDistance"]:
itype = "IfcReal"
ivalue = float(getattr(ctx,prop).getValueAs("m"))
elif ptype == "App::PropertyArea":
itype = "IfcReal"
ivalue = float(getattr(ctx,prop).getValueAs("m^2"))
elif ptype == "App::PropertyLink":
t = getattr(ctx,prop)
if t:
itype = "IfcText"
ivalue = "FreeCADLink_" + t.Name
else:
if preferences['DEBUG']: print("Unable to encode property ",prop," of type ",ptype)
if itype:
# TODO add description
if realm == "Gui":
FreeCADGuiProps.append(ifcbin.createIfcPropertySingleValue("FreeCADGui_"+prop,itype,ivalue))
else:
FreeCADProps.append(ifcbin.createIfcPropertySingleValue("FreeCAD_"+prop,itype,ivalue))
if FreeCADProps:
pset = ifcfile.createIfcPropertySet(
ifcopenshell.guid.new(),
history,'FreeCADPropertySet',
None,
FreeCADProps
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],
pset
)
if FreeCADGuiProps:
pset = ifcfile.createIfcPropertySet(
ifcopenshell.guid.new(),
history,
'FreeCADGuiPropertySet',
None,
FreeCADGuiProps
)
ifcfile.createIfcRelDefinesByProperties(
ifcopenshell.guid.new(),
history,
None,
None,
[product],
pset
)
count += 1
# relationships
sites = []
buildings = []
floors = []
treated = []
defaulthost = []
# buildingParts can be exported as any "normal" IFC type. In that case, gather their elements first
for bp in Draft.getObjectsOfType(objectslist,"BuildingPart"):
if bp.IfcType not in ["Site","Building","Building Storey","Space","Undefined"]:
if bp.Name in products:
subs = []
for c in bp.Group:
if c.Name in products:
subs.append(products[c.Name])
treated.append(c.Name)
if subs:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'Assembly',
'',
products[bp.Name],
subs
)
# storeys
for floor in Draft.getObjectsOfType(objectslist,"Floor")+Draft.getObjectsOfType(objectslist,"BuildingPart"):
if (Draft.getType(floor) == "Floor") or (hasattr(floor,"IfcType") and floor.IfcType == "Building Storey"):
objs = Draft.getGroupContents(floor,walls=True,addgroups=True)
objs = Arch.pruneIncluded(objs)
objs.remove(floor) # getGroupContents + addgroups will include the floor itself
buildingelements, spaces = [], []
for c in objs:
if c.Name in products and c.Name not in treated:
prod = products[c.Name]
if prod.is_a()=='IfcSpace':
spaces.append(prod)
else:
buildingelements.append(prod)
treated.append(c.Name)
f = products[floor.Name]
if buildingelements:
ifcfile.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(),
history,
'StoreyLink',
'',
buildingelements,
f
)
if spaces:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'StoreyLink',
'',
f,
spaces
)
floors.append(f)
defaulthost = f
# buildings
for building in Draft.getObjectsOfType(objectslist,"Building")+Draft.getObjectsOfType(objectslist,"BuildingPart"):
if (Draft.getType(building) == "Building") or (hasattr(building,"IfcType") and building.IfcType == "Building"):
objs = Draft.getGroupContents(building,walls=True,addgroups=True)
objs = Arch.pruneIncluded(objs)
children = []
childfloors = []
for c in objs:
if not (c.Name in treated):
if c.Name != building.Name: # getGroupContents + addgroups will include the building itself
if c.Name in products.keys():
if Draft.getType(c) in ["Floor","BuildingPart","Space"]:
childfloors.append(products[c.Name])
treated.append(c.Name)
elif not (c.Name in treated):
children.append(products[c.Name])
treated.append(c.Name)
b = products[building.Name]
if children:
ifcfile.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(),
history,
'BuildingLink',
'',
children,
b
)
if childfloors:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'BuildingLink',
'',
b,
childfloors
)
buildings.append(b)
if not defaulthost and not preferences['ADD_DEFAULT_STOREY']:
defaulthost = b
# sites
for site in exportIFCHelper.getObjectsOfIfcType(objectslist, "Site"):
objs = Draft.getGroupContents(site,walls=True,addgroups=True)
objs = Arch.pruneIncluded(objs)
children = []
childbuildings = []
for c in objs:
if c.Name != site.Name: # getGroupContents + addgroups will include the building itself
if c.Name in products.keys():
if not (c.Name in treated):
if Draft.getType(c) == "Building":
childbuildings.append(products[c.Name])
treated.append(c.Name)
sites.append(products[site.Name])
# add default site, building and storey as required
if not sites:
if preferences['ADD_DEFAULT_SITE']:
if preferences['DEBUG']: print("No site found. Adding default site")
sites = [ifcfile.createIfcSite(
ifcopenshell.guid.new(),
history,"Default Site",
'',
None,
None,
None,
None,
"ELEMENT",
None,
None,
None,
None,
None
)]
if sites:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'ProjectLink',
'',
project,sites
)
if not buildings:
if preferences['ADD_DEFAULT_BUILDING']:
if preferences['DEBUG']: print("No building found. Adding default building")
buildings = [ifcfile.createIfcBuilding(
ifcopenshell.guid.new(),
history,
"Default Building",
'',
None,
None,
None,
None,
"ELEMENT",
None,
None,
None
)]
if buildings and (not sites):
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'ProjectLink',
'',
project,buildings
)
if floors:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'BuildingLink',
'',
buildings[0],floors
)
if sites and buildings:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'SiteLink',
'',
sites[0],
buildings
)
# treat objects that are not related to any site, building or storey
untreated = []
for k,v in products.items():
if not(k in treated):
if (not buildings) or (k != buildings[0].Name):
if not(Draft.getType(FreeCAD.ActiveDocument.getObject(k)) in ["Site","Building","Floor","BuildingPart"]):
untreated.append(v)
elif Draft.getType(FreeCAD.ActiveDocument.getObject(k)) == "BuildingPart":
if not(FreeCAD.ActiveDocument.getObject(k).IfcType in ["Building","Building Storey","Site","Space","Undefined"]):
untreated.append(v)
if untreated:
if not defaulthost:
if preferences['ADD_DEFAULT_STOREY']:
defaulthost = ifcfile.createIfcBuildingStorey(
ifcopenshell.guid.new(),
history,
"Default Storey",
'',
None,
None,
None,
None,
"ELEMENT",
None
)
# if preferences['ADD_DEFAULT_STOREY'] is on, we need a building
# to host it, regardless of preferences['ADD_DEFAULT_BUILDING']
if not buildings:
if preferences['DEBUG']: print("No building found. Adding default building")
buildings = [ifcfile.createIfcBuilding(
ifcopenshell.guid.new(),
history,
"Default Building",
'',
None,