-
Notifications
You must be signed in to change notification settings - Fork 70
/
a2plib.py
1221 lines (1110 loc) · 50.2 KB
/
a2plib.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 -*-
#***************************************************************************
#* *
#* Copyright (c) 2018 kbwbe *
#* *
#* Portions of code based on hamish's assembly 2 *
#* *
#* 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 *
#* *
#***************************************************************************
import os
import sys
import FreeCAD
import FreeCADGui
from FreeCAD import Base
import Part
from PySide import QtGui
from PySide import QtCore
import copy
import platform
import numpy
from pivy import coin
translate = FreeCAD.Qt.translate
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
USE_PROJECTFILE = preferences.GetBool('useProjectFolder', False)
PARTIAL_PROCESSING_ENABLED = preferences.GetBool('usePartialSolver', True)
AUTOSOLVE_ENABLED = preferences.GetBool('autoSolve', True)
RELATIVE_PATHES_ENABLED = preferences.GetBool('useRelativePathes',True)
FORCE_FIXED_POSITION = preferences.GetBool('forceFixedPosition',True)
SHOW_CONSTRAINTS_ON_TOOLBAR= preferences.GetBool('showConstraintsOnToolbar',True)
RECURSIVE_UPDATE_ENABLED = preferences.GetBool('enableRecursiveUpdate',False)
USE_SOLID_UNION = preferences.GetBool('useSolidUnion',True)
SHOW_WARNING_FLOATING_PARTS = True
# if SIMULATION_STATE == True assemblies are solved with less accuracy
SIMULATION_STATE = False
SAVED_TRANSPARENCY = []
path_a2p = os.path.dirname(__file__)
path_a2p_resources = os.path.join( path_a2p, 'GuiA2p', 'Resources', 'resources.rcc')
resourcesLoaded = QtCore.QResource.registerResource(path_a2p_resources)
assert resourcesLoaded
wb_globals = {}
RED = (1.0,0.0,0.0)
GREEN = (0.0,1.0,0.0)
BLUE = (0.0,0.0,1.0)
YELLOW = (1.0,1.0,0.0)
WHITE = (1.0,1.0,1.0)
BLACK = (0.0,0.0,0.0)
# DEFINE DEBUG LEVELS FOR CONSOLE OUTPUT
A2P_DEBUG_NONE = 0
A2P_DEBUG_1 = 1
A2P_DEBUG_2 = 2
A2P_DEBUG_3 = 3
#===================================================
# do debug settings here:
#===================================================
A2P_DEBUG_LEVEL = A2P_DEBUG_NONE #normal: A2P_DEBUG_NONE
GRAPHICALDEBUG = False #normal: False
# for debug purposes
# 0:normal
# 1:one step in each worklist
# 2:one step in first worklist
SOLVER_ONESTEP = 0 #normal: 0
#===================================================
solver_debug_objects = [] #collect solver 3d output for later removal
#===================================================
PARTIAL_SOLVE_STAGE1 = 1 #solve all rigid fully constrained to tempfixed rigid, enable only involved dep, then set them as tempfixed
CONSTRAINT_DIALOG_REF = None
CONSTRAINT_EDITOR__REF = None
CONSTRAINT_VIEWMODE = False
# This Icon map is necessary to show correct icons within very old assemblies
A2P_CONSTRAINTS_ICON_MAP = {
# constraintType: iconPath
'pointIdentity': ':/icons/a2p_PointIdentity.svg',
'pointOnLine': ':/icons/a2p_PointOnLineConstraint.svg',
'pointOnPlane': ':/icons/a2p_PointOnPlaneConstraint.svg',
'circularEdge': ':/icons/a2p_CircularEdgeConstraint.svg',
'axial': ':/icons/a2p_AxialConstraint.svg',
'axisParallel': ':/icons/a2p_AxisParallelConstraint.svg',
'axisPlaneParallel': ':/icons/a2p_AxisPlaneParallelConstraint.svg',
'axisPlaneNormal': ':/icons/a2p_AxisPlaneNormalConstraint.svg',
'axisPlaneAngle': ':/icons/a2p_AxisPlaneAngleConstraint.svg',
'planesParallel': ':/icons/a2p_PlanesParallelConstraint.svg',
'plane': ':/icons/a2p_PlaneCoincidentConstraint.svg',
'angledPlanes': ':/icons/a2p_AngleConstraint.svg',
'sphereCenterIdent': ':/icons/a2p_SphericalSurfaceConstraint.svg',
'CenterOfMass': ':/icons/a2p_CenterOfMassConstraint.svg'
}
#------------------------------------------------------------------------------
# Detect the operating system...
#------------------------------------------------------------------------------
tmp = platform.system()
tmp = tmp.upper()
tmp = tmp.split(' ')
OPERATING_SYSTEM = 'UNKNOWN'
if "WINDOWS" in tmp:
OPERATING_SYSTEM = "WINDOWS"
elif "LINUX" in tmp:
OPERATING_SYSTEM = "LINUX"
else:
OPERATING_SYSTEM = "OTHER"
#------------------------------------------------------------------------------
def get_module_path():
"""
Function return A2p module path. It tested in FreeCAD 0.19 and 0.21 in Linux 64-bit:
Not work in both FreeCAd versions (return different end of string in different FreeCAD versions):
print("os.path.dirname(): " + os.path.dirname(__file__))
Work in both FreeCAd versions:
print("os.path.abspath(): " + os.path.abspath(__file__))
print("os.path.dirname(os.path.abspath(__file__)): " + os.path.dirname(os.path.abspath(__file__)))
# FreeCAD 0.19:
# os.path.dirname(): /home/user/.FreeCAD/Mod/A2plus
# os.path.abspath(): /home/user/.FreeCAD/Mod/A2plus/a2plib.py
# os.path.dirname(os.path.abspath(__file__)): /home/user/.FreeCAD/Mod/A2plus
# FreeCAD 0.21:
# os.path.dirname(): /home/user/.local/share/FreeCAD/Mod/A2plus/.
# os.path.abspath(): /home/user/.local/share/FreeCAD/Mod/A2plus/a2plib.py
# os.path.dirname(os.path.abspath(__file__)): /home/user/.local/share/FreeCAD/Mod/A2plus
"""
s_path = os.path.dirname(os.path.abspath(__file__))
return s_path
#------------------------------------------------------------------------------
def getLanguagePath():
"""
Function return path for localization files. It tested in FreeCAD 0.19 and 0.21 in Linux 64-bit:
Work in both FreeCAd versions:
print("os.path.join(get_module_path(), 'translations'): " + os.path.join(get_module_path(), "translations"))
# FreeCAD 0.19:
# os.path.join(get_module_path(), 'translations'): /home/user/.FreeCAD/Mod/A2plus/translations
# FreeCAD 0.21:
# os.path.join(get_module_path(), 'translations'): /home/user/.local/share/FreeCAD/Mod/A2plus/translations
"""
s_path = os.path.join(get_module_path(), "translations")
return s_path
#------------------------------------------------------------------------------
def getA2pVersion():
"""
Function return A2Plus version for storing in assembly file
"""
A2plus_path = get_module_path()
try:
metadata = FreeCAD.Metadata(os.path.join(A2plus_path, 'package.xml'))
return metadata.Version
except: # Older FreeCAD versions do not support FreeCAD.Metadata, do a workaround
tx = ' ?? '
f = open(os.path.join(A2plus_path, 'package.xml'),'r')
lines = f.readlines()
for line in lines:
strippedLine = line.strip(' ').strip('\n').strip('\r')
if strippedLine.startswith('<version>'):
tx = strippedLine.lstrip('<version>').rstrip('</version>')
return tx
#------------------------------------------------------------------------------
def drawDebugVectorAt(position,direction,rgbColor):
"""
Function draws a vector directly to 3D view using pivy/Coin.
expects position and direction as Base.vector type
color as tuple like (1,0,0)
"""
color = coin.SoBaseColor()
color.rgb = rgbColor
# Line style.
lineStyle = coin.SoDrawStyle()
lineStyle.style = coin.SoDrawStyle.LINES
lineStyle.lineWidth = 2
points = coin.SoCoordinate3()
lines = coin.SoLineSet()
startPoint = position.x,position.y,position.z
ep = position.add(direction)
endPoint = ep.x,ep.y,ep.z
points.point.values = (startPoint,endPoint)
#create and feed data to separator
sep=coin.SoSeparator()
sep.addChild(points)
sep.addChild(color)
sep.addChild(lineStyle)
sep.addChild(lines)
#add separator to sceneGraph
sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
sg.addChild(sep)
solver_debug_objects.append(sep)
#------------------------------------------------------------------------------
def isGlobalVisible(ob):
"""
Part containers do not propagate visibility to all its childs.
This function checks, whether at least one Part container is invisible in tree
upwards direction.
This function returns always true, except one Part- or Group-Container
in tree-structure above is invisible
"""
result = True
#remove constraints from the InList
inList = []
for i in ob.InList:
if isA2pConstraint(i): continue
inList.append(i)
if len(inList) == 0:
if (
ob.Name.startswith('Group') or
ob.Name.startswith('Part')
):
return ob.ViewObject.Visibility # break the recursion
elif len(inList) == 1:
if (
inList[0].Name.startswith('Group') or
inList[0].Name.startswith('Part')
):
if inList[0].ViewObject.Visibility == False:
return False # break instantly
# do search in tree upwards
result = isGlobalVisible(inList[0])
return result
#------------------------------------------------------------------------------
def to_bytes(tx):
if isinstance(tx, str):
value = tx.encode("utf-8")
else:
value = tx
return value # Instance of bytes
#------------------------------------------------------------------------------
def to_str(tx):
if isinstance(tx, bytes):
value = tx.decode("utf-8")
else:
value = tx
return value # Instance of unicode string
#------------------------------------------------------------------------------
def setSimulationState(boolVal):
global SIMULATION_STATE
SIMULATION_STATE = boolVal
#------------------------------------------------------------------------------
def doNotImportInvisibleShapes():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('doNotImportInvisibleShapes',True)
#------------------------------------------------------------------------------
def getPerFaceTransparency():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('usePerFaceTransparency',False)
#------------------------------------------------------------------------------
def getNativeFileManagerUsage():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('useNativeFileManager',False)
#------------------------------------------------------------------------------
def getRecalculateImportedParts():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('recalculateImportedParts',False)
#------------------------------------------------------------------------------
def getRecursiveUpdateEnabled():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('enableRecursiveUpdate',False)
#------------------------------------------------------------------------------
def getForceFixedPosition():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('forceFixedPosition',False)
#------------------------------------------------------------------------------
def getUseSolidUnion():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('useSolidUnion',False)
#------------------------------------------------------------------------------
def getConstraintEditorRef():
global CONSTRAINT_EDITOR__REF
return CONSTRAINT_EDITOR__REF
#------------------------------------------------------------------------------
def setConstraintEditorRef(ref):
global CONSTRAINT_EDITOR__REF
CONSTRAINT_EDITOR__REF = ref
#------------------------------------------------------------------------------
def setConstraintViewMode(active):
global CONSTRAINT_VIEWMODE
CONSTRAINT_VIEWMODE = active
#------------------------------------------------------------------------------
def getConstraintViewMode():
global CONSTRAINT_VIEWMODE
return CONSTRAINT_VIEWMODE
#------------------------------------------------------------------------------
def getConstraintDialogRef():
global CONSTRAINT_DIALOG_REF
return CONSTRAINT_DIALOG_REF
#------------------------------------------------------------------------------
def setConstraintDialogRef(ref):
global CONSTRAINT_DIALOG_REF
CONSTRAINT_DIALOG_REF = ref
#------------------------------------------------------------------------------
def getUseTopoNaming():
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
return preferences.GetBool('useTopoNaming',False)
#------------------------------------------------------------------------------
def getRelativePathesEnabled():
global RELATIVE_PATHES_ENABLED
return RELATIVE_PATHES_ENABLED
#------------------------------------------------------------------------------
def setAutoSolve(enabled):
global AUTOSOLVE_ENABLED
AUTOSOLVE_ENABLED = enabled
#------------------------------------------------------------------------------
def getAutoSolveState():
return AUTOSOLVE_ENABLED
#------------------------------------------------------------------------------
def setPartialProcessing(enabled):
global PARTIAL_PROCESSING_ENABLED
PARTIAL_PROCESSING_ENABLED = enabled
#------------------------------------------------------------------------------
def isPartialProcessing():
return PARTIAL_PROCESSING_ENABLED
#------------------------------------------------------------------------------
def filterShapeObs(_list, allowSketches=False):
lst = []
for ob in _list:
if allowSketches == True:
if ob.Name.startswith("Sketch"):
lst.append(ob)
continue
if (
#Following object now have App::GeoFeatureGroupExtension in FC0.19
#prevent them from being filtered out.
ob.Name.startswith("Boolean") or
ob.Name.startswith("Body")
):
pass
elif ob.hasExtension('App::GeoFeatureGroupExtension'):
#Part Containers within FC0.19.18405 seem to have a shape property..
#filter it out
continue
elif ob.Name.startswith("Group"):
#Group Containers within FC0.19 (Release >= 2020/03/31) seem to have a shape property..
#filter it out
continue
if hasattr(ob,"Shape") and ob.Shape is not None and ob.Shape != 'None': #str 'None': TechDraw Balloons...
if len(ob.Shape.Faces) > 0 and len(ob.Shape.Vertexes) > 0:
lst.append(ob)
S = set(lst)
lst = []
lst.extend(S)
return lst
#------------------------------------------------------------------------------
def setTransparency():
global SAVED_TRANSPARENCY
# Save Transparency of Objects and make all transparent
doc = FreeCAD.ActiveDocument
if len(SAVED_TRANSPARENCY) > 0:
# Transparency is already saved, no need to set transparency again
return
shapedObs = filterShapeObs(doc.Objects) # filter out partlist, spreadsheets etc..
sel = FreeCADGui.Selection
for obj in shapedObs:
if hasattr(obj,'ViewObject'): # save "all-in" *MK
if hasattr(obj.ViewObject,'DiffuseColor'):
SAVED_TRANSPARENCY.append(
(obj.Name, obj.ViewObject.Transparency, obj.ViewObject.ShapeColor, obj.ViewObject.DiffuseColor)
)
else:
SAVED_TRANSPARENCY.append(
(obj.Name, obj.ViewObject.Transparency, obj.ViewObject.ShapeColor, None)
)
obj.ViewObject.Transparency = 80
sel.addSelection(obj) # Transparency workaround. Transparency is taken when once been selected
sel.clearSelection()
#------------------------------------------------------------------------------
def restoreTransparency():
global SAVED_TRANSPARENCY
# restore transparency of objects...
doc = FreeCAD.ActiveDocument
sel = FreeCADGui.Selection
for setting in SAVED_TRANSPARENCY:
obj = doc.getObject(setting[0])
if obj is not None: # restore "all-in" *MK
obj.ViewObject.Transparency = setting[1]
obj.ViewObject.ShapeColor = setting[2]
obj.ViewObject.DiffuseColor = setting[3] # diffuse always at last
sel.addSelection(obj)
sel.clearSelection()
SAVED_TRANSPARENCY = []
#------------------------------------------------------------------------------
def isTransparencyEnabled():
global SAVED_TRANSPARENCY
return (len(SAVED_TRANSPARENCY) > 0)
#------------------------------------------------------------------------------
def getSelectedConstraint():
# Check that constraint is selected
selection = [s for s in FreeCADGui.Selection.getSelection() if s.Document == FreeCAD.ActiveDocument ]
if len(selection) == 0: return None
connectionToView = selection[0]
if not 'ConstraintInfo' in connectionToView.Content and not 'ConstraintNfo' in connectionToView.Content:
return None
return connectionToView
#------------------------------------------------------------------------------
def appVersionStr():
version = int(FreeCAD.Version()[0])
subVersion = int(float(FreeCAD.Version()[1]))
return "%03d.%03d" %(version,subVersion)
#------------------------------------------------------------------------------
def numpyVecToFC(nv):
assert len(nv) == 3
return Base.Vector(nv[0],nv[1],nv[2])
#------------------------------------------------------------------------------
def fit_rotation_axis_to_surface1( surface, n_u=3, n_v=3 ):
'should work for cylinders and possibly cones (depending on the u,v mapping)'
uv = sum( [ [ (u,v) for u in numpy.linspace(0,1,n_u)] for v in numpy.linspace(0,1,n_v) ], [] )
P = [ numpy.array(surface.value(u,v)) for u,v in uv ] #positions at u,v points
N = [ numpy.cross( *surface.tangent(u,v) ) for u,v in uv ]
intersections = []
for i in range(len(N)-1):
for j in range(i+1,len(N)):
# based on the distance_between_axes( p1, u1, p2, u2) function,
if 1 - abs(numpy.dot( N[i], N[j])) < 10**-6:
continue #ignore parallel case
p1_x, p1_y, p1_z = P[i]
u1_x, u1_y, u1_z = N[i]
p2_x, p2_y, p2_z = P[j]
u2_x, u2_y, u2_z = N[j]
t1_t1_coef = u1_x**2 + u1_y**2 + u1_z**2 #should equal 1
t1_t2_coef = -2*u1_x*u2_x - 2*u1_y*u2_y - 2*u1_z*u2_z # collect( expand(d_sqrd), [t1*t2] )
t2_t2_coef = u2_x**2 + u2_y**2 + u2_z**2 #should equal 1 too
t1_coef = 2*p1_x*u1_x + 2*p1_y*u1_y + 2*p1_z*u1_z - 2*p2_x*u1_x - 2*p2_y*u1_y - 2*p2_z*u1_z
t2_coef =-2*p1_x*u2_x - 2*p1_y*u2_y - 2*p1_z*u2_z + 2*p2_x*u2_x + 2*p2_y*u2_y + 2*p2_z*u2_z
A = numpy.array([ [ 2*t1_t1_coef , t1_t2_coef ] , [ t1_t2_coef, 2*t2_t2_coef ] ])
b = numpy.array([ t1_coef, t2_coef])
try:
t1, t2 = numpy.linalg.solve(A,-b)
except numpy.linalg.LinAlgError:
continue #print('distance_between_axes, failed to solve problem due to LinAlgError, using numerical solver instead')
pos_t1 = P[i] + numpy.array(N[i])*t1
pos_t2 = P[j] + N[j]*t2
intersections.append( pos_t1 )
intersections.append( pos_t2 )
if len(intersections) < 2:
error = numpy.inf
return None, None, error
else: #fit vector to intersection points; http://mathforum.org/library/drmath/view/69103.html
X = numpy.array(intersections)
centroid = numpy.mean(X,axis=0)
M = numpy.array([i - centroid for i in intersections ])
A = numpy.dot(M.transpose(), M)
U,s,V = numpy.linalg.svd(A) #numpy docs: s : (..., K) The singular values for every matrix, sorted in descending order.
axis_pos = centroid
axis_dir = V[0]
error = s[1] #dont know if this will work
return numpyVecToFC(axis_dir), numpyVecToFC(axis_pos), error
#------------------------------------------------------------------------------
def fit_plane_to_surface1( surface, n_u=3, n_v=3 ):
uv = sum( [ [ (u,v) for u in numpy.linspace(0,1,n_u)] for v in numpy.linspace(0,1,n_v) ], [] )
P = [ surface.value(u,v) for u,v in uv ] #positions at u,v points
N = [ numpy.cross( *surface.tangent(u,v) ) for u,v in uv ]
plane_norm = sum(N) / len(N) #planes normal, averaging done to reduce error
plane_pos = P[0]
error = sum([ abs( numpy.dot(p - plane_pos, plane_norm) ) for p in P ])
return numpyVecToFC(plane_norm), numpyVecToFC(plane_pos), error
#------------------------------------------------------------------------------
def isLine(param):
if hasattr(Part,"LineSegment"):
return isinstance(param,(Part.Line,Part.LineSegment))
else:
return isinstance(param,Part.Line)
#------------------------------------------------------------------------------
def getObjectFaceFromName( obj, faceName ):
assert faceName.startswith('Face')
ind = int( faceName[4:]) -1
return obj.Shape.Faces[ind]
#------------------------------------------------------------------------------
def getProjectFolder():
"""
#------------------------------------------------------------------------------------
# A new Parameter is required: projectFolder...
# All Parts will be searched below this projectFolder-Value...
#------------------------------------------------------------------------------------
"""
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
if not preferences.GetBool('useProjectFolder', False): return ""
return preferences.GetString('projectFolder', '~')
#------------------------------------------------------------------------------
def pathToOS(path):
if path is None: return None
p = to_str(path)
if OPERATING_SYSTEM == 'WINDOWS':
p = p.replace(u'/',u'\\')
else:
p = p.replace(u'\\',u'/')
return p # unicode string
#------------------------------------------------------------------------------
def findFile(_name, _path):
"""
Searches a file within a directory and its subdirectories.
"""
name = to_str(_name)
path = to_str(_path)
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
return None
#------------------------------------------------------------------------------
def findSourceFileInProject(_pathImportPart, _assemblyPath):
"""
#------------------------------------------------------------------------------------
# interpret the sourcefile name of imported part
# if working with preference "useProjectFolder:
# - path of sourcefile is ignored
# - filename is looked up beneath projectFolder
#
# if not working with preference "useProjectFolder":
# - path of sourcefile is checked for being relative to assembly or absolute
# - path is interpreted in appropriate way
#------------------------------------------------------------------------------------
"""
pathImportPart = _pathImportPart
assemblyPath = _assemblyPath
pathImportPart = to_bytes(pathImportPart)
assemblyPath = to_bytes(assemblyPath)
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
if not preferences.GetBool('useProjectFolder', False):
# not working with useProjectFolder preference,
# check whether path is relative or absolute...
if (
pathImportPart.startswith(b'../') or
pathImportPart.startswith(b'..\\') or
pathImportPart.startswith(b'./') or
pathImportPart.startswith(b'.\\')
):
# relative path
# calculate the absolute path
p1 = to_str(assemblyPath)
p2 = to_str(pathImportPart)
joinedPath = os.path.join(p1,p2)
absolutePath = os.path.normpath(joinedPath)
absolutePath = pathToOS(absolutePath)
return to_str(absolutePath)
else:
pathImportPart = pathToOS(pathImportPart)
return to_str(pathImportPart)
projectFolder = os.path.abspath(getProjectFolder()) # get normalized path
fileName = os.path.basename(pathImportPart)
retval = findFile(fileName,projectFolder)
retval = pathToOS(retval)
if retval:
return to_str(retval)
else:
return None
#------------------------------------------------------------------------------
def checkFileIsInProjectFolder(path):
preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/A2plus")
if not preferences.GetBool('useProjectFolder', False): return True
projectFolder = os.path.abspath(getProjectFolder()) # get normalized path
fileName = os.path.basename(path)
nameInProject = findFile(fileName,projectFolder)
if nameInProject == path:
return True
else:
return False
#------------------------------------------------------------------------------
def Msg(tx):
FreeCAD.Console.PrintMessage(tx)
#------------------------------------------------------------------------------
def DebugMsg(level, tx):
if A2P_DEBUG_LEVEL >= level:
FreeCAD.Console.PrintMessage(tx)
#------------------------------------------------------------------------------
def drawSphere(center, color):
doc = FreeCAD.ActiveDocument
s = Part.makeSphere(2.0,center)
sphere = doc.addObject("Part::Feature","Sphere")
sphere.Shape = s
sphere.ViewObject.ShapeColor = color
doc.recompute()
#------------------------------------------------------------------------------
def drawVector(fromPoint,toPoint, color):
if fromPoint == toPoint: return
doc = FreeCAD.ActiveDocument
l = Part.LineSegment()
l.StartPoint = fromPoint
l.EndPoint = toPoint
line = doc.addObject("Part::Feature","Line")
line.Shape = l.toShape()
line.ViewObject.LineColor = color
line.ViewObject.LineWidth = 1
c = Part.makeCone(0,1,4)
cone = doc.addObject("Part::Feature","ArrowHead")
cone.Shape = c
cone.ViewObject.ShapeColor = color
#
mov = Base.Vector(0,0,0)
zAxis = Base.Vector(0,0,-1)
rot = FreeCAD.Rotation(zAxis,toPoint.sub(fromPoint))
cent = Base.Vector(0,0,0)
conePlacement = FreeCAD.Placement(mov,rot,cent)
cone.Placement = conePlacement.multiply(cone.Placement)
cone.Placement.move(toPoint)
doc.recompute()
#------------------------------------------------------------------------------
def findUnusedObjectName(base, counterStart=1, fmt='%03i', document=None):
if document is None:
document = FreeCAD.ActiveDocument
i = counterStart
usedNames = [ obj.Name for obj in document.Objects ]
base2 = base
if base[-4:-3] == '_':
try:
int(base[-3:])
base2 = base[:-4]
except:
pass
base2 = base2 + '_'
objName = '%s%s' % (base2, fmt%i)
while objName in usedNames:
i += 1
objName = '%s%s' % (base2, fmt%i)
return objName
#------------------------------------------------------------------------------
def findUnusedObjectLabel(base, counterStart=1, fmt='%03i', document=None, extension=None):
if document is None:
document = FreeCAD.ActiveDocument
i = counterStart
usedLabels = [ obj.Label for obj in document.Objects ]
base2 = base
if base[-4:-3] == '_':
try:
int(base[-3:])
base2 = base[:-4]
except:
pass
base2 = base2 + '_'
if extension is None:
base3 = base2
else:
base3 = base2+extension+'_'
objLabel = '%s%s' % (base3, fmt%i)
while objLabel in usedLabels:
i += 1
objLabel = '%s%s' % (base3, fmt%i)
return objLabel
#------------------------------------------------------------------------------
class ConstraintSelectionObserver:
def __init__(self, selectionGate, parseSelectionFunction,
taskDialog_title, taskDialog_iconPath, taskDialog_text,
secondSelectionGate=None):
self.selections = []
self.parseSelectionFunction = parseSelectionFunction
self.secondSelectionGate = secondSelectionGate
FreeCADGui.Selection.addObserver(self)
FreeCADGui.Selection.removeSelectionGate()
FreeCADGui.Selection.addSelectionGate( selectionGate )
wb_globals['selectionObserver'] = self
self.taskDialog = SelectionTaskDialog(taskDialog_title, taskDialog_iconPath, taskDialog_text)
FreeCADGui.Control.showDialog( self.taskDialog )
def addSelection( self, docName, objName, sub, pnt ):
self.selections.append( SelectionRecord( docName, objName, sub ))
if len(self.selections) == 2:
self.stopSelectionObservation()
self.parseSelectionFunction( self.selections)
elif self.secondSelectionGate is not None and len(self.selections) == 1:
FreeCADGui.Selection.removeSelectionGate()
FreeCADGui.Selection.addSelectionGate( self.secondSelectionGate )
def stopSelectionObservation(self):
FreeCADGui.Selection.removeObserver(self)
del wb_globals['selectionObserver']
FreeCADGui.Selection.removeSelectionGate()
FreeCADGui.Control.closeDialog()
#------------------------------------------------------------------------------
class SelectionRecord:
def __init__(self, docName, objName, sub):
self.Document = FreeCAD.getDocument(docName)
self.ObjectName = objName
self.Object = self.Document.getObject(objName)
self.SubElementNames = [sub]
#------------------------------------------------------------------------------
class SelectionTaskDialog:
def __init__(self, title, iconPath, textLines ):
self.form = SelectionTaskDialogForm( textLines )
self.form.setWindowTitle( title )
if iconPath is not None:
self.form.setWindowIcon( QtGui.QIcon( iconPath ) )
def reject(self):
wb_globals['selectionObserver'].stopSelectionObservation()
def getStandardButtons(self): #http://forum.freecadweb.org/viewtopic.php?f=10&t=11801
return 0x00400000 #cancel button
#------------------------------------------------------------------------------
class SelectionTaskDialogForm(QtGui.QWidget):
def __init__(self, textLines ):
super(SelectionTaskDialogForm, self).__init__()
self.textLines = textLines
self.initUI()
def initUI(self):
vbox = QtGui.QVBoxLayout()
for line in self.textLines.split('\n'):
vbox.addWidget( QtGui.QLabel(line) )
self.setLayout(vbox)
#------------------------------------------------------------------------------
class SelectionExObject:
"""Allows for selection gate functions to interface with classification functions below."""
def __init__(self, doc, Object, subElementName):
self.doc = doc
self.Object = Object
self.ObjectName = Object.Name
self.SubElementNames = [subElementName]
#------------------------------------------------------------------------------
def getObjectEdgeFromName( obj, name ):
assert name.startswith('Edge')
ind = int( name[4:]) -1
return obj.Shape.Edges[ind]
#------------------------------------------------------------------------------
def CircularEdgeSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Edge'):
edge = getObjectEdgeFromName( selection.Object, subElement)
if not hasattr(edge, 'Curve'): #issue 39
return False
if isLine(edge.Curve):
return False
if hasattr( edge.Curve, 'Radius' ):
return True
# the following section fails for linear edges, protect it
# by try/except block
try:
BSpline = edge.Curve.toBSpline()
arcs = BSpline.toBiArcs(10**-6)
if all( hasattr(a,'Center') for a in arcs ):
centers = numpy.array([a.Center for a in arcs])
sigma = numpy.std( centers, axis=0 )
if max(sigma) < 10**-6: #then circular curve
return True
except:
pass
return False
#------------------------------------------------------------------------------
def ClosedEdgeSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Edge'):
edge = getObjectEdgeFromName( selection.Object, subElement)
if edge.isClosed():
return True
else:
return False
return False
#------------------------------------------------------------------------------
def AxisOfPlaneSelected( selection ): #adding Planes/Faces selection for Axial constraints
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Face'):
face = getObjectFaceFromName( selection.Object, subElement)
if str(face.Surface) == '<Plane object>':
return True
else:
axis, center, error = fit_rotation_axis_to_surface1(face.Surface)
error_normalized = error / face.BoundBox.DiagonalLength
if error_normalized < 10**-6:
return True
return False
#------------------------------------------------------------------------------
def printSelection(selection):
entries = []
for s in selection:
for e in s.SubElementNames:
entries.append(' - %s:%s' % (s.ObjectName, e))
if e.startswith('Face'):
ind = int( e[4:]) -1
face = s.Object.Shape.Faces[ind]
entries[-1] = entries[-1] + ' %s' % str(face.Surface)
return '\n'.join( entries[:5] )
#------------------------------------------------------------------------------
def updateObjectProperties( c ):
return
#------------------------------------------------------------------------------
def planeSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Face'):
face = getObjectFaceFromName( selection.Object, subElement)
if str(face.Surface) == '<Plane object>':
return True
elif str(face.Surface) == '<BSplineSurface object>':
normal,pos,error = fit_plane_to_surface1(face.Surface)
if abs(error) < 1e-9:
return True
return False
#------------------------------------------------------------------------------
def vertexSelected( selection ):
if len( selection.SubElementNames ) == 1:
return selection.SubElementNames[0].startswith('Vertex')
return False
#------------------------------------------------------------------------------
def cylindricalFaceSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Face'):
face = getObjectFaceFromName( selection.Object, subElement)
if hasattr(face.Surface,'Radius'):
return True
elif str(face.Surface).startswith('<SurfaceOfRevolution'):
return True
else:
axis, center, error = fit_rotation_axis_to_surface1(face.Surface)
error_normalized = error / face.BoundBox.DiagonalLength
if error_normalized < 10**-6:
return True
return False
#------------------------------------------------------------------------------
def LinearEdgeSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Edge'):
edge = getObjectEdgeFromName( selection.Object, subElement)
if not hasattr(edge, 'Curve'): #issue 39
return False
if isLine(edge.Curve):
return True
BSpline = edge.Curve.toBSpline()
arcs = BSpline.toBiArcs(10**-6)
if all(isLine(a) for a in arcs):
lines = arcs
D = numpy.array([L.tangent(0)[0] for L in lines]) #D(irections)
if numpy.std( D, axis=0 ).max() < 10**-9: #then linear curve
return True
return False
#------------------------------------------------------------------------------
def sphericalSurfaceSelected( selection ):
if len( selection.SubElementNames ) == 1:
subElement = selection.SubElementNames[0]
if subElement.startswith('Face'):
face = getObjectFaceFromName( selection.Object, subElement)
return str( face.Surface ).startswith('Sphere ')
return False
#------------------------------------------------------------------------------
def getObjectVertexFromName( obj, name ):
assert name.startswith('Vertex')
ind = int( name[6:]) -1
return obj.Shape.Vertexes[ind]
#------------------------------------------------------------------------------
def removeConstraint( constraint ):
'required as constraint.Proxy.onDelete only called when deleted through GUI'
doc = constraint.Document
if constraint.ViewObject is not None:
constraint.ViewObject.Proxy.onDelete( constraint.ViewObject, None ) # also removes mirror...
doc.removeObject( constraint.Name )
#------------------------------------------------------------------------------
def getPos(obj, subElementName):
pos = None
if subElementName.startswith('Face'):
face = getObjectFaceFromName(obj, subElementName)
surface = face.Surface
if str(surface) == '<Plane object>':
pos = getObjectFaceFromName(obj, subElementName).Faces[0].BoundBox.Center
# axial constraint for Planes
# pos = surface.Position
elif str(surface) == "<Cylinder object>":
pos = surface.Center
elif all( hasattr(surface,a) for a in ['Axis','Center','Radius'] ):
pos = surface.Center
elif str(surface).startswith('<SurfaceOfRevolution'):
pos = getObjectFaceFromName(obj, subElementName).Edges[0].Curve.Center
elif str(surface).startswith('<BSplineSurface'):
axis,pos1,error = fit_plane_to_surface1(surface)
error_normalized = error / face.BoundBox.DiagonalLength
if error_normalized < 10**-6: #then good plane fit
pos = pos1
axis, center, error = fit_rotation_axis_to_surface1(face.Surface)
if axis is not None:
error_normalized = error / face.BoundBox.DiagonalLength
if error_normalized < 10**-6: #then good rotation_axis fix
pos = center
elif subElementName.startswith('Edge'):
edge = getObjectEdgeFromName(obj, subElementName)
if isLine(edge.Curve):
if appVersionStr() <= "000.016":
pos = edge.Curve.StartPoint
else:
pos = edge.firstVertex(True).Point
elif hasattr( edge.Curve, 'Center'): #circular curve
pos = edge.Curve.Center
else:
BSpline = edge.Curve.toBSpline()
arcs = BSpline.toBiArcs(10**-6)
if all( hasattr(a,'Center') for a in arcs ):
centers = numpy.array([a.Center for a in arcs])
sigma = numpy.std( centers, axis=0 )
if max(sigma) < 10**-6: #then circular curve
pos = numpyVecToFC(centers[0])
if all(isLine(a) for a in arcs):
lines = arcs
D = numpy.array([L.tangent(0)[0] for L in lines]) #D(irections)
if numpy.std( D, axis=0 ).max() < 10**-9: #then linear curve
pos = lines[0].value(0)
elif subElementName.startswith('Vertex'):
pos = getObjectVertexFromName(obj, subElementName).Point
return pos # maybe none !!
#------------------------------------------------------------------------------
def getPlaneNormal(surface):