/
exportIFC.py
2495 lines (2272 loc) · 104 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 *
# * *
# ***************************************************************************
"""Provide the exporter for IFC files used above all in Arch and BIM.
Internally it uses IfcOpenShell, which must be installed before using.
"""
## @package exportIFC
# \ingroup ARCH
# \brief IFC file format exporter
#
# This module provides tools to export IFC files.
import os
import time
import tempfile
import math
import FreeCAD
import Part
import Draft
import Arch
import DraftVecUtils
import ArchIFCSchema
import exportIFCHelper
import exportIFCStructuralTools
from DraftGeomUtils import vec
from importIFCHelper import dd2dms
from draftutils.messages import _msg, _err
if FreeCAD.GuiUp:
import FreeCADGui
__title__ = "FreeCAD IFC export"
__author__ = ("Yorik van Havre", "Jonathan Wiedemann", "Bernd Hahnebach")
__url__ = "https://www.freecadweb.org"
# Save the Python open function because it will be redefined
if open.__module__ in ['__builtin__', 'io']:
pyopen = open
# 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",
"VisGroup": "Group",
"Undefined": "BuildingElementProxy",
}
# The base IFC template for export, the $variables will be substituted
# by specific information
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);
ENDSEC;
END-ISO-10303-21;
"""
def getPreferences():
"""Retrieve the IFC preferences available in import and export."""
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
if FreeCAD.GuiUp and p.GetBool("ifcShowDialog", False):
FreeCADGui.showPreferences("Import-Export", 1)
ifcunit = p.GetInt("ifcUnit", 0)
# Factor to multiply the dimension in millimeters
# mm x 0.001 = metre
# mm x 0.00328084 = foot
# mm x 0.03937008 = inch
# The only real use of these units is to make Revit choose which mode
# to work with.
#
# Inch is not yet implemented, and I don't even know if it is actually
# desired
f = 0.001
u = "metre"
if ifcunit == 1:
f = 0.00328084
u = "foot"
# if ifcunit == 2:
# f = 0.03937008
# u = "inch"
# Be careful with setting ADD_DEFAULT_SITE, ADD_DEFAULT_BUILDING,
# and ADD_DEFAULT_STOREY to False. If this is done the spatial structure
# may no longer be fully connected to the `IfcProject`. This means
# some objects may be "unreferenced" and won't belong to the `IfcProject`.
# Some applications may fail at importing these unreferenced objects.
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", True),
'ADD_DEFAULT_BUILDING': p.GetBool("IfcAddDefaultBuilding", True),
'ADD_DEFAULT_STOREY': p.GetBool("IfcAddDefaultStorey", True),
'IFC_UNIT': u,
'SCALE_FACTOR': f,
'GET_STANDARD': p.GetBool("getStandardType", False),
'EXPORT_MODEL': ['arch', 'struct', 'hybrid'][p.GetInt("ifcExportModel", 0)]
}
# get ifcopenshell version
ifcos_version = 0.0
if hasattr(ifcopenshell, "version"):
if ifcopenshell.version.startswith("0"):
ifcos_version = float(ifcopenshell.version[:3]) # < 0.6
elif ifcopenshell.version.startswith("v"):
ifcos_version = float(ifcopenshell.version[1:4]) # 0.7
else:
print("Could not retrieve IfcOpenShell version. Version is set to {}".format(ifcos_version))
else:
print("Could not retrieve IfcOpenShell version. Version is set to {}".format(ifcos_version))
# set schema
if hasattr(ifcopenshell, "schema_identifier"):
schema = ifcopenshell.schema_identifier
elif ifcos_version >= 0.6:
# v0.6 onwards allows to set our own schema
schema = ["IFC4", "IFC2X3"][p.GetInt("IfcVersion", 0)]
else:
schema = "IFC2X3"
preferences["SCHEMA"] = schema
return preferences
def export(exportList, filename, colors=None, preferences=None):
"""Export the selected objects to IFC format.
Parameters
----------
colors:
It defaults to `None`.
It 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.
"""
try:
global ifcopenshell
import ifcopenshell
except ModuleNotFoundError:
_err("IfcOpenShell was not found on this system. "
"IFC support is disabled.\n"
"Visit https://wiki.freecadweb.org/IfcOpenShell "
"to learn about installing it.")
return
if filename.lower().endswith("json"):
import json
try:
from ifcjson import ifc2json5a
except Exception:
try:
import ifc2json5a
except Exception:
_err("Error: Unable to locate ifc2json5a module. Aborting.")
return
starttime = time.time()
if preferences is None:
preferences = getPreferences()
# process template
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])
if preferences['DEBUG']: print("Exporting an", preferences['SCHEMA'], "file...")
template = template.replace("$ifcschema", preferences['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")
of.write(template)
of.close()
os.close(templatefilehandle)
# create IFC file
global ifcfile, surfstyles, clones, sharedobjects, profiledefs, shapedefs, uids
ifcfile = ifcopenshell.open(templatefile)
ifcfile = exportIFCHelper.writeUnits(ifcfile,preferences["IFC_UNIT"])
history = ifcfile.by_type("IfcOwnerHistory")[0]
objectslist = Draft.get_group_contents(exportList, walls=True,
addgroups=True)
# separate 2D objects
annotations = []
for obj in objectslist:
if obj.isDerivedFrom("Part::Part2DObject"):
annotations.append(obj)
elif obj.isDerivedFrom("App::Annotation") or (Draft.getType(obj) in ["DraftText","Text","Dimension","LinearDimension","AngularDimension"]):
annotations.append(obj)
elif obj.isDerivedFrom("Part::Feature"):
if obj.Shape and (not obj.Shape.Solids) and obj.Shape.Edges:
if not obj.Shape.Faces:
annotations.append(obj)
elif (obj.Shape.BoundBox.XLength < 0.0001) or (obj.Shape.BoundBox.YLength < 0.0001) or (obj.Shape.BoundBox.ZLength < 0.0001):
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)
# create project, context and geodata settings
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
decl = Draft.getObjectsOfType(objectslist, "Site")[0].Declination.getValueAs(FreeCAD.Units.Radian)
contextCreator.model_context.TrueNorth.DirectionRatios = (math.cos(decl+math.pi/2), math.sin(decl+math.pi/2))
# reusable entity system
global ifcbin
ifcbin = exportIFCHelper.recycler(ifcfile)
# setup analytic model
if preferences['EXPORT_MODEL'] in ['struct','hybrid']:
exportIFCStructuralTools.setup(ifcfile,ifcbin,preferences['SCALE_FACTOR'])
# define holders for the different types we create
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, ... }
uids = [] # store used UIDs to avoid reuse (some FreeCAD objects might have same IFC UID, ex. copy/pasted objects
# 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:
if obj.Name in products:
# never export same product twice
continue
# structural analysis object
structobj = None
if preferences['EXPORT_MODEL'] in ['struct','hybrid']:
structobj = exportIFCStructuralTools.createStructuralMember(ifcfile,ifcbin,obj)
if preferences['EXPORT_MODEL'] == 'struct':
continue
# getting generic data
name = getText("Name",obj)
description = getText("Description",obj)
uid = getUID(obj,preferences)
ifctype = getIfcTypeFromObj(obj)
# print(ifctype)
if ifctype == "IfcGroup":
groups[obj.Name] = [o.Name for o in obj.Group]
continue
# handle assemblies (arrays, app::parts, references, etc...)
assemblyElements = []
# if ifctype == "IfcArray":
# FIXME: the first array element is not placed correct if the array is not on coordinate origin
# https://forum.freecadweb.org/viewtopic.php?f=39&t=50085&p=431476#p431476
# workaround: do not use the assembly in ifc but a normal compound instead
if False:
clonedeltas = []
if obj.ArrayType == "ortho":
for i in range(obj.NumberX):
clonedeltas.append(obj.Placement.Base+(i*obj.IntervalX))
for j in range(obj.NumberY):
if j > 0:
clonedeltas.append(obj.Placement.Base+(i*obj.IntervalX)+(j*obj.IntervalY))
for k in range(obj.NumberZ):
if k > 0:
clonedeltas.append(obj.Placement.Base+(i*obj.IntervalX)+(j*obj.IntervalY)+(k*obj.IntervalZ))
#print("clonedeltas:",clonedeltas)
if clonedeltas:
ifctype = "IfcElementAssembly"
for delta in clonedeltas:
# print("delta: {}".format(delta))
representation,placement,shapetype = getRepresentation(
ifcfile,
context,
obj.Base,
forcebrep=(getBrepFlag(obj.Base,preferences)),
colors=colors,
preferences=preferences,
forceclone=delta
)
subproduct = createProduct(
ifcfile,
obj.Base,
getIfcTypeFromObj(obj.Base),
getUID(obj.Base,preferences),
history,
getText("Name",obj.Base),
getText("Description",obj.Base),
placement,
representation,
preferences
)
assemblyElements.append(subproduct)
# if an array was handled assemblyElements is not empty
# if assemblyElements is not empty later on
# the own Shape is ignored if representation is retrieved
# this because we will build an assembly for the assemblyElements
# from here and the assembly itself should not have a representation
if ifctype in ["IfcApp::Part","IfcPart::Compound","IfcElementAssembly"]:
if hasattr(obj,"Group"):
group = obj.Group
elif hasattr(obj,"Links"):
group = obj.Links
else:
group = [FreeCAD.ActiveDocument.getObject(n[:-1]) for n in obj.getSubObjects()]
for subobj in group:
if subobj.Name in products:
subproduct = products[subobj.Name]
else:
representation,placement,shapetype = getRepresentation(
ifcfile,
context,
subobj,
forcebrep=(getBrepFlag(subobj,preferences)),
colors=colors,
preferences=preferences
)
subproduct = createProduct(
ifcfile,
subobj,
getIfcTypeFromObj(subobj),
getUID(subobj,preferences),
history,
getText("Name",subobj),
getText("Description",subobj),
placement,
representation,
preferences)
products[obj.Name] = subproduct
assemblyElements.append(subproduct)
ifctype = "IfcElementAssembly"
# 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:
if preferences["DEBUG"]: print("Warning! Axis system object found '{}', but no axis data found.".format(obj.Label))
continue
ifctype = "IfcGrid"
for axg in axgroups:
ifcaxg = []
for ax in axg:
p1 = ifcbin.createIfcCartesianPoint(tuple(FreeCAD.Vector(ax[0]).multiply(preferences['SCALE_FACTOR'])[:2]))
p2 = ifcbin.createIfcCartesianPoint(tuple(FreeCAD.Vector(ax[1]).multiply(preferences['SCALE_FACTOR'])[: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
else:
if preferences["DEBUG"]: print("Warning! Axis system object '{}' only contains one set of axis but at least two are needed for a IfcGrid to be added to IFC.".format(obj.Label))
continue
if ifctype not in ArchIFCSchema.IfcProducts.keys():
ifctype = "IfcBuildingElementProxy"
# getting the representation
# ignore the own shape for assembly objects
skipshape = False
if assemblyElements:
# print("Assembly object: {}, thus own Shape will have no representation.".format(obj.Name))
skipshape = True
representation,placement,shapetype = getRepresentation(
ifcfile,
context,
obj,
forcebrep=(getBrepFlag(obj,preferences)),
colors=colors,
preferences=preferences,
skipshape=skipshape
)
if preferences['GET_STANDARD']:
if isStandardCase(obj,ifctype):
ifctype += "StandardCase"
if preferences['DEBUG']:
print(str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name)
# creating the product
product = createProduct(
ifcfile,
obj,
ifctype,
uid,
history,
name,
description,
placement,
representation,
preferences)
products[obj.Name] = product
if ifctype in ["IfcBuilding","IfcBuildingStorey","IfcSite","IfcSpace"]:
spatialelements[obj.Name] = product
# associate with structural analysis object if any
if structobj:
exportIFCStructuralTools.associates(ifcfile,product,structobj)
# gather assembly subelements
if assemblyElements:
ifcfile.createIfcRelAggregates(
ifcopenshell.guid.new(),
history,
'Assembly',
'',
products[obj.Name],
assemblyElements
)
if preferences['DEBUG']: print(" aggregating",len(assemblyElements),"object(s)")
# 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
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
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 = ''
key = str(key)
tp = str(tp)
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']:
pass
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*preferences['SCALE_FACTOR']))
if ("ExportWidth" in obj.IfcData) and obj.IfcData["ExportWidth"] and hasattr(obj,"Width"):
quantities.append(ifcfile.createIfcQuantityLength('Width',None,None,obj.Width.Value*preferences['SCALE_FACTOR']))
if ("ExportLength" in obj.IfcData) and obj.IfcData["ExportLength"] and hasattr(obj,"Length"):
quantities.append(ifcfile.createIfcQuantityLength('Length',None,None,obj.Length.Value*preferences['SCALE_FACTOR']))
if ("ExportHorizontalArea" in obj.IfcData) and obj.IfcData["ExportHorizontalArea"] and hasattr(obj,"HorizontalArea"):
quantities.append(ifcfile.createIfcQuantityArea('HorizontalArea',None,None,obj.HorizontalArea.Value*(preferences['SCALE_FACTOR']**2)))
if ("ExportVerticalArea" in obj.IfcData) and obj.IfcData["ExportVerticalArea"] and hasattr(obj,"VerticalArea"):
quantities.append(ifcfile.createIfcQuantityArea('VerticalArea',None,None,obj.VerticalArea.Value*(preferences['SCALE_FACTOR']**2)))
if ("ExportVolume" in obj.IfcData) and obj.IfcData["ExportVolume"] and obj.isDerivedFrom("Part::Feature"):
quantities.append(ifcfile.createIfcQuantityVolume('Volume',None,None,obj.Shape.Volume*(preferences['SCALE_FACTOR']**3)))
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
# relate structural analysis objects to the struct model
if preferences['EXPORT_MODEL'] in ['struct','hybrid']:
exportIFCStructuralTools.createStructuralGroup(ifcfile)
# relationships
sites = []
buildings = []
floors = []
treated = []
defaulthost = []
# buildingParts can be exported as any "normal" IFC type. In that case, gather their elements first
# if ifc type is "Undefined" gather elements too
for bp in Draft.getObjectsOfType(objectslist,"BuildingPart"):
if bp.IfcType not in ["Site","Building","Building Storey","Space"]:
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.get_group_contents(floor, walls=True, addgroups=True)
objs = Arch.pruneIncluded(objs)
objs.remove(floor) # get_group_contents + 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',