/
PathSurface.py
2128 lines (1858 loc) · 91.2 KB
/
PathSurface.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) 2016 sliptonic <shopinthewoods@gmail.com> *
# * *
# * 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 *
# * *
# ***************************************************************************
from __future__ import print_function
__title__ = "Path Surface Operation"
__author__ = "sliptonic (Brad Collette)"
__url__ = "http://www.freecadweb.org"
__doc__ = "Class and implementation of 3D Surface operation."
__contributors__ = "russ4262 (Russell Johnson)"
import FreeCAD
from PySide import QtCore
# OCL must be installed
try:
import ocl
except ImportError:
msg = QtCore.QCoreApplication.translate("PathSurface",
"This operation requires OpenCamLib to be installed.")
FreeCAD.Console.PrintError(msg + "\n")
raise ImportError
# import sys
# sys.exit(msg)
import Path
import PathScripts.PathLog as PathLog
import PathScripts.PathUtils as PathUtils
import PathScripts.PathOp as PathOp
import PathScripts.PathSurfaceSupport as PathSurfaceSupport
import time
import math
# lazily loaded modules
from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')
if FreeCAD.GuiUp:
import FreeCADGui
PathLog.setLevel(PathLog.Level.INFO, PathLog.thisModule())
# PathLog.trackModule(PathLog.thisModule())
# Qt translation handling
def translate(context, text, disambig=None):
return QtCore.QCoreApplication.translate(context, text, disambig)
class ObjectSurface(PathOp.ObjectOp):
'''Proxy object for Surfacing operation.'''
def opFeatures(self, obj):
'''opFeatures(obj) ... return all standard features'''
return PathOp.FeatureTool | PathOp.FeatureDepths \
| PathOp.FeatureHeights | PathOp.FeatureStepDown \
| PathOp.FeatureCoolant | PathOp.FeatureBaseFaces
def initOperation(self, obj):
'''initOperation(obj) ... Initialize the operation by
managing property creation and property editor status.'''
self.propertiesReady = False
self.initOpProperties(obj) # Initialize operation-specific properties
# For debugging
if PathLog.getLevel(PathLog.thisModule()) != 4:
obj.setEditorMode('ShowTempObjects', 2) # hide
if not hasattr(obj, 'DoNotSetDefaultValues'):
self.setEditorProperties(obj)
def initOpProperties(self, obj, warn=False):
'''initOpProperties(obj) ... create operation specific properties'''
self.addNewProps = list()
for (prtyp, nm, grp, tt) in self.opPropertyDefinitions():
if not hasattr(obj, nm):
obj.addProperty(prtyp, nm, grp, tt)
self.addNewProps.append(nm)
# Set enumeration lists for enumeration properties
if len(self.addNewProps) > 0:
ENUMS = self.opPropertyEnumerations()
for n in ENUMS:
if n in self.addNewProps:
setattr(obj, n, ENUMS[n])
if warn:
newPropMsg = translate('PathSurface', 'New property added to')
newPropMsg += ' "{}": {}'.format(obj.Label, self.addNewProps) + '. '
newPropMsg += translate('PathSurface', 'Check default value(s).')
FreeCAD.Console.PrintWarning(newPropMsg + '\n')
self.propertiesReady = True
def opPropertyDefinitions(self):
'''opPropertyDefinitions(obj) ... Store operation specific properties'''
return [
("App::PropertyBool", "ShowTempObjects", "Debug",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Show the temporary path construction objects when module is in DEBUG mode.")),
("App::PropertyDistance", "AngularDeflection", "Mesh Conversion",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Smaller values yield a finer, more accurate mesh. Smaller values increase processing time a lot.")),
("App::PropertyDistance", "LinearDeflection", "Mesh Conversion",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Smaller values yield a finer, more accurate mesh. Smaller values do not increase processing time much.")),
("App::PropertyFloat", "CutterTilt", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Stop index(angle) for rotational scan")),
("App::PropertyEnumeration", "DropCutterDir", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Dropcutter lines are created parallel to this axis.")),
("App::PropertyVectorDistance", "DropCutterExtraOffset", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Additional offset to the selected bounding box")),
("App::PropertyEnumeration", "RotationAxis", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "The model will be rotated around this axis.")),
("App::PropertyFloat", "StartIndex", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Start index(angle) for rotational scan")),
("App::PropertyFloat", "StopIndex", "Rotation",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Stop index(angle) for rotational scan")),
("App::PropertyEnumeration", "ScanType", "Surface",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Planar: Flat, 3D surface scan. Rotational: 4th-axis rotational scan.")),
("App::PropertyInteger", "AvoidLastX_Faces", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Avoid cutting the last 'N' faces in the Base Geometry list of selected faces.")),
("App::PropertyBool", "AvoidLastX_InternalFeatures", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Do not cut internal features on avoided faces.")),
("App::PropertyDistance", "BoundaryAdjustment", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Positive values push the cutter toward, or beyond, the boundary. Negative values retract the cutter away from the boundary.")),
("App::PropertyBool", "BoundaryEnforcement", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "If true, the cutter will remain inside the boundaries of the model or selected face(s).")),
("App::PropertyEnumeration", "HandleMultipleFeatures", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Choose how to process multiple Base Geometry features.")),
("App::PropertyDistance", "InternalFeaturesAdjustment", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Positive values push the cutter toward, or into, the feature. Negative values retract the cutter away from the feature.")),
("App::PropertyBool", "InternalFeaturesCut", "Selected Geometry Settings",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Cut internal feature areas within a larger selected face.")),
("App::PropertyEnumeration", "BoundBox", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Select the overall boundary for the operation.")),
("App::PropertyEnumeration", "CutMode", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the direction for the cutting tool to engage the material: Climb (ClockWise) or Conventional (CounterClockWise)")),
("App::PropertyEnumeration", "CutPattern", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the geometric clearing pattern to use for the operation.")),
("App::PropertyFloat", "CutPatternAngle", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "The yaw angle used for certain clearing patterns")),
("App::PropertyBool", "CutPatternReversed", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Reverse the cut order of the stepover paths. For circular cut patterns, begin at the outside and work toward the center.")),
("App::PropertyDistance", "DepthOffset", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the Z-axis depth offset from the target surface.")),
("App::PropertyEnumeration", "LayerMode", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Complete the operation in a single pass at depth, or mulitiple passes to final depth.")),
("App::PropertyVectorDistance", "PatternCenterCustom", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the start point for the cut pattern.")),
("App::PropertyEnumeration", "PatternCenterAt", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Choose location of the center point for starting the cut pattern.")),
("App::PropertyEnumeration", "ProfileEdges", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Profile the edges of the selection.")),
("App::PropertyDistance", "SampleInterval", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the sampling resolution. Smaller values quickly increase processing time.")),
("App::PropertyFloat", "StepOver", "Clearing Options",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Set the stepover percentage, based on the tool's diameter.")),
("App::PropertyBool", "OptimizeLinearPaths", "Optimization",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Enable optimization of linear paths (co-linear points). Removes unnecessary co-linear points from G-Code output.")),
("App::PropertyBool", "OptimizeStepOverTransitions", "Optimization",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Enable separate optimization of transitions between, and breaks within, each step over path.")),
("App::PropertyBool", "CircularUseG2G3", "Optimization",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Convert co-planar arcs to G2/G3 gcode commands for `Circular` and `CircularZigZag` cut patterns.")),
("App::PropertyDistance", "GapThreshold", "Optimization",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Collinear and co-radial artifact gaps that are smaller than this threshold are closed in the path.")),
("App::PropertyString", "GapSizes", "Optimization",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Feedback: three smallest gaps identified in the path geometry.")),
("App::PropertyVectorDistance", "StartPoint", "Start Point",
QtCore.QT_TRANSLATE_NOOP("App::Property", "The custom start point for the path of this operation")),
("App::PropertyBool", "UseStartPoint", "Start Point",
QtCore.QT_TRANSLATE_NOOP("App::Property", "Make True, if specifying a Start Point"))
]
def opPropertyEnumerations(self):
# Enumeration lists for App::PropertyEnumeration properties
return {
'BoundBox': ['BaseBoundBox', 'Stock'],
'PatternCenterAt': ['CenterOfMass', 'CenterOfBoundBox', 'XminYmin', 'Custom'],
'CutMode': ['Conventional', 'Climb'],
'CutPattern': ['Circular', 'CircularZigZag', 'Line', 'Offset', 'Spiral', 'ZigZag'], # Additional goals ['Offset', 'ZigZagOffset', 'Grid', 'Triangle']
'DropCutterDir': ['X', 'Y'],
'HandleMultipleFeatures': ['Collectively', 'Individually'],
'LayerMode': ['Single-pass', 'Multi-pass'],
'ProfileEdges': ['None', 'Only', 'First', 'Last'],
'RotationAxis': ['X', 'Y'],
'ScanType': ['Planar', 'Rotational']
}
def opPropertyDefaults(self, obj, job):
'''opPropertyDefaults(obj, job) ... returns a dictionary of default values
for the operation's properties.'''
defaults = {
'OptimizeLinearPaths': True,
'InternalFeaturesCut': True,
'OptimizeStepOverTransitions': False,
'CircularUseG2G3': False,
'BoundaryEnforcement': True,
'UseStartPoint': False,
'AvoidLastX_InternalFeatures': True,
'CutPatternReversed': False,
'StartPoint': FreeCAD.Vector(0.0, 0.0, obj.ClearanceHeight.Value),
'ProfileEdges': 'None',
'LayerMode': 'Single-pass',
'ScanType': 'Planar',
'RotationAxis': 'X',
'CutMode': 'Conventional',
'CutPattern': 'Line',
'HandleMultipleFeatures': 'Collectively',
'PatternCenterAt': 'CenterOfMass',
'GapSizes': 'No gaps identified.',
'StepOver': 100.0,
'CutPatternAngle': 0.0,
'CutterTilt': 0.0,
'StartIndex': 0.0,
'StopIndex': 360.0,
'SampleInterval': 1.0,
'BoundaryAdjustment': 0.0,
'InternalFeaturesAdjustment': 0.0,
'AvoidLastX_Faces': 0,
'PatternCenterCustom': FreeCAD.Vector(0.0, 0.0, 0.0),
'GapThreshold': 0.005,
'AngularDeflection': 0.25, # AngularDeflection is unused
# Reasonable compromise between speed & precision
'LinearDeflection': 0.001,
# For debugging
'ShowTempObjects': False
}
warn = True
if hasattr(job, 'GeometryTolerance'):
if job.GeometryTolerance.Value != 0.0:
warn = False
# Tessellation precision dictates the offsets we need to add to
# avoid false collisions with the model mesh, so make sure we
# default to tessellating with greater precision than the target
# GeometryTolerance.
defaults['LinearDeflection'] = job.GeometryTolerance.Value / 4
if warn:
msg = translate('PathSurface',
'The GeometryTolerance for this Job is 0.0.')
msg += translate('PathSurface',
'Initializing LinearDeflection to 0.001 mm.')
FreeCAD.Console.PrintWarning(msg + '\n')
return defaults
def setEditorProperties(self, obj):
# Used to hide inputs in properties list
P0 = R2 = 0 # 0 = show
P2 = R0 = 2 # 2 = hide
if obj.ScanType == 'Planar':
# if obj.CutPattern in ['Line', 'ZigZag']:
if obj.CutPattern in ['Circular', 'CircularZigZag', 'Spiral']:
P0 = 2
P2 = 0
elif obj.CutPattern == 'Offset':
P0 = 2
elif obj.ScanType == 'Rotational':
R2 = P0 = P2 = 2
R0 = 0
obj.setEditorMode('DropCutterDir', R0)
obj.setEditorMode('DropCutterExtraOffset', R0)
obj.setEditorMode('RotationAxis', R0)
obj.setEditorMode('StartIndex', R0)
obj.setEditorMode('StopIndex', R0)
obj.setEditorMode('CutterTilt', R0)
obj.setEditorMode('CutPattern', R2)
obj.setEditorMode('CutPatternAngle', P0)
obj.setEditorMode('PatternCenterAt', P2)
obj.setEditorMode('PatternCenterCustom', P2)
def onChanged(self, obj, prop):
if hasattr(self, 'propertiesReady'):
if self.propertiesReady:
if prop in ['ScanType', 'CutPattern']:
self.setEditorProperties(obj)
def opOnDocumentRestored(self, obj):
self.propertiesReady = False
job = PathUtils.findParentJob(obj)
self.initOpProperties(obj, warn=True)
self.opApplyPropertyDefaults(obj, job, self.addNewProps)
mode = 2 if PathLog.getLevel(PathLog.thisModule()) != 4 else 0
obj.setEditorMode('ShowTempObjects', mode)
# Repopulate enumerations in case of changes
ENUMS = self.opPropertyEnumerations()
for n in ENUMS:
restore = False
if hasattr(obj, n):
val = obj.getPropertyByName(n)
restore = True
setattr(obj, n, ENUMS[n])
if restore:
setattr(obj, n, val)
self.setEditorProperties(obj)
def opApplyPropertyDefaults(self, obj, job, propList):
# Set standard property defaults
PROP_DFLTS = self.opPropertyDefaults(obj, job)
for n in PROP_DFLTS:
if n in propList:
prop = getattr(obj, n)
val = PROP_DFLTS[n]
setVal = False
if hasattr(prop, 'Value'):
if isinstance(val, int) or isinstance(val, float):
setVal = True
if setVal:
setattr(prop, 'Value', val)
else:
setattr(obj, n, val)
def opSetDefaultValues(self, obj, job):
'''opSetDefaultValues(obj, job) ... initialize defaults'''
job = PathUtils.findParentJob(obj)
self.opApplyPropertyDefaults(obj, job, self.addNewProps)
# need to overwrite the default depth calculations for facing
d = None
if job:
if job.Stock:
d = PathUtils.guessDepths(job.Stock.Shape, None)
PathLog.debug("job.Stock exists")
else:
PathLog.debug("job.Stock NOT exist")
else:
PathLog.debug("job NOT exist")
if d is not None:
obj.OpFinalDepth.Value = d.final_depth
obj.OpStartDepth.Value = d.start_depth
else:
obj.OpFinalDepth.Value = -10
obj.OpStartDepth.Value = 10
PathLog.debug('Default OpFinalDepth: {}'.format(obj.OpFinalDepth.Value))
PathLog.debug('Defualt OpStartDepth: {}'.format(obj.OpStartDepth.Value))
def opApplyPropertyLimits(self, obj):
'''opApplyPropertyLimits(obj) ... Apply necessary limits to user input property values before performing main operation.'''
# Limit start index
if obj.StartIndex < 0.0:
obj.StartIndex = 0.0
if obj.StartIndex > 360.0:
obj.StartIndex = 360.0
# Limit stop index
if obj.StopIndex > 360.0:
obj.StopIndex = 360.0
if obj.StopIndex < 0.0:
obj.StopIndex = 0.0
# Limit cutter tilt
if obj.CutterTilt < -90.0:
obj.CutterTilt = -90.0
if obj.CutterTilt > 90.0:
obj.CutterTilt = 90.0
# Limit sample interval
if obj.SampleInterval.Value < 0.0001:
obj.SampleInterval.Value = 0.0001
PathLog.error(translate('PathSurface', 'Sample interval limits are 0.001 to 25.4 millimeters.'))
if obj.SampleInterval.Value > 25.4:
obj.SampleInterval.Value = 25.4
PathLog.error(translate('PathSurface', 'Sample interval limits are 0.001 to 25.4 millimeters.'))
# Limit cut pattern angle
if obj.CutPatternAngle < -360.0:
obj.CutPatternAngle = 0.0
PathLog.error(translate('PathSurface', 'Cut pattern angle limits are +-360 degrees.'))
if obj.CutPatternAngle >= 360.0:
obj.CutPatternAngle = 0.0
PathLog.error(translate('PathSurface', 'Cut pattern angle limits are +- 360 degrees.'))
# Limit StepOver to natural number percentage
if obj.StepOver > 100.0:
obj.StepOver = 100.0
if obj.StepOver < 1.0:
obj.StepOver = 1.0
# Limit AvoidLastX_Faces to zero and positive values
if obj.AvoidLastX_Faces < 0:
obj.AvoidLastX_Faces = 0
PathLog.error(translate('PathSurface', 'AvoidLastX_Faces: Only zero or positive values permitted.'))
if obj.AvoidLastX_Faces > 100:
obj.AvoidLastX_Faces = 100
PathLog.error(translate('PathSurface', 'AvoidLastX_Faces: Avoid last X faces count limited to 100.'))
def opUpdateDepths(self, obj):
if hasattr(obj, 'Base') and obj.Base:
base, sublist = obj.Base[0]
fbb = base.Shape.getElement(sublist[0]).BoundBox
zmin = fbb.ZMax
for base, sublist in obj.Base:
for sub in sublist:
try:
fbb = base.Shape.getElement(sub).BoundBox
zmin = min(zmin, fbb.ZMin)
except Part.OCCError as e:
PathLog.error(e)
obj.OpFinalDepth = zmin
elif self.job:
if hasattr(obj, 'BoundBox'):
if obj.BoundBox == 'BaseBoundBox':
models = self.job.Model.Group
zmin = models[0].Shape.BoundBox.ZMin
for M in models:
zmin = min(zmin, M.Shape.BoundBox.ZMin)
obj.OpFinalDepth = zmin
if obj.BoundBox == 'Stock':
models = self.job.Stock
obj.OpFinalDepth = self.job.Stock.Shape.BoundBox.ZMin
def opExecute(self, obj):
'''opExecute(obj) ... process surface operation'''
PathLog.track()
self.modelSTLs = list()
self.safeSTLs = list()
self.modelTypes = list()
self.boundBoxes = list()
self.profileShapes = list()
self.collectiveShapes = list()
self.individualShapes = list()
self.avoidShapes = list()
self.tempGroup = None
self.CutClimb = False
self.closedGap = False
self.tmpCOM = None
self.gaps = [0.1, 0.2, 0.3]
self.cancelOperation = False
CMDS = list()
modelVisibility = list()
FCAD = FreeCAD.ActiveDocument
try:
dotIdx = __name__.index('.') + 1
except Exception:
dotIdx = 0
self.module = __name__[dotIdx:]
# Set debugging behavior
self.showDebugObjects = False # Set to true if you want a visual DocObjects created for some path construction objects
self.showDebugObjects = obj.ShowTempObjects
deleteTempsFlag = True # Set to False for debugging
if PathLog.getLevel(PathLog.thisModule()) == 4:
deleteTempsFlag = False
else:
self.showDebugObjects = False
# mark beginning of operation and identify parent Job
startTime = time.time()
# Identify parent Job
JOB = PathUtils.findParentJob(obj)
self.JOB = JOB
if JOB is None:
PathLog.error(translate('PathSurface', "No JOB"))
return
self.stockZMin = JOB.Stock.Shape.BoundBox.ZMin
# set cut mode; reverse as needed
if obj.CutMode == 'Climb':
self.CutClimb = True
if obj.CutPatternReversed is True:
if self.CutClimb is True:
self.CutClimb = False
else:
self.CutClimb = True
# Instantiate additional class operation variables
self.resetOpVariables()
# Setup cutter for OCL and cutout value for operation - based on tool controller properties
oclTool = PathSurfaceSupport.OCL_Tool(ocl, obj)
self.cutter = oclTool.getOclTool()
if not self.cutter:
PathLog.error(translate('PathSurface', "Canceling 3D Surface operation. Error creating OCL cutter."))
return
self.toolDiam = self.cutter.getDiameter() # oclTool.diameter
self.radius = self.toolDiam / 2.0
self.useTiltCutter = oclTool.useTiltCutter()
self.cutOut = (self.toolDiam * (float(obj.StepOver) / 100.0))
self.gaps = [self.toolDiam, self.toolDiam, self.toolDiam]
# Begin GCode for operation with basic information
# ... and move cutter to clearance height and startpoint
output = ''
if obj.Comment != '':
self.commandlist.append(Path.Command('N ({})'.format(str(obj.Comment)), {}))
self.commandlist.append(Path.Command('N ({})'.format(obj.Label), {}))
self.commandlist.append(Path.Command('N (Tool type: {})'.format(oclTool.toolType), {}))
self.commandlist.append(Path.Command('N (Compensated Tool Path. Diameter: {})'.format(oclTool.diameter), {}))
self.commandlist.append(Path.Command('N (Sample interval: {})'.format(str(obj.SampleInterval.Value)), {}))
self.commandlist.append(Path.Command('N (Step over %: {})'.format(str(obj.StepOver)), {}))
self.commandlist.append(Path.Command('N ({})'.format(output), {}))
self.commandlist.append(Path.Command('G0', {'Z': obj.ClearanceHeight.Value, 'F': self.vertRapid}))
if obj.UseStartPoint is True:
self.commandlist.append(Path.Command('G0', {'X': obj.StartPoint.x, 'Y': obj.StartPoint.y, 'F': self.horizRapid}))
# Impose property limits
self.opApplyPropertyLimits(obj)
# Create temporary group for temporary objects, removing existing
tempGroupName = 'tempPathSurfaceGroup'
if FCAD.getObject(tempGroupName):
for to in FCAD.getObject(tempGroupName).Group:
FCAD.removeObject(to.Name)
FCAD.removeObject(tempGroupName) # remove temp directory if already exists
if FCAD.getObject(tempGroupName + '001'):
for to in FCAD.getObject(tempGroupName + '001').Group:
FCAD.removeObject(to.Name)
FCAD.removeObject(tempGroupName + '001') # remove temp directory if already exists
tempGroup = FCAD.addObject('App::DocumentObjectGroup', tempGroupName)
tempGroupName = tempGroup.Name
self.tempGroup = tempGroup
tempGroup.purgeTouched()
# Add temp object to temp group folder with following code:
# ... self.tempGroup.addObject(OBJ)
# Get height offset values for later use
self.SafeHeightOffset = JOB.SetupSheet.SafeHeightOffset.Value
self.ClearHeightOffset = JOB.SetupSheet.ClearanceHeightOffset.Value
# Calculate default depthparams for operation
self.depthParams = PathUtils.depth_params(obj.ClearanceHeight.Value, obj.SafeHeight.Value, obj.StartDepth.Value, obj.StepDown.Value, 0.0, obj.FinalDepth.Value)
self.midDep = (obj.StartDepth.Value + obj.FinalDepth.Value) / 2.0
# Save model visibilities for restoration
if FreeCAD.GuiUp:
for m in range(0, len(JOB.Model.Group)):
mNm = JOB.Model.Group[m].Name
modelVisibility.append(FreeCADGui.ActiveDocument.getObject(mNm).Visibility)
# Setup STL, model type, and bound box containers for each model in Job
for m in range(0, len(JOB.Model.Group)):
M = JOB.Model.Group[m]
self.modelSTLs.append(False)
self.safeSTLs.append(False)
self.profileShapes.append(False)
# Set bound box
if obj.BoundBox == 'BaseBoundBox':
if M.TypeId.startswith('Mesh'):
self.modelTypes.append('M') # Mesh
self.boundBoxes.append(M.Mesh.BoundBox)
else:
self.modelTypes.append('S') # Solid
self.boundBoxes.append(M.Shape.BoundBox)
elif obj.BoundBox == 'Stock':
self.modelTypes.append('S') # Solid
self.boundBoxes.append(JOB.Stock.Shape.BoundBox)
# ###### MAIN COMMANDS FOR OPERATION ######
# Begin processing obj.Base data and creating GCode
PSF = PathSurfaceSupport.ProcessSelectedFaces(JOB, obj)
PSF.setShowDebugObjects(tempGroup, self.showDebugObjects)
PSF.radius = self.radius
PSF.depthParams = self.depthParams
pPM = PSF.preProcessModel(self.module)
# Process selected faces, if available
if pPM:
self.cancelOperation = False
(FACES, VOIDS) = pPM
self.modelSTLs = PSF.modelSTLs
self.profileShapes = PSF.profileShapes
for m in range(0, len(JOB.Model.Group)):
# Create OCL.stl model objects
PathSurfaceSupport._prepareModelSTLs(self, JOB, obj, m, ocl)
Mdl = JOB.Model.Group[m]
if FACES[m]:
PathLog.debug('Working on Model.Group[{}]: {}'.format(m, Mdl.Label))
if m > 0:
# Raise to clearance between models
CMDS.append(Path.Command('N (Transition to base: {}.)'.format(Mdl.Label)))
CMDS.append(Path.Command('G0', {'Z': obj.ClearanceHeight.Value, 'F': self.vertRapid}))
# make stock-model-voidShapes STL model for avoidance detection on transitions
PathSurfaceSupport._makeSafeSTL(self, JOB, obj, m, FACES[m], VOIDS[m], ocl)
# Process model/faces - OCL objects must be ready
CMDS.extend(self._processCutAreas(JOB, obj, m, FACES[m], VOIDS[m]))
else:
PathLog.debug('No data for model base: {}'.format(JOB.Model.Group[m].Label))
# Save gcode produced
self.commandlist.extend(CMDS)
else:
PathLog.error('Failed to pre-process model and/or selected face(s).')
# ###### CLOSING COMMANDS FOR OPERATION ######
# Delete temporary objects
# Restore model visibilities for restoration
if FreeCAD.GuiUp:
FreeCADGui.ActiveDocument.getObject(tempGroupName).Visibility = False
for m in range(0, len(JOB.Model.Group)):
M = JOB.Model.Group[m]
M.Visibility = modelVisibility[m]
if deleteTempsFlag is True:
for to in tempGroup.Group:
if hasattr(to, 'Group'):
for go in to.Group:
FCAD.removeObject(go.Name)
FCAD.removeObject(to.Name)
FCAD.removeObject(tempGroupName)
else:
if len(tempGroup.Group) == 0:
FCAD.removeObject(tempGroupName)
else:
tempGroup.purgeTouched()
# Provide user feedback for gap sizes
gaps = list()
for g in self.gaps:
if g != self.toolDiam:
gaps.append(g)
if len(gaps) > 0:
obj.GapSizes = '{} mm'.format(gaps)
else:
if self.closedGap is True:
obj.GapSizes = 'Closed gaps < Gap Threshold.'
else:
obj.GapSizes = 'No gaps identified.'
# clean up class variables
self.resetOpVariables()
self.deleteOpVariables()
self.modelSTLs = None
self.safeSTLs = None
self.modelTypes = None
self.boundBoxes = None
self.gaps = None
self.closedGap = None
self.SafeHeightOffset = None
self.ClearHeightOffset = None
self.depthParams = None
self.midDep = None
del self.modelSTLs
del self.safeSTLs
del self.modelTypes
del self.boundBoxes
del self.gaps
del self.closedGap
del self.SafeHeightOffset
del self.ClearHeightOffset
del self.depthParams
del self.midDep
execTime = time.time() - startTime
if execTime > 60.0:
tMins = math.floor(execTime / 60.0)
tSecs = execTime - (tMins * 60.0)
exTime = str(tMins) + ' min. ' + str(round(tSecs, 5)) + ' sec.'
else:
exTime = str(round(execTime, 5)) + ' sec.'
msg = translate('PathSurface', 'operation time is')
FreeCAD.Console.PrintMessage('3D Surface ' + msg + ' {}\n'.format(exTime))
if self.cancelOperation:
FreeCAD.ActiveDocument.openTransaction(translate("PathSurface", "Canceled 3D Surface operation."))
FreeCAD.ActiveDocument.removeObject(obj.Name)
FreeCAD.ActiveDocument.commitTransaction()
return True
# Methods for constructing the cut area and creating path geometry
def _processCutAreas(self, JOB, obj, mdlIdx, FCS, VDS):
'''_processCutAreas(JOB, obj, mdlIdx, FCS, VDS)...
This method applies any avoided faces or regions to the selected faces.
It then calls the correct scan method depending on the ScanType property.'''
PathLog.debug('_processCutAreas()')
final = list()
# Process faces Collectively or Individually
if obj.HandleMultipleFeatures == 'Collectively':
if FCS is True:
COMP = False
else:
ADD = Part.makeCompound(FCS)
if VDS is not False:
DEL = Part.makeCompound(VDS)
COMP = ADD.cut(DEL)
else:
COMP = ADD
if obj.ScanType == 'Planar':
final.extend(self._processPlanarOp(JOB, obj, mdlIdx, COMP, 0))
elif obj.ScanType == 'Rotational':
final.extend(self._processRotationalOp(JOB, obj, mdlIdx, COMP))
elif obj.HandleMultipleFeatures == 'Individually':
for fsi in range(0, len(FCS)):
fShp = FCS[fsi]
# self.deleteOpVariables(all=False)
self.resetOpVariables(all=False)
if fShp is True:
COMP = False
else:
ADD = Part.makeCompound([fShp])
if VDS is not False:
DEL = Part.makeCompound(VDS)
COMP = ADD.cut(DEL)
else:
COMP = ADD
if obj.ScanType == 'Planar':
final.extend(self._processPlanarOp(JOB, obj, mdlIdx, COMP, fsi))
elif obj.ScanType == 'Rotational':
final.extend(self._processRotationalOp(JOB, obj, mdlIdx, COMP))
COMP = None
# Eif
return final
def _processPlanarOp(self, JOB, obj, mdlIdx, cmpdShp, fsi):
'''_processPlanarOp(JOB, obj, mdlIdx, cmpdShp)...
This method compiles the main components for the procedural portion of a planar operation (non-rotational).
It creates the OCL PathDropCutter objects: model and safeTravel.
It makes the necessary facial geometries for the actual cut area.
It calls the correct Single or Multi-pass method as needed.
It returns the gcode for the operation. '''
PathLog.debug('_processPlanarOp()')
final = list()
SCANDATA = list()
def getTransition(two):
first = two[0][0][0] # [step][item][point]
safe = obj.SafeHeight.Value + 0.1
trans = [[FreeCAD.Vector(first.x, first.y, safe)]]
return trans
# Compute number and size of stepdowns, and final depth
if obj.LayerMode == 'Single-pass':
depthparams = [obj.FinalDepth.Value]
elif obj.LayerMode == 'Multi-pass':
depthparams = [i for i in self.depthParams]
lenDP = len(depthparams)
# Prepare PathDropCutter objects with STL data
pdc = self._planarGetPDC(self.modelSTLs[mdlIdx], depthparams[lenDP - 1], obj.SampleInterval.Value, self.cutter)
safePDC = self._planarGetPDC(self.safeSTLs[mdlIdx], depthparams[lenDP - 1], obj.SampleInterval.Value, self.cutter)
profScan = list()
if obj.ProfileEdges != 'None':
prflShp = self.profileShapes[mdlIdx][fsi]
if prflShp is False:
msg = translate('PathSurface', 'No profile geometry shape returned.')
PathLog.error(msg)
return list()
self.showDebugObject(prflShp, 'NewProfileShape')
# get offset path geometry and perform OCL scan with that geometry
pathOffsetGeom = self._offsetFacesToPointData(obj, prflShp)
if pathOffsetGeom is False:
msg = translate('PathSurface', 'No profile path geometry returned.')
PathLog.error(msg)
return list()
profScan = [self._planarPerformOclScan(obj, pdc, pathOffsetGeom, True)]
geoScan = list()
if obj.ProfileEdges != 'Only':
self.showDebugObject(cmpdShp, 'CutArea')
# get internal path geometry and perform OCL scan with that geometry
PGG = PathSurfaceSupport.PathGeometryGenerator(obj, cmpdShp, obj.CutPattern)
if self.showDebugObjects:
PGG.setDebugObjectsGroup(self.tempGroup)
self.tmpCOM = PGG.getCenterOfPattern()
pathGeom = PGG.generatePathGeometry()
if pathGeom is False:
msg = translate('PathSurface', 'No clearing shape returned.')
PathLog.error(msg)
return list()
if obj.CutPattern == 'Offset':
useGeom = self._offsetFacesToPointData(obj, pathGeom, profile=False)
if useGeom is False:
msg = translate('PathSurface', 'No clearing path geometry returned.')
PathLog.error(msg)
return list()
geoScan = [self._planarPerformOclScan(obj, pdc, useGeom, True)]
else:
geoScan = self._planarPerformOclScan(obj, pdc, pathGeom, False)
if obj.ProfileEdges == 'Only': # ['None', 'Only', 'First', 'Last']
SCANDATA.extend(profScan)
if obj.ProfileEdges == 'None':
SCANDATA.extend(geoScan)
if obj.ProfileEdges == 'First':
profScan.append(getTransition(geoScan))
SCANDATA.extend(profScan)
SCANDATA.extend(geoScan)
if obj.ProfileEdges == 'Last':
SCANDATA.extend(geoScan)
SCANDATA.extend(profScan)
if len(SCANDATA) == 0:
msg = translate('PathSurface', 'No scan data to convert to Gcode.')
PathLog.error(msg)
return list()
# Apply depth offset
if obj.DepthOffset.Value != 0.0:
self._planarApplyDepthOffset(SCANDATA, obj.DepthOffset.Value)
# If cut pattern is `Circular`, there are zero(almost zero) straight lines to optimize
# Store initial `OptimizeLinearPaths` value for later restoration
self.preOLP = obj.OptimizeLinearPaths
if obj.CutPattern in ['Circular', 'CircularZigZag']:
obj.OptimizeLinearPaths = False
# Process OCL scan data
if obj.LayerMode == 'Single-pass':
final.extend(self._planarDropCutSingle(JOB, obj, pdc, safePDC, depthparams, SCANDATA))
elif obj.LayerMode == 'Multi-pass':
final.extend(self._planarDropCutMulti(JOB, obj, pdc, safePDC, depthparams, SCANDATA))
# If cut pattern is `Circular`, restore initial OLP value
if obj.CutPattern in ['Circular', 'CircularZigZag']:
obj.OptimizeLinearPaths = self.preOLP
# Raise to safe height between individual faces.
if obj.HandleMultipleFeatures == 'Individually':
final.insert(0, Path.Command('G0', {'Z': obj.SafeHeight.Value, 'F': self.vertRapid}))
return final
def _offsetFacesToPointData(self, obj, subShp, profile=True):
PathLog.debug('_offsetFacesToPointData()')
offsetLists = list()
dist = obj.SampleInterval.Value / 5.0
# defl = obj.SampleInterval.Value / 5.0
if not profile:
# Reverse order of wires in each face - inside to outside
for w in range(len(subShp.Wires) - 1, -1, -1):
W = subShp.Wires[w]
PNTS = W.discretize(Distance=dist)
# PNTS = W.discretize(Deflection=defl)
if self.CutClimb:
PNTS.reverse()
offsetLists.append(PNTS)
else:
# Reference https://forum.freecadweb.org/viewtopic.php?t=28861#p234939
for fc in subShp.Faces:
# Reverse order of wires in each face - inside to outside
for w in range(len(fc.Wires) - 1, -1, -1):
W = fc.Wires[w]
PNTS = W.discretize(Distance=dist)
# PNTS = W.discretize(Deflection=defl)
if self.CutClimb:
PNTS.reverse()
offsetLists.append(PNTS)
return offsetLists
def _planarPerformOclScan(self, obj, pdc, pathGeom, offsetPoints=False):
'''_planarPerformOclScan(obj, pdc, pathGeom, offsetPoints=False)...
Switching function for calling the appropriate path-geometry to OCL points conversion function
for the various cut patterns.'''
PathLog.debug('_planarPerformOclScan()')
SCANS = list()
if offsetPoints or obj.CutPattern == 'Offset':
PNTSET = PathSurfaceSupport.pathGeomToOffsetPointSet(obj, pathGeom)
for D in PNTSET:
stpOvr = list()
ofst = list()
for I in D:
if I == 'BRK':
stpOvr.append(ofst)
stpOvr.append(I)
ofst = list()
else:
# D format is ((p1, p2), (p3, p4))
(A, B) = I
ofst.extend(self._planarDropCutScan(pdc, A, B))
if len(ofst) > 0:
stpOvr.append(ofst)
SCANS.extend(stpOvr)
elif obj.CutPattern in ['Line', 'Spiral', 'ZigZag']:
stpOvr = list()
if obj.CutPattern == 'Line':
PNTSET = PathSurfaceSupport.pathGeomToLinesPointSet(obj, pathGeom, self.CutClimb, self.toolDiam, self.closedGap, self.gaps)
elif obj.CutPattern == 'ZigZag':
PNTSET = PathSurfaceSupport.pathGeomToZigzagPointSet(obj, pathGeom, self.CutClimb, self.toolDiam, self.closedGap, self.gaps)
elif obj.CutPattern == 'Spiral':
PNTSET = PathSurfaceSupport.pathGeomToSpiralPointSet(obj, pathGeom)
for STEP in PNTSET:
for LN in STEP:
if LN == 'BRK':
stpOvr.append(LN)
else:
# D format is ((p1, p2), (p3, p4))
(A, B) = LN
stpOvr.append(self._planarDropCutScan(pdc, A, B))
SCANS.append(stpOvr)
stpOvr = list()
elif obj.CutPattern in ['Circular', 'CircularZigZag']:
# PNTSET is list, by stepover.
# Each stepover is a list containing arc/loop descriptions, (sp, ep, cp)
PNTSET = PathSurfaceSupport.pathGeomToCircularPointSet(obj, pathGeom, self.CutClimb, self.toolDiam, self.closedGap, self.gaps, self.tmpCOM)
for so in range(0, len(PNTSET)):
stpOvr = list()
erFlg = False
(aTyp, dirFlg, ARCS) = PNTSET[so]
if dirFlg == 1: # 1
cMode = True
else:
cMode = False
for a in range(0, len(ARCS)):
Arc = ARCS[a]
if Arc == 'BRK':
stpOvr.append('BRK')
else:
scan = self._planarCircularDropCutScan(pdc, Arc, cMode)
if scan is False:
erFlg = True
else:
if aTyp == 'L':
scan.append(FreeCAD.Vector(scan[0].x, scan[0].y, scan[0].z))
stpOvr.append(scan)
if erFlg is False:
SCANS.append(stpOvr)
# Eif
return SCANS
def _planarDropCutScan(self, pdc, A, B):
(x1, y1) = A
(x2, y2) = B
path = ocl.Path() # create an empty path object
p1 = ocl.Point(x1, y1, 0) # start-point of line
p2 = ocl.Point(x2, y2, 0) # end-point of line
lo = ocl.Line(p1, p2) # line-object
path.append(lo) # add the line to the path
pdc.setPath(path)
pdc.run() # run dropcutter algorithm on path
CLP = pdc.getCLPoints()
PNTS = [FreeCAD.Vector(p.x, p.y, p.z) for p in CLP]
return PNTS # pdc.getCLPoints()
def _planarCircularDropCutScan(self, pdc, Arc, cMode):
path = ocl.Path() # create an empty path object
(sp, ep, cp) = Arc
# process list of segment tuples (vect, vect)
p1 = ocl.Point(sp[0], sp[1], 0) # start point of arc
p2 = ocl.Point(ep[0], ep[1], 0) # end point of arc
C = ocl.Point(cp[0], cp[1], 0) # center point of arc
ao = ocl.Arc(p1, p2, C, cMode) # arc object
path.append(ao) # add the arc to the path
pdc.setPath(path)
pdc.run() # run dropcutter algorithm on path
CLP = pdc.getCLPoints()