-
Notifications
You must be signed in to change notification settings - Fork 75
/
Asm4_Measure.py
1187 lines (1077 loc) · 244 KB
/
Asm4_Measure.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#****************************************************************************
#* *
#* by Zoltan Hubert *
#* *
#* code partially based on: *
#* *
#* Caliper tool, icons by easyw-fc *
#* evolution of Macro_CenterFace *
#* some part of Macro WorkFeature *
#* and Macro Rotate To Point, Macro_Delta_xyz *
#* and assembly2 *
#* *
#* Measure tool *
#* *
#* This is a stand-alone tool that doesn't need anything outside Part *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Library 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. *
#****************************************************************************
import threading, sys, math, os
import numpy as np
import base64
from PySide import QtGui, QtCore
from pivy import coin
import FreeCADGui as Gui
import FreeCAD as App
from FreeCAD import Base
from FreeCAD import Console as FCC
import Part
# only needed for icons
import Asm4_libs as Asm4
import selectionFilter
"""
+-----------------------------------------------+
| Global variables |
+-----------------------------------------------+
"""
global taskUI, addedDims, PtS, Asm4_3DselObserver
addedDims = []
PtS = None
annoFontSize = 12.0
annoPrecision = 0.001
iconDir = Asm4.iconPath
# remove previous snap point
def removePtS():
global PtS
if PtS and hasattr(PtS,'Name') and App.ActiveDocument.getObject(PtS.Name):
App.ActiveDocument.removeObject(PtS.Name)
PtS = None
# usage:
# object = App.ActiveDocument.addObject('App::FeaturePython','objName')
# object.ViewObject.Proxy = setCustomIcon(object,'Icon.svg')
# import base64
# encoded = base64.b64encode(open("filename.png", "rb").read())
class setCustomIcon():
def __init__( self, obj, iconFile ):
icon = os.path.join( iconDir , iconFile )
self.customIcon = icon
def getIcon(self):
return self.customIcon
"""
+-----------------------------------------------+
| The menu and toolbar command |
+-----------------------------------------------+
"""
class MeasureCmd():
def __init__(self):
super(MeasureCmd,self).__init__()
def GetResources(self):
return {"MenuText": "Measure",
"ToolTip": "Measure Tool",
"Pixmap" : os.path.join( iconDir , 'Part_Measure.svg')
}
def IsActive(self):
if App.ActiveDocument:
return True
return False
def Activated(self):
Gui.Control.showDialog( MeasureUI() )
"""
+-----------------------------------------------+
| The UI and functions in the Task panel |
+-----------------------------------------------+
"""
class MeasureUI():
def __init__(self):
self.base = QtGui.QWidget()
self.form = self.base
iconFile = os.path.join( iconDir , 'Part_Measure.svg')
self.form.setWindowIcon(QtGui.QIcon( iconFile ))
self.form.setWindowTitle('Measure')
# remove selectionFilter
global Asm4_3DselObserver
self.selectionFilterStatus = selectionFilter.observerStatus()
selectionFilter.observerDisable()
selectionFilter.uncheckAll()
# draw the GUI, objects are defined later down
self.drawUI()
global taskUI
taskUI = self
global PtS
global addedDims
# start the observer
Gui.Selection.clearSelection()
#self.so=SelObserverCaliper()
self.so = selectionObserver()
Gui.Selection.addObserver( self.so, 1 ) # 1 = resolve
FCC.PrintMessage('Observer started\n')
# enable the measurement points
self.Selection1.setEnabled(True)
self.Selection1.setChecked(False)
self.Selection2.setEnabled(False)
self.sel1Icon.setIcon(QtGui.QIcon(self.selectIcon))
# init finished
# standard FreeCAD Task panel buttons
def getStandardButtons(self):
return QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Reset | QtGui.QDialogButtonBox.Ok
# OK button
def accept(self):
# update the Measure group to get rid if the small overlay icon
App.ActiveDocument.recompute()
self.Finish()
# Cancel button
def reject(self):
self.Reset()
self.Finish()
# Reset button
def clicked(self, button):
if button == QtGui.QDialogButtonBox.Reset:
self.Reset()
# Close
def Finish(self):
FCC.PrintMessage("closing ... ")
try:
Gui.Selection.removeObserver(self.so) # uninstall the resident SelObserver function
FCC.PrintMessage("done\n")
except:
FCC.PrintWarning("was not able to remove observer\n")
# remove PtS because it can have strange results
removePtS()
# close Task widget
Gui.Control.closeDialog()
# Reset (clear measures)
def Reset(self):
global PtS, addedDims
Gui.Selection.clearSelection()
self.clearConsole()
FCC.PrintMessage('Removing all measurements ...')
removePtS()
for d in addedDims:
FCC.PrintMessage('.')
try:
App.ActiveDocument.removeObject(d.Name)
except:
pass
addedDims=[]
# also remove the "Measures" group if any
if App.ActiveDocument.getObject('Measures') and \
App.ActiveDocument.getObject('Measures').TypeId=='App::DocumentObjectGroup':
App.ActiveDocument.removeObject('Measures')
# clear UI
self.sel1Name.clear()
self.sel2Name.clear()
self.sel1Icon.setIcon(QtGui.QIcon(self.selectIcon))
self.sel2Icon.setIcon(QtGui.QIcon(self.noneIcon))
self.Selection1.setEnabled(True)
self.Selection1.setChecked(False)
self.Selection2.setEnabled(False)
self.resultText.clear()
FCC.PrintMessage(' done\n')
# clear report view and Python panel
def clearConsole(self):
#clearing previous messages
mw = Gui.getMainWindow()
#c=mw.findChild(QtGui.QPlainTextEdit, "Python console")
#c.clear()
rv = mw.findChild(QtGui.QTextEdit, "Report view")
rv.clear()
# Actions
#
# when changing the measurement type, reset pre-existing selection
def onMeasure_toggled(self):
global PtS
self.Selection1.setChecked(False)
self.Selection2.setEnabled(False)
Gui.Selection.clearSelection()
removePtS()
self.sel1Icon.setIcon(QtGui.QIcon(self.selectIcon))
self.sel2Icon.setIcon(QtGui.QIcon(self.noneIcon))
# Angle dimensions only work with Snap selection
if self.rbAngle.isChecked():
self.rbShape.setChecked(True)
# re-initialize Selection 1
def onSel1_toggled(self):
if not self.Selection1.isChecked() and self.Selection2.isEnabled():
self.Selection1.setChecked(False)
self.sel1Name.clear()
self.Selection2.setEnabled(False)
Gui.Selection.clearSelection()
removePtS()
self.sel1Icon.setIcon(QtGui.QIcon(self.selectIcon))
self.sel2Icon.setIcon(QtGui.QIcon(self.noneIcon))
else:
if not self.Selection2.isEnabled():
self.Selection1.setChecked(False)
self.sel1Icon.setIcon(QtGui.QIcon(self.selectIcon))
#self.sel2Icon.setIcon(QtGui.QIcon(self.noneIcon))
# Angle can be measured only between shapes
def onSnap_toggled(self):
if self.rbAngle.isChecked() and self.rbSnap.isChecked():
self.rbDistance.setChecked(True)
# defines the UI, only static elements
def drawUI(self):
iconSize = 32
btSize = 48
btn_sizeX=32;btn_sizeY=32;
btn_sizeX=32;btn_sizeY=32;
chkb_sizeX=20;chkb_sizeY=20;
btn_sm_sizeX=20;btn_sm_sizeY=20;
btn_md_sizeX=26;btn_md_sizeY=26;
# icons of UI
pm = QtGui.QPixmap()
self.noneIcon = None
pm.loadFromData(base64.b64decode( valid_b64 ))
self.validIcon = QtGui.QIcon(pm)
pm.loadFromData(base64.b64decode( select_b64 ))
self.selectIcon = QtGui.QIcon(pm)
# icons for the tree
self.pointIcon = 'Draft_Point.svg'
self.lineIcon = 'Draft_Line.svg'
self.circleIcon = 'Draft_Circle.svg'
self.dimensionIcon = 'Draft_Dimension.svg'
# the layout for the main window is vertical (top to down)
self.mainLayout = QtGui.QVBoxLayout(self.form)
self.mainLayout.addWidget(QtGui.QLabel('Controls'))
# measurement type
self.measureGroup = QtGui.QFrame(self.form)
self.measureGroup.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain)
self.mainLayout.addWidget(self.measureGroup)
self.measureGrid = QtGui.QGridLayout(self.measureGroup)
# self.mainLayout.addLayout(self.measureGrid)
# 0,0
pm.loadFromData(base64.b64decode(Dim_Radius_b64))
self.rbRadius = QtGui.QRadioButton(self.measureGroup)
self.rbRadius.setObjectName("rbRadius")
self.rbRadius.setToolTip("Measure Radius of Arc or Circle\nMeasure Length of Edge")
self.rbRadius.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.rbRadius.setIcon(QtGui.QIcon(pm))
self.rbRadius.setChecked(True)
self.measureGrid.addWidget(self.rbRadius, 0, 0 )
# 0,1
pm.loadFromData(base64.b64decode(Dim_Length_b64))
self.rbDistance = QtGui.QRadioButton(self.measureGroup)
self.rbDistance.setObjectName("rbDistance")
self.rbDistance.setToolTip("Measure Distance")
self.rbDistance.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.rbDistance.setIcon(QtGui.QIcon(pm))
self.measureGrid.addWidget(self.rbDistance, 0, 1 )
# 0,2
pm.loadFromData(base64.b64decode(Dim_Angle_b64))
self.rbAngle = QtGui.QRadioButton(self.measureGroup)
self.rbAngle.setObjectName("rbAngle")
self.rbAngle.setToolTip("Measure Angle")
self.rbAngle.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.rbAngle.setIcon(QtGui.QIcon(pm))
self.measureGrid.addWidget(self.rbAngle, 0, 2 )
# actual measurement tools
self.snapGroup = QtGui.QFrame(self.form)
self.snapGroup.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain)
# self.snapGroup.setTitle("Selection method")
self.mainLayout.addWidget(self.snapGroup)
self.snapGrid = QtGui.QGridLayout(self.snapGroup)
# self.mainLayout.addLayout(self.snapGrid)
# original snap/selection tools
# 0,0
pm.loadFromData(base64.b64decode(Snap_Options_b64))
self.rbSnap = QtGui.QRadioButton(self.snapGroup)
self.rbSnap.setObjectName("rbSnap")
self.rbSnap.setToolTip("Snap to EndPoint, MiddlePoint, Center")
self.rbSnap.setIconSize(QtCore.QSize(3*btn_md_sizeX,btn_md_sizeY))
self.rbSnap.setIcon(QtGui.QIcon(pm))
self.rbSnap.setChecked(False)
self.snapGrid.addWidget(self.rbSnap, 0, 0, 1, 2 )
# 0,2
pm.loadFromData(base64.b64decode(Center_Mass_b64))
self.rbShape = QtGui.QRadioButton(self.snapGroup)
self.rbShape.setObjectName("rbShape")
self.rbShape.setToolTip("Select Shape")
self.rbShape.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.rbShape.setIcon(QtGui.QIcon(pm))
self.rbShape.setChecked(True)
self.snapGrid.addWidget(self.rbShape, 0, 2 )
'''
# TODO : make this selectionFilter be applied
# new snap/select tools
self.selGroup = QtGui.QFrame(self.form)
self.selGroup.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain)
self.mainLayout.addWidget(self.selGroup)
self.selGrid = QtGui.QGridLayout(self.selGroup)
# 0,0 SnapCenter
pm.loadFromData(base64.b64decode(SnapCenter_b64))
self.selCenter = QtGui.QPushButton(self.selGroup)
self.selCenter.setObjectName("selCenter")
self.selCenter.setToolTip("Select Circle Center")
self.selCenter.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.selCenter.setIcon(QtGui.QIcon(pm))
self.selCenter.setCheckable(True)
self.selCenter.setChecked(False)
self.selCenter.setFlat(True)
self.selGrid.addWidget(self.selCenter, 0, 0 )
# 0,1 SnapVertex
pm.loadFromData(base64.b64decode(SnapVertex_b64))
self.selVertex = QtGui.QPushButton(self.selGroup)
self.selVertex.setObjectName("selVertex")
self.selVertex.setToolTip("Select Vertex")
self.selVertex.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.selVertex.setIcon(QtGui.QIcon(pm))
self.selVertex.setCheckable(True)
self.selVertex.setChecked(False)
self.selVertex.setFlat(True)
self.selGrid.addWidget(self.selVertex, 0, 1 )
# 0,2 SnapEdge
pm.loadFromData(base64.b64decode(SnapEdge_b64))
self.selEdge = QtGui.QPushButton(self.selGroup)
self.selEdge.setObjectName("selEdge")
self.selEdge.setToolTip("Select Edge")
self.selEdge.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.selEdge.setIcon(QtGui.QIcon(pm))
self.selEdge.setCheckable(True)
self.selEdge.setChecked(False)
self.selEdge.setFlat(True)
self.selGrid.addWidget(self.selEdge, 0, 2 )
# 0,3 SnapFace
pm.loadFromData(base64.b64decode(SnapFace_b64))
self.selFace = QtGui.QPushButton(self.selGroup)
self.selFace.setObjectName("selFace")
self.selFace.setToolTip("Select Face")
self.selFace.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.selFace.setIcon(QtGui.QIcon(pm))
self.selFace.setCheckable(True)
self.selFace.setChecked(False)
self.selFace.setFlat(True)
self.selGrid.addWidget(self.selFace, 0, 3 )
# 0,4 SnapAll
pm.loadFromData(base64.b64decode(SelectAll_b64))
self.selShape = QtGui.QPushButton(self.selGroup)
self.selShape.setObjectName("selShape")
self.selShape.setToolTip("Select any Shape")
self.selShape.setIconSize(QtCore.QSize(btn_md_sizeX,btn_md_sizeY))
self.selShape.setIcon(QtGui.QIcon(pm))
self.selShape.setCheckable(True)
self.selShape.setChecked(True)
self.selShape.setFlat(True)
self.selGrid.addWidget(self.selShape, 0, 4 )
# exclusive buttons
self.buttonGroup = QtGui.QButtonGroup(self.selGroup)
self.buttonGroup.setExclusive(True)
self.buttonGroup.addButton(self.selCenter)
self.buttonGroup.addButton(self.selVertex)
self.buttonGroup.addButton(self.selEdge)
self.buttonGroup.addButton(self.selFace)
self.buttonGroup.addButton(self.selShape)
'''
# select elements
self.selectGrid = QtGui.QGridLayout()
# first element
self.Selection1 = QtGui.QPushButton('Selection 1')
self.Selection1.setToolTip("Select First Element")
self.Selection1.setMaximumWidth(150)
self.Selection1.setCheckable(True)
self.Selection1.setChecked(False)
self.sel1Name = QtGui.QLineEdit()
self.sel1Name.setMinimumWidth (50)
self.sel1Name.setReadOnly(True)
self.sel1Icon = QtGui.QPushButton()
self.sel1Icon.setFlat(True)
self.sel1Icon.setMinimumSize(QtCore.QSize(iconSize, iconSize))
self.sel1Icon.setMaximumSize(QtCore.QSize(iconSize, iconSize))
self.sel1Icon.setIconSize(QtCore.QSize(iconSize,iconSize))
self.sel1Icon.setIcon(QtGui.QIcon(self.noneIcon))
self.selectGrid.addWidget(self.Selection1, 0,0)
self.selectGrid.addWidget(self.sel1Name, 0,1)
self.selectGrid.addWidget(self.sel1Icon, 0,2)
# second element
self.Selection2 = QtGui.QPushButton('Selection 2')
self.Selection2.setToolTip("Select Second Element")
self.Selection2.setMaximumWidth(150)
self.Selection2.setEnabled(False)
self.Selection2.setChecked(False)
self.sel2Name = QtGui.QLineEdit()
self.sel2Name.setMinimumWidth (50)
self.sel2Name.setReadOnly(True)
self.sel2Icon = QtGui.QPushButton()
self.sel2Icon.setFlat(True)
self.sel2Icon.setMinimumSize(QtCore.QSize(iconSize, iconSize))
self.sel2Icon.setMaximumSize(QtCore.QSize(iconSize, iconSize))
self.sel2Icon.setIconSize(QtCore.QSize(iconSize,iconSize))
self.sel2Icon.setIcon(QtGui.QIcon(self.noneIcon))
self.selectGrid.addWidget(self.Selection2, 1,0)
self.selectGrid.addWidget(self.sel2Name, 1,1)
self.selectGrid.addWidget(self.sel2Icon, 1,2)
self.mainLayout.addLayout(self.selectGrid)
# Results
# draw annotation in the GUI window
self.bLabel = QtGui.QCheckBox()
self.bLabel.setObjectName("bLabel")
self.bLabel.setToolTip("Enable extra Label")
self.bLabel.setText("Show Label in 3D view")
self.bLabel.setChecked(True)
self.mainLayout.addWidget(self.bLabel)
# draw X-Y-Z components
self.Components = QtGui.QCheckBox()
self.Components.setObjectName("Components")
self.Components.setToolTip("Show all dimension components")
self.Components.setText("Show Components")
self.Components.setChecked(False)
self.mainLayout.addWidget(self.Components)
# Results
self.mainLayout.addWidget(QtGui.QLabel('Results'))
self.resultText = QtGui.QTextEdit()
self.resultText.setMinimumSize(200, 200)
self.resultText.setReadOnly(True)
self.mainLayout.addWidget(self.resultText)
# Actions
self.rbRadius.toggled.connect(self.onMeasure_toggled)
self.rbDistance.toggled.connect(self.onMeasure_toggled)
self.rbAngle.toggled.connect(self.onMeasure_toggled)
#self.rbAngle.toggled.connect(self.onAngle_toggled)
self.rbSnap.toggled.connect(self.onSnap_toggled)
self.Selection1.toggled.connect(self.onSel1_toggled)
"""
+-----------------------------------------------+
| a selection observer resident function |
+-----------------------------------------------+
"""
class selectionObserver():
def __init__(self):
global PtS
self.Sel1 = None
self.Shp1 = None
self.Pt1 = None
self.Sel2 = None
self.Shp2 = None
self.Pt2 = None
PtS = None
def render_distance(self, distance: float) -> str:
return App.Units.schemaTranslate(
App.Units.Quantity(str(distance) + " mm"),
App.Units.getSchema(),
)[0]
# add the dim to the global addedDims table to be able to remove it
# add it also the "Measures" group
def addToDims( self, dim ):
global addedDims
# check whether there is a "Measures" group
if not App.ActiveDocument.getObject('Measures'):
# if no, create one
measuresGroup = App.ActiveDocument.addObject( 'App::DocumentObjectGroup', 'Measures' )
# if there is already one, use it
elif App.ActiveDocument.getObject('Measures').TypeId=='App::DocumentObjectGroup':
measuresGroup = App.ActiveDocument.getObject('Measures')
# there is already a "Measures" object but it's not a Group, don't use it
else:
measuresGroup = None
if measuresGroup:
measuresGroup.addObject(dim)
# finally, add the dim to the global addedDims table/list
addedDims.append(dim)
# the real function
def addSelection(self, document, obj, element, position):
global taskUI
global PtS
fntsize='0.25mm'
ticksize='0.1mm'
# Select a subObject w/ the full hierarchy information
# empty string means current document, '*' means all document.
# The second argument 1 means resolve sub-object, which is the default value. 0 means full hierarchy.
# sel = Gui.Selection.getSelectionEx('', 0)[0].SubObjects[0]
selEx = Gui.Selection.getSelectionEx('', 0)
if len(Gui.Selection.getSelection()) == 1 or len(selEx) == 1:# or (len(selobject) == 1 and len(sel) == 1):
selObj = Gui.Selection.getSelection()[0]
#Faces or Edges
if len(selEx[0].SubObjects)>0:
subShape = selEx[0].SubObjects[0]
# we have selected an LCS, this needs special treatment
if selObj.TypeId == 'PartDesign::CoordinateSystem':
globalPlacement = App.Placement()
'''
# get the selection hierarchy
( obj, tree ) = Asm4.getSelectionTree()
# double-check, should always be true
if selObj == obj:
# first object is always in the current document
doc = App.ActiveDocument
# we parse the tree and cumulate the Placements
for objName in tree:
obj = doc.getObject(objName)
# Groups don't have Placement properties, ignore
if hasattr(obj,'Placement'):
globalPlacement *= obj.Placement
# if *this* object is a link to an *external* document, switch to that document
# necessary because links can be in the *current* document also
if obj.isDerivedFrom('App::Link') and obj.LinkedObject.Document != App.ActiveDocument:
doc = obj.LinkedObject.Document
# else, keep the same document
else:
pass
'''
# from https://forum.freecad.org/viewtopic.php?p=569083#p569083
# retType=3 returns the placement. Check the doc string for more info
# simplyfied version for single selection
path = selEx[0].SubElementNames[0]
globalPlacement = selEx[0].Object.getSubObject(path, retType=3)
# create a point at the origin of the LCS
base = globalPlacement.Base
PtS = self.drawPoint( App.Vector(base.x,base.y,base.z) )
subShape = PtS.Shape
# if valid selection
if subShape.isValid() and ('Face' in str(subShape) or 'Edge' in str(subShape) or 'Vertex' in str(subShape)):
# clear the result area
taskUI.resultText.clear()
removePtS()
# first element selection
if not taskUI.Selection1.isChecked():
# figure out the first selected element
self.Sel1 = None
self.Shp1 = None
self.Pt1 = None
self.Sel2 = None
self.Shp2 = None
self.Pt2 = None
#taskUI.sel1Name.setText(str(subShape))
taskUI.sel1Name.setText(str(subShape).split(' ')[0][1:])
taskUI.sel2Name.clear() # shape selected
if taskUI.rbShape.isChecked():
# the shape is actually a vertex, thus a point
if 'Vertex' in str(subShape):
self.Pt1 = subShape.Vertexes[0].Point
PtS = self.drawPoint(self.Pt1)
self.Sel1 = 'point'
# all other (real) shapes
else:
self.Shp1 = subShape
self.Sel1 = 'shape'
# Snap to select a point
elif taskUI.rbSnap.isChecked():
self.Pt1 = self.getSnap(subShape)
if self.Pt1:
PtS = self.drawPoint(self.Pt1)
self.Sel1 = 'point'
# this measures single objects
if taskUI.rbRadius.isChecked():
# if we have snapped a point before, we show its coordinates
if self.Sel1 == 'point':
self.measureCoords(self.Pt1)
# if we have selected a shape before, we show its characteristics
elif self.Sel1 == 'shape':
# a surface
if 'Face' in str(self.Shp1):
self.measureArea(self.Shp1)
# a point (should have been caught before)
elif 'Vertex' in str(self.Shp1):
self.measureCoords( self.Shp1 )
# a circle or arc of circle
# elif hasattr(self.Shp1,'Curve') and hasattr(self.Shp1.Curve,'Radius'):
elif self.isCircle(self.Shp1):
taskUI.sel1Name.setText('Circle')
self.measureCircle( self.Shp1 )
# a straight line segment
#elif hasattr(self.Shp1,'Curve') and self.Shp1.Curve.TypeId=='Part::GeomLine':
elif self.isSegment(self.Shp1):
taskUI.sel1Name.setText('Segment')
self.measureLine( self.Shp1 )
# dunno what that stuff is
else:
self.printResult("Can't measure\n"+str(self.Shp1))
# dunno what that stuff is
else:
self.printResult("Can't measure\n"+str(subShape))
# unset first selection
self.Sel1 is None
# if not rbRadius, launch the selection of the second element
elif self.Sel1 is not None:
#taskUI.Selection1.setEnabled(False)
taskUI.Selection2.setEnabled(True)
taskUI.Selection1.setChecked(True)
taskUI.sel1Icon.setIcon(QtGui.QIcon(taskUI.validIcon))
taskUI.sel2Icon.setIcon(QtGui.QIcon(taskUI.selectIcon))
# second element selected
elif taskUI.Selection2.isEnabled(): #step #2
#if PtS and ha#sattr(PtS,'Name') and App.ActiveDocument.getObject(PtS.Name):
# App.ActiveDocument.removeObject(PtS.Name)
# PtS = None
# figure out the second selected element
taskUI.sel2Name.setText(str(subShape).split(' ')[0][1:])
if taskUI.rbShape.isChecked():
self.Sel2 = 'shape'
self.Shp2 = subShape
# Snap to select a point
elif taskUI.rbSnap.isChecked():
self.Pt2 = self.getSnap(subShape)
if self.Pt2:
self.Sel2 = 'point'
# if we have a valid selection:
if self.Sel2 is not None:
taskUI.Selection2.setEnabled(False)
taskUI.Selection1.setChecked(False)
taskUI.sel1Icon.setIcon(QtGui.QIcon(taskUI.selectIcon))
taskUI.sel2Icon.setIcon(QtGui.QIcon(taskUI.validIcon))
removePtS()
# Measure distance
if taskUI.rbDistance.isChecked():
# make a vertex shape out of a point
if self.Pt1 and self.Sel1=='point':
self.Shp1 = Part.Vertex(Part.Point( self.Pt1 ))
self.Sel1 = 'shape'
if self.Pt2 and self.Sel2=='point':
self.Shp2 = Part.Vertex(Part.Point( self.Pt2 ))
self.Sel2 = 'shape'
if self.Sel1=='shape' and self.Sel2=='shape':
self.distShapes(self.Shp1,self.Shp2)
# unexpected behaviour
else:
self.printResult( 'ERROR 42\n'+str(self.Shp1)+'\n'+str(self.Shp2) )
# Measure angle
elif taskUI.rbAngle.isChecked():
if self.Sel1=='shape' and self.Sel2=='shape':
self.angleShapes( self.Shp1, self.Shp2 )
else:
self.printResult( 'Select only faces or lines' )
# some problem
else:
self.printResult( 'ERROR 44\n'+str(self.Shp2) )
# not valid selection
else:
self.printResult('ERROR 40\n'+str(subShape))
# uses BRepExtrema_DistShapeShape to calculate the distance between 2 shapes
def angleShapes( self, shape1, shape2 ):
global taskUI
if shape1.isValid() and shape2.isValid():
Gui.Selection.clearSelection()
self.printResult( 'Measuring angles' )
# Datum object
if shape1.BoundBox.DiagonalLength > 1e+10:
pt1 = shape1.Placement.Base
else:
pt1 = shape1.BoundBox.Center
# Datum object
if shape2.BoundBox.DiagonalLength > 1e+10:
pt2 = shape2.Placement.Base
else:
pt2 = shape2.BoundBox.Center
# get the direction of the shape
dir1 = self.getDir(shape1)
dir2 = self.getDir(shape2)
if dir1 and dir2:
distance = -1
angle = dir1.getAngle(dir2)*180./math.pi
# 2 flat faces
if self.isFlatFace(shape1) and self.isFlatFace(shape2):
angle = 180 - angle
else:
# 1 flat face and 1 direction
if self.isFlatFace(shape1) or self.isFlatFace(shape2):
angle = 90 - angle
if angle > 90:
angle = 180. - angle
# parallel directions
if abs(angle) < 1.0e-6 or abs(180-angle)<1.0e-6:
v1 = Part.Vertex(Part.Point( pt1 ))
v2 = Part.Vertex(Part.Point( pt2 ))
distance = v1.distToShape(v2)[0]
self.printAngle( angle, distance )
try:
self.drawLine(pt1,pt2,'Angle')
self.annoAngle( self.midPoint(pt1,pt2), angle, distance )
except:
pass
else:
self.printResult('Ivalid directions')
else:
self.printResult('Ivalid shapes')
# uses BRepExtrema_DistShapeShape to calculate the distance between 2 shapes
def distShapes( self, shape1, shape2 ):
global taskUI
if shape1.isValid() and shape2.isValid():
Gui.Selection.clearSelection()
measure = shape1.distToShape(shape2)
if measure and self.isVector(measure[1][0][0]) and self.isVector(measure[1][0][1]):
dist = measure[0]
self.printResult('Minimum Distance :\n '+str(dist))
if dist > 1.0e-9:
pt1 = measure[1][0][0]
pt2 = measure[1][0][1]
self.measurePoints(pt1,pt2)
else:
self.printResult('Ivalid shapes')
# measure a straight line
def measureLine(self, line ):
global taskUI
if self.isSegment(line):
pt1 = line.Vertexes[0].Point
pt2 = line.Vertexes[1].Point
Gui.Selection.clearSelection()
self.drawLine(pt1,pt2,'Length')
dx = pt1[0]-pt2[0]
dy = pt1[1]-pt2[1]
dz = pt1[2]-pt2[2]
length = line.Length
text = 'Length = '+self.render_distance(length)+'\n'
text += "ΔX = "+self.render_distance(dx)+"\n"
text += 'ΔY = '+self.render_distance(dy)+'\n'
text += 'ΔZ = '+self.render_distance(dz)
# self.printResult( 'Measuring length of\n'+str(line) )
self.printResult( text )
if taskUI.bLabel.isChecked():
mid = line.BoundBox.Center
if taskUI.Components.isChecked():
anno = ['L = '+self.arrondi(length),'ΔX = '+self.arrondi(dx), \
'ΔY = '+self.arrondi(dy), 'ΔZ = '+self.arrondi(dz) ]
else:
anno = ['L = '+self.render_distance(length)]
self.drawAnnotation( mid, anno )
else:
self.printResult( 'Not a valid Line\n'+str(line) )
# measure distance between 2 points
def measurePoints(self, pt1, pt2 ):
global taskUI
mid = self.midPoint(pt1,pt2)
if mid:
Gui.Selection.clearSelection()
self.drawLine(pt1,pt2,'DistPoints')
dx = pt1[0]-pt2[0]
dy = pt1[1]-pt2[1]
dz = pt1[2]-pt2[2]
dist = math.sqrt(dx*dx + dy*dy + dz*dz)
text = 'Distance = '+self.render_distance(dist)+'\n'
text += "ΔX : "+self.render_distance(dx)+"\n"
text += 'ΔY : '+self.render_distance(dy)+'\n'
text += 'ΔZ : '+self.render_distance(dz)
# self.printResult( 'Measuring length of\n'+str(line) )
self.printResult( text )
if taskUI.bLabel.isChecked():
if taskUI.Components.isChecked():
anno = ['D = '+self.render_distance(dist), 'ΔX = '+self.arrondi(dx),
'ΔY = '+self.arrondi(dy), 'ΔZ = '+self.arrondi(dz) ]
else:
anno = ['D = '+self.render_distance(dist)]
self.drawAnnotation( mid, anno )
else:
self.printResult( 'Not valid Points' )
# measure radius of a circle
def measureCircle(self, circle):
global taskUI, PtS
if self.isCircle(circle):
radius = circle.Curve.Radius
center = circle.Curve.Center
axis = circle.Curve.Axis
Gui.Selection.clearSelection()
self.drawCircle( radius, center, axis )
text = 'Radius : '+self.render_distance(radius)+"\n"
# if annotation is checked, show label with R = radius
text += "Diameter : "+self.render_distance(radius*2)+"\n"
text += 'Center : \n'
text += ' ( '+self.arrondi(center.x)+", "+self.arrondi(center.y)+", "+self.arrondi(center.z)+" )\n"
text += 'Axis : \n'
text += " ( "+self.arrondi(axis.x)+", "+self.arrondi(axis.y)+", "+self.arrondi(axis.z)+" )"
self.printResult(text)
if taskUI.bLabel.isChecked():
pt = circle.Vertexes[0].Point
self.drawLine(center,pt,'Radius')
self.drawAnnotation(pt, ['R = '+self.render_distance(radius)])
else:
PtS = self.drawPoint(center)
else:
self.printResult('Not a valid circle\n'+str(circle))
# figure out the direction of a shape, be it a line, a surface or a circle
def getDir( self, shape ):
direction = None
# for a segment, it's the normalized vector along the segment
if self.isSegment(shape):
line = shape
pt1 = line.Vertexes[0].Point
pt2 = line.Vertexes[1].Point
vect = (pt2.sub(pt1))
if vect.Length != 0:
direction = vect / vect.Length
# for another line (like Datum::Line) it's the Z vector
# multiplied by the Line's Placement
elif self.isLine(shape):
direction = shape.Placement.Rotation.multVec(App.Vector(0,0,1))
# for a Circle it's the circle's axis
elif self.isCircle(shape):
direction = shape.Curve.Axis
# TODO: drawAxis(circle)
# for a flt face it's the normal
elif self.isFlatFace(shape):
direction = shape.normalAt(0,0)
# TODO: drawNormal(face)
return direction
# figure out snap point of shape
def getSnap( self, shape ):
point = None
if shape.isValid():
if 'Vertex' in str(shape):
point = shape.Vertexes[0].Point
# for a circle, snap to the center
elif 'Edge' in str(shape) and hasattr(shape,'Curve') \
and hasattr(shape.Curve,'Radius'):
point = shape.Curve.Center
# as fall-back, snap to center of bounding box
elif hasattr(shape,'BoundBox'):
point = shape.BoundBox.Center
else:
self.printResult('Invalid shape\n'+str(shape))
return point
# measure the coordinates of a single point
def measureCoords(self, vertex ):
global taskUI
point = None
if self.isVector(vertex):
point = vertex
elif hasattr(vertex,'isValid') and vertex.isValid() \
and hasattr(vertex,'Vertexes') \
and len(vertex.Vertexes) > 0:
point = vertex.Vertexes[0].Point
else:
self.printResult('Not a valid point\n'+str(vertex))
if point:
#self.printResult( 'Measuring coordinates of\n'+str(vertex) )
anno = ['Coordinates :', 'X : '+self.arrondi(point.x), 'Y : '+self.arrondi(point.y), 'Z : '+self.arrondi(point.z)]
text = 'Coordinates :\n'
text += "X : "+str(point.x)+"\n"
text += 'Y : '+str(point.y)+'\n'
text += 'Z : '+str(point.z)
self.printResult(text)
if taskUI.bLabel.isChecked():
self.drawAnnotation( point, anno )
def measureArea(self, face ):
if face.isValid() and hasattr(face,'Area'):
if self.isFlatFace(face):
self.printResult('Flat face\nArea : '+str(face.Area)+'\n')
else:
self.printResult('Area : '+str(face.Area)+"\n")
else:
self.printResult('Not a valid surface\n'+str(face) )
def printDims(self, ds, dx, dy, dz, dimType='Distance'):
text = dimType+' : '+str(ds)
text += "\nΔX = "+str(dx)+"\nΔY = "+str(dy)+"\nΔZ = "+str(dz)
self.printResult(text)
def printAngle(self, angle, distance=-1 ):
global taskUI
taskUI.resultText.clear()
text = 'Angle : '+str(angle)+'°\n'
if distance != -1:
text += 'Distance // '+str(distance)
taskUI.resultText.setPlainText(text)
# print the result in the text field of the UI
def printResult(self,text):
global taskUI
taskUI.resultText.clear()
taskUI.resultText.setPlainText(text)
def drawAnnotation(self, pos, textTable ):
anno = App.ActiveDocument.addObject("App::AnnotationLabel","MeasureLbl")
anno.BasePosition = pos
# textTable is a table if strings: [ 'toto', 'titi', 'tata' ]
anno.LabelText = textTable
annoG = Gui.ActiveDocument.getObject(anno.Name)
annoG.FontSize = annoFontSize
self.addToDims(anno)
def drawCircle( self, radius, center, axis ):
global taskUI
cc = Part.makeCircle( radius, center, axis )
circle = App.ActiveDocument.addObject('Part::FeaturePython', 'aCircle')
#circle.ViewObject.Proxy = setCustomIcon(circle,'Draft_Circle.svg')
circle.ViewObject.Proxy = setCustomIcon( circle, taskUI.circleIcon )
circle.Shape = Part.Wire( cc )
circle.ViewObject.LineWidth = 5
circle.ViewObject.LineColor = ( 1.0, 1.0, 1.0 )
circle.ViewObject.PointSize = 10
circle.ViewObject.PointColor= ( 0.0, 0.0, 1.0 )
self.addToDims(circle)
def drawDim( self, pt1, pt2, name='aDim', width=2 ):
global taskUI
if pt1!=pt2:
# unit direction vector
vDir = App.Vector(pt2.sub(pt1))
uV = vDir.multiply(1/vDir.Length)
#setup the contour
color = coin.SoBaseColor()
color.rgb = (1, 1, 1)
points=coin.SoCoordinate3()
lines=coin.SoLineSet()
points.point.values = ( (0,0,0),(10,10,10),(10,10,0) )
#feed data to separator
sep=coin.SoSeparator()
sep.addChild(points)
sep.addChild(color)
sep.addChild(lines)
#add separator to sceneGraph
sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
sg.addChild(sep)