/
freecad_reader.py
403 lines (370 loc) · 17.4 KB
/
freecad_reader.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
# -*- coding: utf-8 -*-
''' Read block topology data from FreeCAD files.'''
from __future__ import division
from __future__ import print_function
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AO_O)"
__copyright__= "Copyright 2020, LCPT and AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com" "ana.ortega.ort@gmail.com"
import xc_base
import sys
import re
from import_export import reader_base
from scipy.spatial.distance import cdist
from misc_utils import log_messages as lmsg
from import_export import block_topology_entities as bte
# path to FreeCAD.so
FREECADPATH = '/usr/lib/freecad-daily-python2/lib/'
if(sys.version_info.major == 3):
FREECADPATH = '/usr/lib/freecad-daily-python3/lib/'
sys.path.append(FREECADPATH)
# import FreeCAD
# NOTE 1: Apparently the FreeCAD module redirects C standard output
# somewhere so you stop seeing cout, clog and cerr messages in the
# console.
try:
import FreeCAD
xc_base.resetStandardOutput() # See NOTE 1.
except ModuleNotFoundError as err:
# Error handling
lmsg.log(err)
quit()
ifcStringAttributes= ['IfcType', 'PredefinedType', 'IfcProperties', 'SteelGrade']
ifcLengthAttributes= ['Thickness', 'LongitudinalBarNominalDiameter', 'LongitudinalBarSpacing', 'TransverseBarNominalDiameter', 'TransverseBarSpacing']
ifcAreaAttributes= ['LongitudinalBarCrossSectionArea', 'TransverseBarCrossSectionArea']
def getType(obj):
'''getType(object): returns the Draft type of the given object'''
import Part
if not obj:
return None
if isinstance(obj,Part.Shape):
return 'Shape'
if 'Proxy' in obj.PropertiesList:
if hasattr(obj.Proxy,'Type'):
return obj.Proxy.Type
if obj.isDerivedFrom('Sketcher::SketchObject'):
return 'Sketch'
if (obj.TypeId == 'Part::Line'):
return 'Part::Line'
if (obj.TypeId == 'Part::Offset2D'):
return 'Offset2D'
if obj.isDerivedFrom('Part::Feature'):
return 'Part'
if (obj.TypeId == 'App::Annotation'):
return 'Annotation'
if obj.isDerivedFrom('Mesh::Feature'):
return 'Mesh'
if obj.isDerivedFrom('Points::Feature'):
return 'Points'
if (obj.TypeId == 'App::DocumentObjectGroup'):
return 'Group'
if (obj.TypeId == 'App::Part'):
return 'App::Part'
return 'Unknown'
def get_ifc_attributes(obj):
''' Return the ifc attributes of the argument.
:param obj: object to get the IFC attributes from.
'''
retval= dict()
# Read "regular" attributes
for attrName in ifcStringAttributes:
if hasattr(obj,attrName):
retval[attrName]= getattr(obj,attrName)
# Read attributes that correspond to a lenght measurement.
for attrName in ifcLengthAttributes:
if hasattr(obj,attrName):
retval[attrName]= float(getattr(obj,attrName).getValueAs('m')) # meter
# Read attributes that correspond to an area measurement.
for attrName in ifcAreaAttributes:
if hasattr(obj,attrName):
retval[attrName]= getattr(obj,attrName) # square meter
# Read attributes that have a somewhat "special" treatment in XC.
if hasattr(obj,'Material') and obj.Material:
retval['Material']= obj.Material.Label
if hasattr(obj,'Description'):
retval['IfcDescription']= obj.Description
return retval
class FreeCADImport(reader_base.ReaderBase):
'''Import FreeCAD geometric entities.
:ivar groupsToImport: list of regular expressions to be tested.
'''
def __init__(self,fileName, groupsToImport, getRelativeCoo, threshold= 0.01,importLines= True, importSurfaces= True):
''' Constructor.
:param fileName: file name to import.
:param groupsToImport: list of regular expressions to be tested.
:param getRelativeCoo: coordinate transformation to be applied to the
points.
:param importLines: if true import lines.
:param importSurfaces: if true import surfaces.
'''
super(FreeCADImport, self).__init__(fileName, getRelativeCoo, threshold, importLines, importSurfaces)
self.document= FreeCAD.openDocument(self.fileName)
self.groupsToImport= self.getObjectsToImport(groupsToImport)
self.compounds= dict() # Stack for compound names.
if(len(self.groupsToImport)):
self.kPointsNames= self.selectKPoints()
self.importPoints()
if(self.impLines):
self.importLines()
if(self.impSurfaces):
self.importFaces()
else:
self.kPoints= None
def getObjectsToImport(self, namesToImport):
'''Return the object names that will be imported according to the
regular expressions contained in the second argument.
:param namesToImport: list of regular expressions to be tested.
'''
retval= []
# Compile regular expressions.
regExpList= list()
for name in namesToImport:
regExpList.append(re.compile(name))
for obj in self.document.Objects:
if(reader_base.nameToImport(obj.Label, regExpList)):
retval.append(obj)
if(len(retval)==0):
className= type(self).__name__
methodName= sys._getframe(0).f_code.co_name
lmsg.warning(className+'.'+methodName+f': no groups to import (names to import: {namesToImport})')
return retval
def extractPoints(self):
'''Extract the points from the entities argument.'''
retval_pos= dict()
retval_properties= dict()
def append_point(pt, groupLabel, pointName, objProperties):
'''Append the point to the lists.'''
retval_pos[pointName]= self.getRelativeCoo(pt)
# group name as label.
objProperties.extendLabels([groupLabel])
retval_properties[pointName]= objProperties
def append_points(vertexes, objName, groupLabel, objProperties):
'''Append the points to the list.'''
if(len(vertexes)>1):
for ptCount, v in enumerate(vertexes):
pointName= f'{objName}.{ptCount}'
append_point([v.X, v.Y, v.Z], groupLabel, pointName, objProperties)
else:
v= vertexes[0]
append_point([v.X, v.Y, v.Z], groupLabel, objName, objProperties)
for grp in self.groupsToImport:
groupLabel= grp.Label
if(hasattr(grp,'Shape')): # Object has shape.
objName= grp.Name
shape= grp.Shape
shapeType= shape.ShapeType
objProperties= bte.BlockProperties(labels= [groupLabel])
if(shapeType=='Shell'):
for fCount, f in enumerate(shape.SubShapes):
thisFaceName= f'{objName}.{fCount}'
append_points(f.OuterWire.OrderedVertexes, thisFaceName, groupLabel, objProperties)
else:
append_points(grp.Shape.Vertexes, objName, groupLabel, objProperties)
elif(len(grp.OutList)>0): # Object is a group
for obj in grp.OutList:
if(hasattr(obj,'Shape')): # Object has shape.
shapeType= obj.Shape.ShapeType
objName= obj.Name
objProperties= bte.BlockProperties(labels= [obj.Label])
if(shapeType=='Face'):
append_points(obj.Shape.Vertexes, objName, groupLabel, objProperties)
return retval_pos, retval_properties
def importPoints(self):
''' Import points from FreeCAD file.'''
self.points= dict()
for obj in self.groupsToImport:
if(hasattr(obj,'Shape')):
shape= obj.Shape
shapeType= shape.ShapeType
pointName= obj.Name
labelName= obj.Label
if(shapeType=='Vertex'):
vertices= [-1]
p= self.getRelativeCoo([float(shape.X), float(shape.Y), float(shape.Z)])
vertices[0]= self.getIndexNearestPoint(p)
self.points[pointName]= vertices
pointAttributes= get_ifc_attributes(obj)
properties= bte.BlockProperties(labels= [labelName], attributes= pointAttributes)
self.propertyDict[pointName]= properties
def importLines(self):
''' Import lines from FreeCAD file.'''
self.lines= dict()
def import_edge(e, edgeName, labelName, edgeAttributes):
''' Import an edge.
:param e: edge to import.
:param edgeName: name of the edge object.
:param labelName: label of the parent object.
:param edgeAttributes: IFC attributes of the parent object.
'''
vertices= [-1,-1]
v0= e.Vertexes[0]
v1= e.Vertexes[1]
p1= self.getRelativeCoo([float(v0.X), float(v0.Y), float(v0.Z)])
p2= self.getRelativeCoo([float(v1.X), float(v1.Y), float(v1.Z)])
length= cdist([p1],[p2])[0][0]
# Try to have all lines with the
# same orientation.
idx0, idx1= self.getOrientation(p1, p2, length/1e4)
# end orientation.
vertices[0]= idx0
vertices[1]= idx1
if(vertices[0]==vertices[1]):
className= type(self).__name__
methodName= sys._getframe(0).f_code.co_name
lmsg.error(className+'.'+methodName+f': error in line {edgeName} vertices are equal: {vertices}')
if(length>self.threshold):
self.lines[edgeName]= vertices
objLabels= [labelName]
# # groups
# if(edgeName in self.entitiesGroups):
# objLabels.extend(self.entitiesGroups[edgeName])
self.propertyDict[edgeName]= bte.BlockProperties(labels= objLabels, attributes= edgeAttributes)
else:
className= type(self).__name__
methodName= sys._getframe(0).f_code.co_name
lmsg.error(className+'.'+methodName+f'; line too short: {p1},{p2}, {length}')
def import_edges(edges, names, labelName, attributes):
''' Import edges from a wire shape.
:param edges: edge list.
:param names: list containing the names of the edges.
:param labelName: label of the parent object.
:param attributes: IFC attributes for all the edges.
'''
for e, name in zip(edges, names):
import_edge(e, name, labelName, attributes)
def import_wire(wireObj, attributes):
''' Import a wire shape.
:param wireObj: shape object containing the wire.
:param wireName: name of the wire object.
:param objLabel: label of the parent object.
:param attributes: IFC attributes for all the edges.
'''
labelName= wireObj.Label
edges= list()
names= list()
for i, e in enumerate(wireObj.Shape.Edges):
edges.append(e)
names.append(f'{wireObj.Name}{i}')
import_edges(edges, names, labelName, attributes)
for obj in self.groupsToImport:
if(hasattr(obj,'Shape')):
shapeType= obj.Shape.ShapeType
labelName= obj.Label
attributes= get_ifc_attributes(obj)
if(shapeType=='Wire'):
import_wire(obj, attributes)
elif(shapeType=='Compound'):
for cCount, ss in enumerate(obj.Shape.SubShapes):
ssName= f'{obj.Name}.{cCount}'
edges= ss.Edges
names= list()
for i in range(0,len(edges)):
names.append(ssName+'.'+str(i))
import_edges(edges, names, labelName+'.'+ssName, attributes)
elif(shapeType=='Edge'):
className= type(self).__name__
methodName= sys._getframe(0).f_code.co_name
lmsg.warning(className+'.'+methodName+'; entity with shape of type: '+shapeType+' not imported yet (promote it into "Line" if you want it to be imported).')
def importFaces(self):
''' Import faces from FreeCAD file.'''
self.facesTree= dict()
for obj in self.groupsToImport:
self.facesTree[obj.Label]= dict()
def import_face(faceShape, faceName, objLabel):
''' Add the face argument to the dictionary.'''
objPoints= list()
for wire in faceShape.Wires:
wirePoints= list()
for v in wire.OrderedVertexes:
wirePoints.append([float(v.X), float(v.Y), float(v.Z)])
objPoints.append(wirePoints)
vertices= list()
for wirePoints in objPoints:
wireVertices= list()
for pt in wirePoints:
p= self.getRelativeCoo(pt)
idx= self.getIndexNearestPoint(p)
wireVertices.append(idx)
vertices.append(wireVertices)
# Outer wire.
facesDict[faceName]= vertices[0]
faceAttributes= get_ifc_attributes(obj)
faceAttributes.update({'name':faceName})
# Inner wire(s).
holes= list()
for idx, wire in enumerate(vertices[1:]):
holeName= faceName+'_hole'+str(idx)
facesDict[holeName]= wire
holeAttributes= get_ifc_attributes(obj)
holeAttributes.update({'objType':'hole', 'ownerName':faceName})
holeProperties= bte.BlockProperties(labels= [objLabel], attributes= holeAttributes)
self.propertyDict[holeName]= holeProperties
holes.append(holeName)
if(len(holes)>0):
faceAttributes.update({'holeNames':holes})
properties= bte.BlockProperties(labels= [objLabel], attributes= faceAttributes)
self.propertyDict[faceName]= properties
def import_shape(shape, objName, objLabel):
''' Import simple shape.'''
shapeType= shape.ShapeType
if(shapeType=='Face'):
import_face(shape, objName, objLabel)
elif(shapeType=='Shell'):
for s in shape.SubShapes:
import_shape(s, objName, objLabel)
elif(shapeType=='Compound'):
for cCount, ss in enumerate(shape.SubShapes):
# ssType= ss.ShapeType
ssName= f'{objName}.{cCount}'
import_shape(ss, ssName, objLabel)
elif(shapeType=='Vertex'):
pass # Nothing to do with those here.
elif(shapeType in ['Wire']):
pass # Nothing to do with those.
else:
className= type(self).__name__
methodName= sys._getframe(0).f_code.co_name
lmsg.warning(className+'.'+methodName+'; entity with shape of type: '+shapeType+' ignored.')
for obj in self.groupsToImport:
if(hasattr(obj,'Shape')):
shapeType= obj.Shape.ShapeType
objName= obj.Name
objLabel= obj.Label
if(objLabel in self.facesTree):
facesDict= self.facesTree[objLabel]
import_shape(obj.Shape, objName, objLabel)
# Store compound components.
if(shapeType=='Compound'):
objTypeId= obj.TypeId
compoundContainer= None
if(objTypeId=='App::DocumentObjectGroup'): # Object group.
compoundContainer= obj.Group
compoundType= 'Group'
#draftType= getType(obj)
elif(objTypeId!='Part::FeaturePython'):
compoundContainer= obj.Links
compoundType= 'Compound'
if(compoundContainer):
for tag, lnk in enumerate(compoundContainer):
componentLabel= obj.Label+'.'+compoundType+'.'+str(tag)
if(componentLabel in self.compounds):
self.compounds[componentLabel].add({objLabel})
else:
self.compounds[componentLabel]= {objLabel}
# Define belongsTo attribute for compounds components.
for key in self.propertyDict:
pDict= self.propertyDict[key]
for label in pDict.labels:
if label in self.compounds:
compound= list(self.compounds[label])
if('belongsTo' in pDict.attributes):
pDict.attributes['belongsTo'].extend(compound)
else:
pDict.attributes['belongsTo']= compound
def getNamesToImport(self):
''' Return the names of the objects to import.'''
retval= list()
for obj in self.groupsToImport:
retval.append(obj.Label)
return retval