File size: 29,237 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2020 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                                                                   *
# *                                                                         *
# ***************************************************************************

import FreeCAD
import Part
import Path
import Path.Op.Base as PathOp
import Path.Op.EngraveBase as PathEngraveBase
import PathScripts.PathUtils as PathUtils
import math
from PySide.QtCore import QT_TRANSLATE_NOOP

__doc__ = "Class and implementation of CAM Vcarve operation"

PRIMARY = 0
SECONDARY = 1
EXTERIOR1 = 2
EXTERIOR2 = 3
COLINEAR = 4
TWIN = 5
BORDERLINE = 6

# There is a bug in logging library. To enable debugging - set True also in Gui/Vcarve.py

if False:
    Path.Log.setLevel(Path.Log.Level.DEBUG, Path.Log.thisModule())
    Path.Log.trackModule(Path.Log.thisModule())
else:
    Path.Log.setLevel(Path.Log.Level.INFO, Path.Log.thisModule())


translate = FreeCAD.Qt.translate


def _collectVoronoiWires(vd):
    edges = [e for e in vd.Edges if e.Color == PRIMARY]
    vertex = {}
    for e in edges:
        for v in e.Vertices:
            i = v.Index
            j = vertex.get(i, [])
            j.append(e)
            vertex[i] = j

    # knots are the start and end points of a wire
    knots = [i for i in vertex if len(vertex[i]) == 1]
    knots.extend([i for i in vertex if len(vertex[i]) > 2])
    if len(knots) == 0:
        for i in vertex:
            if len(vertex[i]) > 0:
                knots.append(i)
                break

    def consume(v, edge):
        vertex[v] = [e for e in vertex[v] if e.Index != edge.Index]
        return len(vertex[v]) == 0

    def traverse(vStart, edge, edges):
        if vStart == edge.Vertices[0].Index:
            vEnd = edge.Vertices[1].Index
            edges.append(edge)
        else:
            vEnd = edge.Vertices[0].Index
            edges.append(edge.Twin)

        consume(vStart, edge)
        if consume(vEnd, edge):
            return None
        return vEnd

    wires = []
    while knots:
        we = []
        vFirst = knots[0]
        vStart = vFirst
        vLast = vFirst
        if len(vertex[vStart]):
            while vStart is not None:
                vLast = vStart
                edges = vertex[vStart]
                if len(edges) > 0:
                    edge = edges[0]
                    vStart = traverse(vStart, edge, we)
                else:
                    vStart = None
            wires.append(we)
        if len(vertex[vFirst]) == 0:
            knots = [v for v in knots if v != vFirst]
        if len(vertex[vLast]) == 0:
            knots = [v for v in knots if v != vLast]
    return wires


def _sortVoronoiWires(wires, start=FreeCAD.Vector(0, 0, 0)):
    def closestTo(start, point):
        p = None
        length = None
        for i in point:
            if length is None or length > start.distanceToPoint(point[i]):
                length = start.distanceToPoint(point[i])
                p = i
        return (p, length)

    begin = {}
    end = {}

    for i, w in enumerate(wires):
        begin[i] = w[0].Vertices[0].toPoint()
        end[i] = w[-1].Vertices[1].toPoint()

    result = []
    while begin:
        (bIdx, bLen) = closestTo(start, begin)
        (eIdx, eLen) = closestTo(start, end)
        if bLen < eLen:
            result.append(wires[bIdx])
            start = end[bIdx]
            del begin[bIdx]
            del end[bIdx]
        else:
            result.append([e.Twin for e in reversed(wires[eIdx])])
            start = begin[eIdx]
            del begin[eIdx]
            del end[eIdx]

    return result


def getReversedEdge(edge):
    # returns a reversed edge (copy of original edge)
    curve = edge.Curve
    first = edge.FirstParameter
    last = edge.LastParameter
    curve_c = curve.copy()
    curve_c.reverse()
    return Part.Edge(curve_c, curve_c.reversedParameter(last), curve_c.reversedParameter(first))


