-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathimporterFreeCAD.py
4327 lines (3836 loc) · 172 KB
/
importerFreeCAD.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
# -*- coding: utf-8 -*-
__author__ = 'Jens M. Plonka'
__copyright__ = 'Copyright 2023, Germany'
__url__ = "https://www.github.com/jmplonka/InventorLoader"
'''
importerFreeCAD.py
'''
import FreeCAD, Draft, Part, Sketcher, traceback, Mesh, InventorViewProviders, Acis, re
from importerClasses import *
from importerUtils import *
from importerSegNode import SecNode, SecNodeRef, setParameter
from math import sqrt, tan, degrees, pi, asin
from FreeCAD import Vector as VEC, Rotation as ROT, Placement as PLC, ParamGet
from importerConstants import CENTER, DIR_X, DIR_Y, DIR_Z
BIT_GEO_ALIGN_HORIZONTAL = 1 << 0
BIT_GEO_ALIGN_VERTICAL = 1 << 1
BIT_GEO_BEND = 1 << 2
BIT_GEO_COINCIDENT = 1 << 3
BIT_GEO_EQUAL = 1 << 4
BIT_GEO_FIX = 1 << 5 # not supported
BIT_GEO_HORIZONTAL = 1 << 6
BIT_GEO_VERTICAL = 1 << 7
BIT_GEO_OFFSET = 1 << 8 # not supported
BIT_GEO_PARALLEL = 1 << 9
BIT_GEO_TANGENTIAL = 1 << 10
BIT_GEO_PERPENDICULAR = 1 << 11
BIT_GEO_POLYGON = 1 << 12
BIT_GEO_RADIUS = 1 << 13
BIT_GEO_SPLINEFITPOINT = 1 << 14 # not supported
BIT_GEO_SYMMETRY_LINE = 1 << 15
BIT_GEO_SYMMETRY_POINT = 1 << 16 # not supported
BIT_DIM_ANGLE_2_LINE = 1 << 17
BIT_DIM_ANGLE_3_POINT = 1 << 18 # Workaround required: 2 construction lines
BIT_DIM_RADIUS = 1 << 19
BIT_DIM_DIAMETER = 1 << 20 # Workaround required: radius constraint
BIT_DIM_DISTANCE = 1 << 21
BIT_DIM_OFFSET_SPLINE = 1 << 22 # not supported
# x 10 2 2 1 1 0 0 0
# x 1 4 0 6 2 8 4 0
#SKIP_CONSTRAINTS_DEFAULT = 0b11111111111111111111111
#SKIP_CONSTRAINTS_DEFAULT = 0b00000000000000000001000 # Only geometric coincidens
SKIP_CONSTRAINTS_DEFAULT = 0b00110000001111011011111 # default values: no workarounds, nor unsupported constraints!
SKIP_CONSTRAINTS = SKIP_CONSTRAINTS_DEFAULT # will be updated by stored preferences!
PART_LINE = Part.Line
if (hasattr(Part, "LineSegment")):
PART_LINE = Part.LineSegment
IMPLEMENTED_COMPONENTS = [
u"Sketch2D",
u"Sketch3D",
u"SketchBlock",
u"Feature",
u"MeshFolder",
u"iPart",
u"Blocks",
]
def __dumpProperties__(fxNode):
name = fxNode.name
properties = fxNode.get('properties')
text = []
for p in properties:
if p is None:
text.append(u"")
else:
t = p.node.getRefText()
i = t.index('): ')
t = t[i+3:]
try:
i = t.index('=')
text.append(t[i+1:])
except:
text.append(t)
dump = u"%s\t%s\n" %(name, u"\t".join(text))
# print(dump.encode("utf8"))
FreeCAD.Console.PrintMessage(dump)
def _enableConstraint(name, bit, preset):
global SKIP_CONSTRAINTS
SKIP_CONSTRAINTS &= ~bit # clear the bit if already set.
enable = ParamGet("User parameter:BaseApp/Preferences/Mod/InventorLoader").GetBool(name, preset)
if (enable):
SKIP_CONSTRAINTS |= bit # now set the bit if desired.
if (enable != preset):
ParamGet("User parameter:BaseApp/Preferences/Mod/InventorLoader").SetBool(name, enable)
return
def getCoord(point, coordName, scale = 10.0):
p = point
if (p is None): return 0.0
if (hasattr(p, 'get')): p = p.get(coordName)
if (p is None): return 0.0
return p * 10.0
def p2v(point, scale=10.0):
p = point
if (not isinstance(p, VEC)):
p = p.get('pos')
return p * scale
def createConstructionPoint(sketchObj, point):
part = Part.Point(p2v(point))
addSketch2D(sketchObj, part, True, point)
return point.sketchIndex
def createLine(p1, p2):
return PART_LINE(p1, p2)
def createCircle(c, n, r):
return Part.Circle(c, n, r)
def createArc(p1, p2, p3):
return Part.ArcOfCircle(p1, p2, p3)
def _initPreferences():
_enableConstraint('Sketch.Constraint.Geometric.AlignHorizontal', BIT_GEO_ALIGN_HORIZONTAL , True)
_enableConstraint('Sketch.Constraint.Geometric.AlignVertical', BIT_GEO_ALIGN_VERTICAL , True)
_enableConstraint('Sketch.Constraint.Geometric.Bend', BIT_GEO_BEND , True)
_enableConstraint('Sketch.Constraint.Geometric.Coincident', BIT_GEO_COINCIDENT , True)
_enableConstraint('Sketch.Constraint.Geometric.Equal', BIT_GEO_EQUAL , True)
_enableConstraint('Sketch.Constraint.Geometric.Fix', BIT_GEO_FIX , False)
_enableConstraint('Sketch.Constraint.Geometric.Horizontal', BIT_GEO_HORIZONTAL , True)
_enableConstraint('Sketch.Constraint.Geometric.Offset', BIT_GEO_OFFSET , False)
_enableConstraint('Sketch.Constraint.Geometric.Parallel', BIT_GEO_PARALLEL , True)
_enableConstraint('Sketch.Constraint.Geometric.Perpendicular', BIT_GEO_PERPENDICULAR , True)
_enableConstraint('Sketch.Constraint.Geometric.Polygon', BIT_GEO_POLYGON , True)
_enableConstraint('Sketch.Constraint.Geometric.Radius', BIT_GEO_RADIUS , True)
_enableConstraint('Sketch.Constraint.Geometric.SplineFitPoint', BIT_GEO_SPLINEFITPOINT , False)
_enableConstraint('Sketch.Constraint.Geometric.SymmetryLine', BIT_GEO_SYMMETRY_LINE , False)
_enableConstraint('Sketch.Constraint.Geometric.SymmetryPoint', BIT_GEO_SYMMETRY_POINT , False)
_enableConstraint('Sketch.Constraint.Geometric.Tangential', BIT_GEO_TANGENTIAL , True)
_enableConstraint('Sketch.Constraint.Geometric.Vertical', BIT_GEO_VERTICAL , True)
_enableConstraint('Sketch.Constraint.Dimension.Angle2Line', BIT_DIM_ANGLE_2_LINE , True)
_enableConstraint('Sketch.Constraint.Dimension.Angle3Point', BIT_DIM_ANGLE_3_POINT , False)
_enableConstraint('Sketch.Constraint.Dimension.Radius', BIT_DIM_RADIUS , True)
_enableConstraint('Sketch.Constraint.Dimension.Diameter', BIT_DIM_DIAMETER , True)
_enableConstraint('Sketch.Constraint.Dimension.Distance', BIT_DIM_DISTANCE , True)
_enableConstraint('Sketch.Constraint.Dimension.OffsetSpline', BIT_DIM_OFFSET_SPLINE , False)
def skipConstraint(bit):
global SKIP_CONSTRAINTS
return (SKIP_CONSTRAINTS & bit == 0)
def ignoreBranch(node):
return None
def unsupportedNode(node):
if (node.typeName == 'Feature'):
logWarning(u" ... %s '%s' not supported (yet?) - please use SAT or STEP instead!", node.typeName, node.getSubTypeName())
else:
logWarning(u" ... %s not supported (yet?) - please use SAT or STEP instead!", node.typeName)
node.setGeometry(None)
return None
def newObject(className, name, body = None):
doc = FreeCAD.ActiveDocument
view = FreeCADGui.ActiveDocument.ActiveView
activeBody = None
if hasattr(view,'getActiveObject'):
activeBody = view.getActiveObject('pdbody')
obj = doc.addObject(className, InventorViewProviders.getObjectName(name))
if (activeBody):
activeBody.addObject(obj)
if (obj):
obj.Label = name
if (body):
try:
body.addObject(obj)
except:
obj.adjustRelativeLinks(body)
body.ViewObject.dropObject(obj, None, name, [])
return obj
def createGroup(name):
return newObject('App::DocumentObjectGroup', name)
def isConstructionMode(node):
if (node):
flags2 = node.get('flags2')
if (flags2 is None):
logError(u"FATAL> (%04X): %s has no flags2 parameter!", node.index, node.typeName)
else:
if ((flags2 & 0x04080040) > 0): return True # 0x40 => This is a Reference!!!
return False
def isOrigo2D(vec2D):
return vec2D == (0,0)
def getDistancePointPoint(p, q):
return p2v(p).distanceToPoint(p2v(q))
def getDistanceLinePoint(line, point):
return p2v(point).distanceToLine(p2v(line.get('points')[0]), p2v(line.get('points')[1]))
def getDistanceCircleLine(circle, line):
point = circle.get('center')
distance = getDistanceLinePoint(line, point)
return distance - getCoord(circle, 'r')
def getDistanceCirclePoint(circle, point):
center = circle.get('center')
distance = getDistancePointPoint(center, point)
return distance - getCoord(circle, 'r')
def getDistanceCircleCircle(circle1, circle2):
center = circle2.get('center')
distance = getDistanceCirclePoint(circle1, center)
return distance - getCoord(circle2, 'r')
def getLengthPoints(entity1, entity2):
type1 = entity1.typeName
type2 = entity2.typeName
if (type1 == 'Point2D'):
if (type2 == 'Point2D'): return getDistancePointPoint(entity1, entity2)
if (type2 == 'Line2D'): return getDistanceLinePoint(entity2, entity1)
if (type2 == 'Circle2D'): return getDistanceCirclePoint(entity2, entity1)
if (type1 == 'Line2D'):
if (type2 == 'Point2D'): return getDistanceLinePoint(entity1, entity2)
if (type2 == 'Line2D'): return getDistanceLinePoint(entity1, entity2.get('points')[0]) # Hope that the lines are parallel!
if (type2 == 'Circle2D'): return getDistanceCircleLine(entity2, entity1)
if (type1 == 'Circle2D'):
if (type2 == 'Point2D'): return getDistanceCirclePoint(entity1, entity2)
if (type2 == 'Line2D'): return getDistanceCircleLine(entity1, entity2) # Hope that the lines are parallel!
if (type2 == 'Circle2D'): return getDistanceCircleCircle(entity1, entity2)
raise BaseException("Don't know how to determine the distance between '%s' and '%s'!" %(entity1.node.getRefText(), entity2.node.getRefText()))
def getLengthLine(line):
point1 = line.get('points')[0]
point2 = line.get('points')[1]
return getLengthPoints(point1, point2)
def isSamePoint(point1, point2):
if (point1 is None): return point2 is None
if (point2 is None): return False
return isEqual(p2v(point1), p2v(point2))
def getCoincidentPos(sketchObj, point, entity):
if (entity.sketchIndex is None): return -1
entityType = entity.typeName
if (entityType == 'Point2D'): return 1
if (isSamePoint(point, entity.get('points')[0])): return 1
if (isSamePoint(point, entity.get('points')[1])): return 2
if (isSamePoint(point, entity.get('center'))): return 3
pos = p2v(point)
if (sketchObj.isPointOnCurve(entity.sketchIndex, pos.x, pos.y)): return None
return -1
def addSketch2D(sketchObj, geometry, mode, entityNode):
index = sketchObj.addGeometry(geometry, mode)
newGeo = sketchObj.Geometry[index]
entityNode.setGeometry(newGeo, index)
if (hasattr(geometry, 'Construction')):
# till FC .. v0.18
geometry.Construction = mode
else:
# from FC 0.19 ..
sketchObj.setConstruction(index, mode)
return newGeo
def addSketch3D(sketchObj, geometry, mode, entityNode):
# geometry.Construction = mode
index = sketchObj.addGeometry(geometry, mode)
newGeo = sketchObj.Geometry[index]
entityNode.setGeometry(geometry, index)
return geometry
def addEqualRadius2d(sketchObj, arc1, arc2):
if (arc1 is not None):
constraint = Sketcher.Constraint('Equal', arc1, arc2)
sketchObj.addConstraint(constraint)
return
def getProperty(properties, index):
try:
return properties[index]
except:
return None
def getPropertyValue(properties, index, name):
property = getProperty(properties, index)
try:
return property.get(name)
except:
return None
def getDimension(node, varName):
dimension = node.get(varName)
if (dimension.typeName == 'Line2D'):
dimension = Length(getLengthLine(dimension))
elif (dimension.typeName == 'Point2D'):
dimension = Length(0)
elif (dimension.typeName != 'Parameter'):
logError(u"Expected Dimension for (%04X): %s - NOT %s", node.index, node.typeName, dimension.typeName)
return dimension
def getNextLineIndex(coincidens, startIndex):
i = startIndex
try:
ref = coincidens[i]
if (ref.typeName == 'Line2D'):
return i
return getNextLineIndex(coincidens, i + 1)
except:
return len(coincidens)
def getPlacement(node):
transformation = node.get('transformation')
matrix4x4 = transformation.getMatrix()
# convert centimeter to millimeter
matrix4x4.A14 *= 10.0
matrix4x4.A24 *= 10.0
matrix4x4.A34 *= 10.0
return PLC(matrix4x4)
def getFirstBodyName(ref):
try:
bodies = ref.get('items')
return bodies[0].name
except:
return ref.name
def getNominalValue(node):
if (node):
value = node.get('valueNominal')
if (value): return value
logWarning(u" ... Can't get nomininal value from (%04X): %s - assuming 0!", node.index, node.typeName)
return 0.0
def getDirection(node, dir, distance):
if (dir < 0): return -distance
if (dir == 0): return 0.0
return distance
def getCountDir(length, count, direction, fitted):
if (length is None): return 1, CENTER
if (count is None): return 1, CENTER
if (direction is None): return 1, CENTER
if (direction.typeName in ['DirectionPath']):
logWarning(u" ... Pattern along path (%04X): %s not (yet) supported - ignoring pattern", direction.index, direction.typeName)
return 1, CENTER
if (direction.typeName not in ['DirectionAxis', 'DirectionEdge', 'DirectionFace']):
logError(u" ... Don't know how to get direction from (%04X): %s - ignoring pattern", direction.index, direction.typeName)
return 1, CENTER
node = direction.node # Should be DirectionNode
dst = getMM(length) # distance
cnt = getNominalValue(count) # count
dir = node.getDirection()
if (dir):
if (isTrue(fitted) and (cnt > 1)):
return cnt, dir.normalize() * dst / (cnt - 1)
return cnt, dir.normalize() * dst
return 1, CENTER
def setDefaultViewObjectValues(geo):
if (geo is None): return
geo.ViewObject.AngularDeflection = 28.5 # double
geo.ViewObject.BoundingBox = False # bool
geo.ViewObject.Deviation = 0.5 # double
geo.ViewObject.DisplayMode = 0 # enum {0: u"Flat Lines", 1: u"Shaded", 2: u"Wireframe", 3: u"Points"}
geo.ViewObject.DrawStyle = 0 # enum {0: u"Solid", 1: u"Dahed", 2: u"Dotted", 3: u"Dashdot"}
geo.ViewObject.Lighting = 1 # enum {0: u"One side", 1: u"Two side"}
geo.ViewObject.LineColor = (0.1, 0.1, 0.1, 0.0) # double[4]
geo.ViewObject.LineWidth = 1.0 # double
geo.ViewObject.PointColor = (0.1, 0.1, 0.1, 0.0) # double[4]
geo.ViewObject.PointSize = 2.0 # double
geo.ViewObject.Selectable = True # bool
geo.ViewObject.SelectionStyle = 0 # enum {0: u"Shape", 1: u"BoundBox"}
geo.ViewObject.ShapeColor = (0.75, 0.75, 0.75, 0.0) # double[4]
geo.ViewObject.Transparency = 0 # int 0..100
geo.ViewObject.Visibility = True # bool
def adjustViewObject(newGeo, baseGeo):
if (newGeo is None): return
if (baseGeo is None): return
newGeo.ViewObject.DisplayMode = baseGeo.ViewObject.DisplayMode
newGeo.ViewObject.DrawStyle = baseGeo.ViewObject.DrawStyle
newGeo.ViewObject.Lighting = baseGeo.ViewObject.Lighting
newGeo.ViewObject.LineColor = baseGeo.ViewObject.LineColor
newGeo.ViewObject.LineWidth = baseGeo.ViewObject.LineWidth
newGeo.ViewObject.PointColor = baseGeo.ViewObject.PointColor
newGeo.ViewObject.PointSize = baseGeo.ViewObject.PointSize
newGeo.ViewObject.ShapeColor = baseGeo.ViewObject.ShapeColor
newGeo.ViewObject.Transparency = baseGeo.ViewObject.Transparency
def getBOOL(parameter):
if (parameter is None): return False
if (type(parameter) == bool): return parameter
boolean = parameter.get('value')
if (type(boolean) == bool): return boolean
return boolean
def getMM(parameter):
if (parameter is None): return 0.0
if (type(parameter) == float): return parameter
if (isinstance(parameter, AbstractValue)):
mm = parameter
else:
mm = parameter.getValue()
if (isinstance(mm, Length)): return mm.getMM()
if (isinstance(mm, Scalar)): return mm.x * 10
return mm * 10.0
def getGRAD(parameter):
if (parameter is None): return 0.0
if (type(parameter) == float): return parameter
if (isinstance(parameter, AbstractValue)):
angle = parameter
else:
angle = parameter.getValue()
if (isinstance(angle, Angle)): return angle.getGRAD()
if (isinstance(angle, Scalar)): return angle.x
return angle
def getRAD(parameter):
if (parameter is None): return 0.0
if (type(parameter) == float): return parameter
if (isinstance(parameter, AbstractValue)):
angle = parameter
else:
angle = parameter.getValue()
if (isinstance(angle, Angle)): return angle.getRAD()
if (isinstance(angle, Scalar)): return angle.x
return angle
def isTrue(param):
if (param is None): return False
return param.get('value')
def setPlacement(geo, placement, base):
geo.Placement = placement
if (base is not None): geo.Placement.Base = base
return
def replaceGeometry(sketchObj, node, geo):
node.data.geometry = geo
sketchObj.Geometry[node.sketchIndex] = geo
return geo
def replacePoint(sketchObj, pOld, line, pNew):
l = line.geometry
if (l is None): return None
if (isEqual(p2v(pOld), l.StartPoint)):
return replaceGeometry(sketchObj, line, createLine(p2v(pNew), l.EndPoint))
return replaceGeometry(sketchObj, line, createLine(l.StartPoint, p2v(pNew)))
def setAssociatedSketchEntity(sketchNode, node, ai, entityType):
if (not ai in sketchNode.data.associativeIDs):
idMap = {}
sketchNode.data.associativeIDs[ai] = idMap
idMap = sketchNode.data.associativeIDs[ai]
idMap[entityType] = node
def getAssociatedSketchEntity(sketchNode, ai, entityType):
if (not ai in sketchNode.data.associativeIDs):
return None
idMap = sketchNode.data.associativeIDs[ai]
return idMap.get(entityType, None)
def getNodeColor(node):
attributes = node.get('attrs')
for attribute in attributes.get('attributes'):
if (attribute.typeName in ['AttrPartDraw', 'Attr_Colors']):
return attribute.get('Color.diffuse')
return None
def getBodyColor(body):
color = getNodeColor(body)
if (not color is None): return color
part = body.get('parent')
color = getNodeColor(part)
if (not color is None): return color
group = part._data.parent
return getNodeColor(group)
def getFaceColor(face):
styles = face.get('styles')
if (styles):
for style in styles.get('styles'):
if (style.typeName in ['Style_PrimColorAttr', 'Style_LineColor']):
return style.get('Color.diffuse')
return None
def getFaceIndex(face, shape):
faceIndex = 0
for f in shape.Faces:
b1 = f.BoundBox
b2 = face.get('box')
if isEqual1D(b1.XMin, b2[0] * 10.0, 0.1):
if isEqual1D(b1.YMin, b2[1] * 10.0, 0.1):
if isEqual1D(b1.ZMin, b2[2] * 10.0, 0.1):
if isEqual1D(b1.XMax, b2[3] * 10.0, 0.1):
if isEqual1D(b1.YMax, b2[4] * 10.0, 0.1):
if isEqual1D(b1.ZMax, b2[5] * 10.0, 0.1):
return faceIndex
faceIndex = faceIndex + 1
return -1
def adjustBodyColor(entity, body):
if (body):
color = getBodyColor(body)
if (color):
if not (type(entity) is list):
#entity.ViewObject.ShapeColor = color.getRGB()
shell = body.get('shell')
shellColor = getFaceColor(shell)
if (shellColor):
color = shellColor
colors = [color.getRGB()] * len(entity.Shape.Faces)
# entity must have same number of faces as shell!!!
for face in shell.get('objects'):
faceColor = getFaceColor(face)
if (faceColor):
faceIndex = getFaceIndex(face, entity.Shape)
if (faceIndex < 0):
logInfo(u" Can't find index for face %r", face)
else:
colors[faceIndex] = faceColor.getRGB()
entity.ViewObject.DiffuseColor = colors
entity.ViewObject.Transparency = 100 - int(color.alpha * 100)
def adjustFxColor(entity, nodColor):
if (entity is not None):
if (nodColor is not None):
color = getColor(nodColor.name)
if (color is not None):
if (type(entity) is list):
for child in entity:
child.ViewObject.ShapeColor = color
else:
entity.ViewObject.ShapeColor = color
return
def __hide__(geo):
if (geo):
geo.ViewObject.Visibility = False
return
def hide(geos):
if (type(geos) == list):
for geo in geos:
__hide__(geo)
else:
__hide__(geos)
return
def resolveNameTableItem(item, vk):
if (hasattr(vk, 'entry') and (vk.entry is None)):
nt = item.segment.elementNodes.get(vk.nameTable)
if (nt is not None):
vk.entry = nt.get('entries')[vk.key]
return vk.entry
return None
def getNameTableEntry(node):
ntEntry = node.get('ntEntry')
if (ntEntry.entry is None):
entry = resolveNameTableItem(node, ntEntry)
resolveNameTableItem(node, entry.get('from'))
resolveNameTableItem(node, entry.get('to'))
resolveNameTableItem(node, entry.get('edge'))
lst2 = entry.get('lst2')
for i, vk in enumerate(lst2):
resolveNameTableItem(node, vk)
return ntEntry.entry
def checkPoints(fcEdge, acisPoints):
pt1 = fcEdge.firstVertex().Point
pt2 = fcEdge.lastVertex().Point
for pt in acisPoints:
if (not isEqual(pt, pt1)) and (not isEqual(pt, pt2)):
return False
return True
def checkCircles(fcCurve, acisCurve):
if (not isEqual1D(fcCurve.Radius, acisCurve.major.Length)): return False
if (not (isEqual(fcCurve.Axis, acisCurve.axis) or isEqual(fcCurve.Axis, acisCurve.axis.negative()))): return False
if (not isEqual(fcCurve.Center, acisCurve.center)): return False
return True
def checkEllipses(fcCurve, acisCurve):
if (not isEqual1D(fcCurve.MajorRadius, acisCurve.major.Length)): return False
if (not isEqual1D(fcCurve.MinorRadius, acisCurve.major.Length * acisCurve.ratio)): return False
if (not (isEqual(fcCurve.Axis, acisCurve.axis) or isEqual(fcCurve.Axis, acisCurve.axis.negative()))): return False
if (not isEqual(fcCurve.Center, acisCurve.center)): return False
return True
def checkBSplines(fcCurve, acisCurve):
logWarning("Don't know how to compare BSpline-curves!")
return False
def checkProjectedCurves(fcCurve, acisCurve):
logWarning("Don't know how to compare projected curves!")
return False
def checkComposedCurves(fcCurve, acisCurve):
logWarning("Don't know how to compare composed curves!")
return False
def checkDegenerateCurves(fcCurve, acisCurve):
return False
def isEqualCurve(fcEdge, acisEdge):
c = fcEdge.Curve
acisPoints = acisEdge.getPoints()
if (not checkPoints(fcEdge, acisPoints)): return False
acisCurve = acisEdge.getCurve()
cn = c.__class__.__name__
if (isinstance(acisCurve, Acis.CurveStraight)):
return (cn in ['Line', 'LineSegment'])
if (isinstance(acisCurve, Acis.CurveEllipse)):
if (isEqual1D(acisCurve.ratio, 1)):
if (cn in ['Circle', 'ArcOfCircle', 'Arc']):
return (checkCircles(c, acisCurve))
else:
if (cn in ['Ellipse', 'ArcOfEllipse', 'ArcOfConic']):
return (checkEllipses(c, acisCurve))
elif (isinstance(acisCurve, Acis.CurveInt)):
if (cn in ['BSplineCurve']):
return (checkBSplines(c, acisCurve))
elif (isinstance(acisCurve, Acis.CurveP)):
if (cn in []):
return (checkProjectedCurves(c, acisCurve))
elif (isinstance(acisCurve, Acis.CurveComp)):
if (cn in []):
return (checkComposedCurves(c, acisCurve))
elif (isinstance(acisCurve, Acis.CurveDegenerate)):
if (cn in []):
return (checkDegenerateCurves(c, acisCurve))
return False
def checkFaceCurves(fcFace, acisFace):
fcEdges = fcFace.Edges
acisEdges = acisFace.getEdges()
for fcEdge in fcEdges:
found = False
if (not fcEdge.Degenerated):
for acisEdge in acisEdges:
if (isEqualCurve(fcEdge, acisEdge)):
found = True
break;
if (found == False):
return False
return True
def checkPlane(fcFace, acisFace):
s1 = fcFace.Surface
s2 = acisFace.getSurface()
if (not (isEqual(s1.Axis, s2.normal) or isEqual(s1.Axis, s2.normal))): return False # axis are not pointing in the same/opposite direction
if (not isEqual1D(s2.root.distanceToPlane(s1.Position, s1.Axis), 0.0)): return False
return checkFaceCurves(fcFace, acisFace)
def checkCylinder(fcFace, acisFace):
# axis and radius
s1 = fcFace.Surface
s2 = acisFace.getSurface()
if (not isEqual1D(s2.sine, 0.0)): return False # acisFace is a cone!
if (not isEqual1D(s1.Radius, s2.major.Length)): return False
if (not (isEqual(s1.Axis, s2.axis) or isEqual(s1.Axis, s2.axis))): return False # axis are not pointing in the same/opposite direction
if (not isEqual1D(s2.center.distanceToLine(s1.center, s1.Axis), 0.0)): return False
return checkFaceCurves(fcFace, acisFace)
def checkCone(fcFace, acisFace):
# axis, apex and angle
s1 = fcFace.Surface
s2 = acisFace.getSurface()
if (not (isEqual(s1.Axis, s2.axis) or isEqual(s1.Axis, s2.axis))): return False # axis are not pointing in the same/opposite direction
if (not isEqual(s1.Apex, s2.apex)): return False
if (not isEqual1D(s1.SemiAngle, asin(s2.sine))): return False
return checkFaceCurves(fcFace, acisFace)
def checkSpere(fcFace, acisFace):
# center and radius
s1 = fcFace.Surface
s2 = acisFace.getSurface()
if (not isEqual1D(s1.Radius, s2.radius)): return False
if (not isEqual(s1.Center, s2.center)): return False
return checkFaceCurves(fcFace, acisFace)
def checkToroid(fcFace, acisFace):
# axis, center, major- and minor-radius
s1 = fcFace.Surface
s2 = acisFace.getSurface()
if (not (isEqual(s1.Axis, s2.axis) or isEqual(s1.Axis, s2.axis))): return False # axis are not pointing in the same/opposite direction
if (not isEqual(s1.Center, s2.center)): return False
if (not isEqual1D(s1.MajorRadius, s2.major)): return False
if (not isEqual1D(s1.MinorRadius, s2.minor)): return False
return checkFaceCurves(fcFace, acisFace)
def checkBSplineSurface(fcFace, acisFace):
s1 = fcFace.Surface
s2 = acisFace.getSurface()
return checkFaceCurves(fcFace, acisFace)
def isEqualFace(fcFace, acisFace):
cn = fcFace.Surface.__class__.__name__
if (acisFace.isCone()):
if (cn == 'Cylinder'):
return checkCylinder(fcFace, acisFace)
if (cn == 'Cone'):
return checkCone(fcFace, acisFace)
elif (acisFace.isMesh()):
logWarning("Don't know how to compare Mesh-Surfaces!")
return False
elif (acisFace.isPlane()):
if (cn in ['Plane']):
return checkPlane(fcFace, acisFace)
elif (acisFace.isSphere()):
if (cn in ['Sphere']):
return checkSpere(fcFace, acisFace)
elif (acisFace.isSpline()):
if (cn in ['BSplineSurface']):
return checkBSplineSurface(fcFace, acisFace)
elif (acisFace.isTorus()):
if (cn in ['Toroid']):
return checkToroid(fcFace, acisFace)
return False
def findFcEdgeIndex(fcShape, acisEdges):
for idx, fcEdge in enumerate(fcShape.Edges):
if (not fcEdge.Degenerated):
for acisEdge in acisEdges:
if (isEqualCurve(fcEdge, acisEdge)):
return idx
return None
def findFcFaceIndex(fcShape, acisFaces):
for idx, fcFace in enumerate(fcShape.Faces):
for acisFace in acisFaces:
if (isEqualFace(fcFace, acisFace)):
return idx
return None
def getFxAttribute(node, typeNames):
attr = node.get('next')
while (attr):
if (attr.typeName in typeNames):
return attr
attr = attr.get('next')
return None
def _DBG_checkFeatureAttributes(attr):
if (attr):
if (not hasattr(attr.data, 'isAttr')):
logError(" NOT AN ATTRIBUTE: %r", attr)
else:
props = attr.data.properties
if not('next' in props):
logError(" NO NEXT ATTRIBUTE: %r", attr)
else:
_DBG_checkFeatureAttributes(props['next'][0])
return
def _DBG_checkBrowserSegment(browser):
mgr = browser.tree.getFirstChild('EntryManager')
if (mgr is not None):
entries = mgr.get('entries')
for e in entries:
o = entries[e]
if not hasattr(o.data, 'Entry'):
FreeCAD.Console.PrintError(" NO ENTRY: %r\n" %(o.typeName))
def _DBG_checkDcSegment(dc):
doc = dc.tree.getFirstChild('Document')
if (doc):
component = doc.get('component')
for o in component.get('objects'):
if not hasattr(o.data, 'Item'):
FreeCAD.Console.PrintError(u" NO ITEM: '%s'\n" %(o.typeName))
def _DBG_checkSegments():
_DBG_checkBrowserSegment(getModel().getBrowser())
_DBG_checkDcSegment(getModel().getDC())
class FreeCADImporter(object):
FX_EXTRUDE_NEW = 0x0001
FX_EXTRUDE_CUT = 0x0002
FX_EXTRUDE_JOIN = 0x0003
FX_EXTRUDE_INTERSECTION = 0x0004
FX_EXTRUDE_SURFACE = 0x0005
FX_HOLE_DRILLED = 0x0000
FX_HOLE_SINK = 0x0001
FX_HOLE_BORED = 0x0002
FX_HOLE_SPOT = 0x0003
FX_HOLE_TYPE = {FX_HOLE_DRILLED: u'None', FX_HOLE_SINK: 'Countersink', FX_HOLE_BORED: u'Counterbore', FX_HOLE_SPOT: u'Counterbore'}
def __init__(self):
self.root = None
self.mapConstraints = None
self.pointDataDict = None
self.bodyNodes = {}
#_initPreferences()
# override user selected Constraints!
SKIP_CONSTRAINTS = SKIP_CONSTRAINTS_DEFAULT
def getGeometry(self, node):
if (node):
try:
if (not isinstance(node, DataNode)): node = node.node
if (node.handled == False):
node.handled = True
if (node.valid):
importObject = getattr(self, 'Create_%s' %(node.typeName))
importObject(node)
except Exception as e:
logError(u"Error in creating (%04X): %s - %s", node.index, node.typeName, e)
logError(traceback.format_exc())
node.valid = False
return node.geometry
return None
def addConstraint(self, sketchObj, constraint, key):
index = sketchObj.addConstraint(constraint)
self.mapConstraints[key] = constraint
return index
def addSolidBody(self, fxNode, obj3D, solid):
fxNode.setGeometry(obj3D)
if (solid is not None):
bodies = solid.get('items')
body = bodies[0]
body.setGeometry(obj3D)
# overwrite previously added solids with the same name!
self.bodyNodes[body.name] = fxNode
self.lastActiveBody = fxNode
return
def addSurfaceBody(self, fxNode, obj3D, surface):
fxNode.setGeometry(obj3D)
if (surface is not None):
surface.setGeometry(obj3D)
# overwrite previously added sourfaces with the same name!
self.bodyNodes[surface.name] = fxNode
return
def getBodyNode(self, ref):
if (ref.typeName == 'ObjectCollection'):
bodies = ref.get('items')
try:
body = bodies[0]
except:
body = None
else:
body = ref
try:
return self.bodyNodes[body.name]
except:
return None
def addBody(self, fxNode, body, solidIdx, surfaceIdx):
properties = fxNode.get('properties')
solid = getProperty(properties, solidIdx)
if (solid is not None):
self.addSolidBody(fxNode, body, solid)
else:
sourface = getProperty(properties, surfaceIdx)
self.addSurfaceBody(fxNode, body, sourface)
return
def findBase(self, base):
baseGeo = None
if (base is not None):
name = getFirstBodyName(base)
if (name in self.bodyNodes):
baseGeo = self.getGeometry(self.bodyNodes[name])
if (baseGeo is None):
logWarning(u" Base2 = '%s' -> (%04X): %s can't be created!", name, base.index, base.typeName)
else:
logInfo(u" ... Base2 = '%s'", name)
else:
logWarning(u" Base2 (%04X): %s '%s' not created!", base.index, base.getSubTypeName(), base.name)
else:
logWarning(u" Base2: ref is None!")
return baseGeo
def findSurface(self, node):
try:
return self.getGeometry(self.bodyNodes[node.name])
except:
return None
def findGeometries(self, node):
geometries = []
if (node is not None):
assert (node.typeName == 'ObjectCollectionDef'), 'FATA> (%04X): %s expected ObjectCollectionDef' %(node.index, node.typeName)
edges = node.get('items')
if (edges is not None):
for edge in edges:
name = getFirstBodyName(edge)
if (name in self.bodyNodes):
# ensure that the sketch is already created!
toolGeo = self.getGeometry(self.bodyNodes[name])
if (toolGeo is None):
logWarning(u" Tool = '%s' -> (%04X): %s can't be created", name, node.index, node.typeName)
else:
geometries.append(toolGeo)
logInfo(u" ... Tool = '%s'", name)
else:
logWarning(u"WARNING> Can't find body for '%s'!", name)
else:
logError(u"ERROR> (%04X): %s -> 'items' not found!", node.index, node.typeName)
else:
logWarning(u" Tool: ref is None!")
return geometries
def addDimensionConstraint(self, sketchObj, dimension, constraint, key, useExpression = True):
number = sketchObj.ConstraintCount
index = self.addConstraint(sketchObj, constraint, key)
name = dimension.name
if (name):
constraint.Name = str(name)
sketchObj.renameConstraint(index, name)
if (useExpression):
expression = dimension.get('alias')
sketchObj.setExpression('Constraints[%d]' %(number), expression)
else:
constraint.Name = 'Constraint%d' %(index)
return index
def adjustIndexPos(self, data, index, pos, point):
if ((data.typeName == 'Circle2D') or (data.typeName == 'Ellipse2D')):
pos = point.get('pos')
points = data.get('points')
for ref in points:
if (ref):
if (isEqual(ref.get('pos'), pos) and (ref.sketchIndex != -1)):
if (ref.sketchIndex is not None):
index = ref.sketchIndex
pos = ref.sketchPos
return index, pos
def addCoincidentEntity(self, sketchObj, point, entity, pos):
if (entity.typeName != 'Point2D'):
p = point.get('pos') * 10.0
vec2D = (p.x, p.y)
if (vec2D not in self.pointDataDict):
self.pointDataDict[vec2D] = []
coincidens = self.pointDataDict[vec2D]
for t in coincidens:
if (entity.index == t[0].index): return # already added -> done!
if (pos < 0):
pos = getCoincidentPos(sketchObj, point, entity)
if (pos != -1):
coincidens.append([entity, entity.sketchIndex, pos])
return
def addCoincidentConstraint(self, fix, move, sketchObj):
constraint = None
if (move is not None):
if (move[1] is not None):
typ1 = 'Point'
if (isinstance(fix[0], SecNodeRef)): typ1 = fix[0].typeName[0:-2]
if (move[2] is None):
logInfo(u" ... added point on object constraint between %s %s/%s and %s %s", typ1, fix[1], fix[2], move[0].typeName[0:-2], move[1])
constraint = Sketcher.Constraint('PointOnObject', fix[1], fix[2], move[1])
else:
logInfo(u" ... added coincident constraint between %s %s/%s and %s %s/%s", typ1, fix[1], fix[2], move[0].typeName[0:-2], move[1], move[2])
constraint = Sketcher.Constraint('Coincident', fix[1], fix[2], move[1], move[2])
return constraint
def getSketchEntityInfo(self, sketchObj, entity):
try:
if (entity.typeName == 'Point2D'):
entities = entity.get('entities')
return entities[0].sketchIndex
except:
return entity.sketchIndex
def findEntityPos(self, sketchObj, entity):
if (entity.typeName == 'Point2D'):
pos = entity.get('pos') * 10.0
vec2D = (pos.x, pos.y)
if (isOrigo2D(vec2D)): return (-1, 1)
if (vec2D in self.pointDataDict):
coincidens = self.pointDataDict[vec2D]
if (len(coincidens) > 0):
return (coincidens[0][1], coincidens[0][2])
return (createConstructionPoint(sketchObj, entity), 1)
return (entity.sketchIndex, None)