def generateVirtualBackTrackEdges(positionHistory, nextEdge, tolerance) -> list:
    """
    Generate a list of "virtual edges" to backtrack using normal G1 moves instead lifting
    toolbit and repositioning using G0 to get to beginning of nextEdge.
    Those virtual edges are either already carved or are part of nextEdge anyway so it's safe
    to follow them without lifting toolbit. This approach makes carving a lot of faster.
    """

    if not positionHistory or len(positionHistory) < 2:
        return []

    backTrackEdges = []

    currentPosition = positionHistory[-1]
    previousPosition = positionHistory[-2]

    nextEdgeStart = nextEdge.valueAt(nextEdge.FirstParameter)
    nextEdgeEnd = nextEdge.valueAt(nextEdge.LastParameter)

    # Scenario 1
    #
    # in some cases travelling between wires looks like that:
    # A ========= B ------- D
    #             |
    #             C
    #
    # we follow first wire from A to B - new wire starts at C and goes through B -> D
    # Repositioning to position C using G0 command does not make sense and it's slow
    # We can insert "virtual" edge B->C at the beginning of a second wire to make
    # continuous CNC head movement
    #

    if nextEdgeEnd.isEqual(currentPosition, tolerance):
        # virtual edge is "reversed"
        virtualEdge = Part.Edge(Part.LineSegment(nextEdgeEnd, nextEdgeStart))
        backTrackEdges.append(virtualEdge)

    # Scenario 2
    # next edge has common node with previous position but it's reversed
    #  A     C
    #   \   //
    #    \ //
    #     B
    # We went from B to C and next wire edge starts at A and goes back to B
    # Normally we would G0 jump from C to A and start from there,
    # but we can go back from C to B and then to A (by adding extra edge which
    # is reversed A->B edge).

    elif nextEdgeEnd.isEqual(previousPosition, tolerance):
        # travel back to the previous toolbit position
        virtualEdge = Part.Edge(Part.LineSegment(currentPosition, previousPosition))
        backTrackEdges.append(virtualEdge)
        # instead of G0 - just carve the edge in reverse direction
        backTrackEdges.append(getReversedEdge(nextEdge))

    return backTrackEdges


def canSkipRepositioning(positionHistory, newPosition, tolerance):
    """
    Calculate if it makes sense to raise head to safe height and reposition before
    starting to cut another edge
    """

    if not positionHistory:
        return False

    currentPosition = positionHistory[-1]
    previousPosition = positionHistory[-2]

    # get vertex position on X/Y plane only
    v0 = FreeCAD.Base.Vector(currentPosition.x, currentPosition.y)
    v1 = FreeCAD.Base.Vector(newPosition.x, newPosition.y)

    # do not bother with G0 if new and current position differ by less than 0.5 mm in X/Y
    if v0.distanceToPoint(v1) <= 0.5:
        return True

    # if new position is same as previous head position we can essentially
    # go back traversing same edge. This is handy with short "detour" edges like that:
    #
    #      A--------------B===============C
    #                     |
    #                     D
    # We are travelling wire from A -> B -> D within first wire and ending at D. New wire starts with edge going from
    # B to C. We don't need to G0 to point B, we can skip positioning because if we travel G1 move from D to B we will follow already
    # carved path

    if newPosition.isEqual(previousPosition, tolerance):
        return True

    return False


class _Geometry(object):
    """POD class so the limits only have to be calculated once."""

    def __init__(self, zStart, zStop, zScale, zStepDown):
        self.start = zStart
        self.stop = zStop
        self.scale = zScale
        self.stepDown = zStepDown
        self.stepDownPass = 1

        # offset is used in finishing passes to override
        # any calculated vcarving depths. Usually going deeper 0.1-0.2 mm on finishing pass can help
        # remove "fuzzy skin" or other imperfections.
        self.offset = 0

    def incrementStepDownDepth(self, maximumUsableDepth):
        """
        Increase stepDown depth before starting new carving pass.
        :returns: True if successful, False if maximum depth achieved
        """

        # do not allow one to increase depth if we are already at stop depth
        if self.maximumDepth == self.stop:
            return False

        # do not allow one to increase depth if we are already at
        # maximum usable depth

        if self.maximumDepth <= maximumUsableDepth:
            return False

        self.stepDownPass += 1
        return True

    @property
    def maximumDepth(self):
        """
        Return maximum vcarving depth computed from step down setting and pass number
        """

        if self.stepDown == 0:
            return self.stop

        return max(self.stop, self.start - (self.stepDownPass * self.stepDown))

    @classmethod
    def FromTool(cls, tool, zStart, zFinal, zStepDown=0):
        rMax = float(tool.Diameter) / 2.0
        rMin = float(tool.TipDiameter) / 2.0
        toolangle = math.tan(math.radians(tool.CuttingEdgeAngle.Value / 2.0))
        zScale = 1.0 / toolangle
        zStop = zStart - rMax * zScale
        zOff = rMin * zScale

        return _Geometry(zStart + zOff, max(zStop + zOff, zFinal), zScale, zStepDown)

    @classmethod
    def FromObj(cls, obj, model):
        if obj.BaseShapes and hasattr(obj.BaseShapes[0], "Shape"):
            zStart = obj.BaseShapes[0].Shape.BoundBox.ZMax
        elif obj.Base and obj.Base[0][0] and hasattr(obj.Base[0][0], "Shape"):
            if len(obj.Base[0]) > 1 and "Face" in obj.Base[0][1][0]:
                faceName = obj.Base[0][1][0]
                faceIndex = int(faceName.replace("Face", "")) - 1
                face = obj.Base[0][0].Shape.Faces[faceIndex]
                zStart = face.BoundBox.ZMax
            else:
                zStart = obj.Base[0][0].Shape.BoundBox.ZMax
        else:
            zStart = model.Shape.BoundBox.ZMax
            Path.Log.error("Base object not set")
        finalDepth = obj.FinalDepth.Value
        stepDown = abs(obj.StepDown.Value)

        return cls.FromTool(obj.ToolController.Tool, zStart, finalDepth, stepDown)


def _calculate_depth(MIC, geom):
    # given a maximum inscribed circle (MIC) and tool angle,
    # return depth of cut relative to zStart.
    depth = geom.start - round(MIC * geom.scale, 4)

    return max(depth, geom.maximumDepth) + geom.offset


def _get_maximumUsableDepth(wires, geom):
    """
    Calculate maximum engraving depth for a list of wires
    belonging to one face.
    """

    def _get_depth(MIC, geom):
        """Similar logic to _calculate_depth but without stepdown and offset calculations"""
        depth = geom.start - round(MIC * geom.scale, 4)
        return max(depth, geom.stop)

    min_depth = None

    for wire in wires:
        for edge in wire:
            dist = edge.getDistances()
            depth = min(_get_depth(dist[0], geom), _get_depth(dist[1], geom))

            if min_depth is None:
                min_depth = depth
            else:
                min_depth = min(min_depth, depth)

    return min_depth


def _getPartEdge(edge, geom):
    dist = edge.getDistances()
    zBegin = _calculate_depth(dist[0], geom)
    zEnd = _calculate_depth(dist[1], geom)
    return edge.toShape(zBegin, zEnd)


def _getPartEdges(obj, vWire, geom):
    edges = []
    for e in vWire:
        edges.append(_getPartEdge(e, geom))
    return edges


class ObjectVcarve(PathEngraveBase.ObjectOp):
    """Proxy class for Vcarve operation."""

    def opFeatures(self, obj):
        """opFeatures(obj) ... return all standard features and edges based geometries"""
        return (
            PathOp.FeatureTool
            | PathOp.FeatureHeights
            | PathOp.FeatureDepths
            | PathOp.FeatureStepDown
            | PathOp.FeatureBaseFaces
            | PathOp.FeatureCoolant
        )

    def setupAdditionalProperties(self, obj):
        if not hasattr(obj, "BaseShapes"):
            obj.addProperty(
                "App::PropertyLinkList",
                "BaseShapes",
                "Path",
                QT_TRANSLATE_NOOP("App::Property", "Additional base objects to be engraved"),
            )
        obj.setEditorMode("BaseShapes", 2)  # hide

        if not hasattr(obj, "OptimizeMovements"):

            obj.addProperty(
                "App::PropertyBool",
                "OptimizeMovements",
                "Path",
                QT_TRANSLATE_NOOP("App::Property", "Optimize movements"),
            )
            obj.OptimizeMovements = False

        if not hasattr(obj, "FinishingPass"):
            obj.addProperty(
                "App::PropertyBool",
                "FinishingPass",
                "Path",
                QT_TRANSLATE_NOOP("App::Property", "Add finishing pass"),
            )
            obj.FinishingPass = False

        if not hasattr(obj, "FinishingPassZOffset"):
            obj.addProperty(
                "App::PropertyDistance",
                "FinishingPassZOffset",
                "Path",
                QT_TRANSLATE_NOOP("App::Property", "Finishing pass Z offset"),
            )

            obj.FinishingPassZOffset = "0.00"

    def initOperation(self, obj):
        """initOperation(obj) ... create vcarve specific properties."""
        obj.addProperty(
            "App::PropertyFloat",
            "Discretize",
            "Path",
            QT_TRANSLATE_NOOP("App::Property", "The deflection value for discretizing arcs"),
        )
        obj.addProperty(
            "App::PropertyFloat",
            "Colinear",
            "Path",
            QT_TRANSLATE_NOOP(
                "App::Property",
                "Cutoff for removing colinear segments (degrees). \
                        default=10.0.",
            ),
        )
        obj.addProperty(
            "App::PropertyFloat",
            "Tolerance",
            "Path",
            QT_TRANSLATE_NOOP("App::Property", "Vcarve Tolerance"),
        )

        obj.Colinear = 10.0
        obj.Discretize = 0.25
        obj.Tolerance = Path.Preferences.defaultGeometryTolerance()
        # keep copy in local object to use in methods which do not operate directly on obj
        # we use getattr because OpsDefaultEditor may trigger this method to gather list of
        # default operation settings but reading from OpPrototype object fails
        self.Tolerance = getattr(obj, "Tolerance", Path.Preferences.defaultGeometryTolerance())
        self.setupAdditionalProperties(obj)

    def opOnDocumentRestored(self, obj):
        # upgrade ...
        self.setupAdditionalProperties(obj)

    def buildMedialWires(self, obj, faces):
        """
        constructs a medial axis path using openvoronoi
        :returns: dictionary - each face object is a key containing list of wires"""

        medial_wires_by_face = dict()
        edges_by_face = dict()  # non processed voronoi edges, for debugging

        self.voronoiDebugMedialCache = dict()
        self.voronoiDebugEdgeCache = dict()

        def is_exterior(vertex, face):
            vector = FreeCAD.Vector(vertex.toPoint(face.BoundBox.ZMin))
            (u, v) = face.Surface.parameter(vector)
            # isPartOfDomain is faster than face.IsInside(...)
            return not face.isPartOfDomain(u, v)

        def insert_many_wires(vd, wires):
            for wire in wires:
                Path.Log.debug("discretize value: {}".format(obj.Discretize))
                pts = wire.discretize(QuasiDeflection=obj.Discretize)
                ptv = [FreeCAD.Vector(p.x, p.y) for p in pts]
                # Check over the last point before just closing the polygon
                # by adding the start again.  If the discretizer was aiming
                # for the last point and missed by a little bit, closing the
                # polygon as is could result in OpenVoronoi truncating the
                # coordinates to a self-intersecting polygon which is invalid.
                # Instead, if the last point is close to the first, remove it
                # and let the final append close the polygon.
                # See issue 8064
                if len(ptv) > 0:
                    dist = ptv[-1].distanceToPoint(ptv[0])
                    if dist < FreeCAD.Base.Precision.confusion():
                        Path.Log.debug(
                            "Removing bad carve point: {} from polygon origin".format(dist)
                        )
                        del ptv[-1]
                ptv.append(ptv[0])

                for i in range(len(ptv) - 1):
                    vd.addSegment(ptv[i], ptv[i + 1])

        for f in faces:
            voronoiWires = []
            vd = Path.Voronoi.Diagram()
            insert_many_wires(vd, f.Wires)

            vd.construct()
            edges_by_face[f] = vd.Edges

            for e in vd.Edges:
                if e.isPrimary():
                    if e.isBorderline():
                        e.Color = BORDERLINE
                    else:
                        e.Color = PRIMARY
                else:
                    e.Color = SECONDARY

            # filter our colinear edged so there are fewer ones
            # to iterate over in colorExterior which is slow
            vd.colorColinear(COLINEAR, obj.Colinear)

            vd.colorExterior(EXTERIOR1)
            vd.colorExterior(EXTERIOR2, lambda v: is_exterior(v, f))

            # if colorTwin is done before colorExterior we seem to have
            # much more weird exterior edges needed to be filtered out,
            # keep it here to be safe
            vd.colorTwins(TWIN)

            wires = _collectVoronoiWires(vd)
            wires = _sortVoronoiWires(wires)
            voronoiWires.extend(wires)

            medial_wires_by_face[f] = voronoiWires

        self.voronoiDebugMedialCache = medial_wires_by_face
        self.voronoiDebugEdgeCache = edges_by_face

        return medial_wires_by_face

    def buildCommandList(self, obj, faces):
        """
        Build command list to cut wires - based on voronoi
        wire list from buildMedialWires
        """

        def getPositionHistory(wire):
            """
            Get CNC current and previous head position assuming it reached the end of the wire
            returns: previousPosition, currentPostion tuple
            """

            if not wire:
                return None

            lastEdge = wire[-1]
            return (
                lastEdge.valueAt(lastEdge.FirstParameter),
                lastEdge.valueAt(lastEdge.LastParameter),
            )

        def cutWires(wires, pathlist, optimizeMovements=False):

            positionHistory = None

            for w in wires:
                pWire = _getPartEdges(obj, w, geom)
                if pWire:
                    pathlist.extend(_cutWire(pWire, positionHistory))

                    # movement optimization only works if we provide head position history
                    if optimizeMovements:
                        positionHistory = getPositionHistory(pWire)

        def _cutWire(wire, positionHistory=None):
            path = []

            backtrack_edges = []

            # we start vcarving another wire which may not be connected to previous one
            # but using some routing logic we may avoid raising CNC toolbit and using G0
            # and instead traverse back already carved edges at full speed

            backtrack_edges = generateVirtualBackTrackEdges(positionHistory, wire[0], obj.Tolerance)

            edge_list = backtrack_edges + wire

            e = edge_list[0]
            newPosition = e.valueAt(e.FirstParameter)

            hSpeed = obj.ToolController.HorizFeed.Value
            vSpeed = obj.ToolController.VertFeed.Value

            # check if we can smart-skip using G0 repositioning which is slow
            if not canSkipRepositioning(positionHistory, newPosition, obj.Tolerance):
                path.append(Path.Command("G0", {"Z": obj.SafeHeight.Value}))
                path.append(
                    Path.Command(
                        "G0",
                        {
                            "X": newPosition.x,
                            "Y": newPosition.y,
                            "Z": obj.SafeHeight.Value,
                        },
                    )
                )

                path.append(
                    Path.Command(
                        "G1",
                        {
                            "X": newPosition.x,
                            "Y": newPosition.y,
                            "Z": newPosition.z,
                            "F": vSpeed,
                        },
                    )
                )
            else:  # skip repositioning
                # technically hSpeed + vSpeed should be properly recalculated into F parameter
                # as cmdsForEdge does but we either cut max 0.5 mm through stock or backtrack
                # over already carved edges, so hSpeed will be just fine
                path.append(
                    Path.Command(
                        "G1 X{} Y{} Z{} F{}".format(
                            newPosition.x, newPosition.y, newPosition.z, hSpeed
                        )
                    )
                )

            for e in edge_list:
                path.extend(Path.Geom.cmdsForEdge(e, hSpeed=hSpeed, vSpeed=vSpeed))

            return path

        pathlist = []
        pathlist.append(Path.Command("(starting)"))

        geom = _Geometry.FromObj(obj, self.model[0])

        # iterate over each face separately
        for face, wires in self.buildMedialWires(obj, faces).items():

            # If using depth step-down, calculate maximum usable depth for current face.
            # This is done to avoid adding additional step-down engraving passes when it
            # would make no sense as depth is limited by Maximum Inscribed Circle anyway.

            maximumUsableDepth = geom.stop

            if geom.stepDown > 0:
                _maximumUsableDepth = _get_maximumUsableDepth(wires, geom)
                if _maximumUsableDepth is not None:
                    maximumUsableDepth = _maximumUsableDepth
                    Path.Log.debug(f"Maximum usable depth for current face: {maximumUsableDepth}")

            # first pass
            cutWires(wires, pathlist, obj.OptimizeMovements)

            # subsequent stepDown depth passes (if any)
            while geom.incrementStepDownDepth(maximumUsableDepth):
                cutWires(wires, pathlist, obj.OptimizeMovements)

            # add finishing pass if enabled

            if obj.FinishingPass:
                geom.offset = obj.FinishingPassZOffset.Value

                cutWires(wires, pathlist, obj.OptimizeMovements)

        self.commandlist = pathlist

    def opExecute(self, obj):
        """opExecute(obj) ... process engraving operation"""
        Path.Log.track()

        self.voronoiDebugMedialCache = None
        self.voronoiDebugEdgesCache = None

        if obj.ToolController is None:
            return

        if not hasattr(obj.ToolController.Tool, "CuttingEdgeAngle"):
            Path.Log.info(
                translate(
                    "CAM_Vcarve",
                    "VCarve requires an engraving cutter with a cutting edge angle",
                )
            )
            return

        if obj.ToolController.Tool.CuttingEdgeAngle >= 180.0:
            Path.Log.info(
                translate("CAM_Vcarve", "Engraver cutting edge angle must be < 180 degrees.")
            )
            return

        try:
            faces = []

            for base in obj.BaseShapes:
                faces.extend(base.Shape.Faces)

            for base in obj.Base:
                for sub in base[1]:
                    shape = getattr(base[0].Shape, sub)
                    if isinstance(shape, Part.Face):
                        faces.append(shape)

            if not faces:
                for model in self.model:
                    if model.isDerivedFrom("Sketcher::SketchObject") or model.isDerivedFrom(
                        "Part::Part2DObject"
                    ):
                        faces.extend(model.Shape.Faces)

            if faces:
                self.buildCommandList(obj, faces)
            else:
                Path.Log.error(
                    translate(
                        "PathVcarve",
                        "The Job Base Object has no engraveable element. Engraving operation will produce no output.",
                    )
                )

        except Exception:
            Path.Log.warning(
                "Error processing Base object. Engraving operation will produce no output."
            )
            import traceback

            Path.Log.error(f"Engraving operation exception: {traceback.format_exc()}")

    def opUpdateDepths(self, obj, ignoreErrors=False):
        """updateDepths(obj) ... engraving is always done at the top most z-value"""
        job = PathUtils.findParentJob(obj)
        self.opSetDefaultValues(obj, job)

    def opSetDefaultValues(self, obj, job):
        """opSetDefaultValues(obj) ... set depths for vcarving"""
        if PathOp.FeatureDepths & self.opFeatures(obj):
            if job and len(job.Model.Group) > 0:
                bb = job.Proxy.modelBoundBox(job)
                obj.OpStartDepth = bb.ZMax
                obj.OpFinalDepth = job.Stock.Shape.BoundBox.ZMin
            else:
                obj.OpFinalDepth = -0.1

    def isToolSupported(self, obj, tool):
        """isToolSupported(obj, tool) ... returns True if v-carve op can work with tool."""
        return (
            hasattr(tool, "Diameter")
            and hasattr(tool, "CuttingEdgeAngle")
            and hasattr(tool, "TipDiameter")
        )

    def debugVoronoiMedial(self, obj):
        """Debug function to display calculated voronoi medial wires"""

        if not getattr(self, "voronoiDebugMedialCache", None):
            Path.Log.error("debugVoronoi: empty debug cache. Recompute VCarve operation first")
            return

        vPart = FreeCAD.activeDocument().addObject("App::Part", f"{obj.Name}-VoronoiDebugMedial")

        wiresToShow = []

        for face, wires in self.voronoiDebugMedialCache.items():
            for wire in wires:
                currentPartWire = Part.Wire()
                currentPartWire.fixTolerance(0.01)
                for edge in wire:
                    currentEdge = edge.toShape()

                    for v in currentEdge.Vertexes:
                        v.fixTolerance(0.1)

                    currentPartWire.add(currentEdge)
                wiresToShow.append(currentPartWire)

        for w in wiresToShow:
            vPart.addObject(Part.show(w))

    def debugVoronoiEdges(self, obj):
        """Debug function to display calculated voronoi edges"""

        if not getattr(self, "voronoiDebugEdgeCache", None):
            Path.Log.error("debugVoronoi: empty debug cache. Recompute VCarve operation first")
            return

        vPart = FreeCAD.activeDocument().addObject("App::Part", f"{obj.Name}-VoronoiDebugEdge")

        edgesToShow = []

        for face, edges in self.voronoiDebugEdgeCache.items():
            for edge in edges:  # those are voronoi Edge objects, not FC Edge
                currentEdge = edge.toShape()

                edgesToShow.append(currentEdge)

        for e in edgesToShow:
            vPart.addObject(Part.show(e))


def SetupProperties():
    return ["Discretize"]


def Create(name, obj=None, parentJob=None):
    """Create(name) ... Creates and returns a Vcarve operation."""
    if obj is None:
        obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", name)
    obj.Proxy = ObjectVcarve(obj, name, parentJob)
    return obj