File size: 9,909 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
# SPDX-License-Identifier: LGPL-2.1-or-later

import FreeCAD as App
import Part
import Path
import numpy
import math

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())


def checkForBlindHole(baseshape, selectedFace):
    """
    check for blind holes, returns the bottom face if found, none
    if the hole is a thru-hole
    """
    circularFaces = [
        f
        for f in baseshape.Faces
        if len(f.OuterWire.Edges) == 1 and type(f.OuterWire.Edges[0].Curve) == Part.Circle
    ]

    circularFaceEdges = [f.OuterWire.Edges[0] for f in circularFaces]
    commonedges = [i for i in selectedFace.Edges for x in circularFaceEdges if i.isSame(x)]

    bottomface = None
    for f in circularFaces:
        for e in f.Edges:
            for i in commonedges:
                if e.isSame(i):
                    bottomface = f
                break

    return bottomface


def isDrillableCylinder(obj, candidate, tooldiameter=None, vector=App.Vector(0, 0, 1)):
    """
    checks if a candidate cylindrical face is drillable
    """

    matchToolDiameter = tooldiameter is not None
    matchVector = vector is not None

    Path.Log.debug(
        "\n match tool diameter {} \n match vector {}".format(matchToolDiameter, matchVector)
    )

    def raisedFeature(obj, candidate):
        # check if the cylindrical 'lids' are inside the base
        # object.  This eliminates extruded circles but allows
        # actual holes.

        startLidCenter = App.Vector(
            candidate.BoundBox.Center.x,
            candidate.BoundBox.Center.y,
            candidate.BoundBox.ZMax,
        )

        endLidCenter = App.Vector(
            candidate.BoundBox.Center.x,
            candidate.BoundBox.Center.y,
            candidate.BoundBox.ZMin,
        )

        return obj.isInside(startLidCenter, 1e-6, False) or obj.isInside(endLidCenter, 1e-6, False)

    def getSeam(candidate):
        # Finds the vertical seam edge in a cylinder

        for e in candidate.Edges:
            if isinstance(e.Curve, Part.Line):  # found the seam
                return e

    if not candidate.ShapeType == "Face":
        raise TypeError("expected a Face")

    if not isinstance(candidate.Surface, Part.Cylinder):
        raise TypeError("expected a cylinder")

    if len(candidate.Edges) != 3:
        raise TypeError("cylinder does not have 3 edges.  Not supported yet")

    if raisedFeature(obj, candidate):
        Path.Log.debug("The cylindrical face is a raised feature")
        return False

    if not matchToolDiameter and not matchVector:
        return True

    if matchToolDiameter and tooldiameter / 2 > candidate.Surface.Radius:
        Path.Log.debug("The tool is larger than the target")
        return False

    bottomface = checkForBlindHole(obj, candidate)
    Path.Log.track("candidate is a blind hole")

    if bottomface is not None and matchVector:  # blind holes only drillable at exact vector
        result = compareVecs(bottomface.normalAt(0, 0), vector, exact=True)
        Path.Log.track(result)
        return result

    elif matchVector and not (compareVecs(getSeam(candidate).Curve.Direction, vector)):
        Path.Log.debug("The feature is not aligned with the given vector")
        return False
    else:
        return True


def isDrillableFace(obj, candidate, tooldiameter=None, vector=App.Vector(0, 0, 1)):
    """
    checks if a flat face or edge is drillable
    """
    matchToolDiameter = tooldiameter is not None
    matchVector = vector is not None
    Path.Log.debug(
        "\n match tool diameter {} \n match vector {}".format(matchToolDiameter, matchVector)
    )

    if not type(candidate.Surface) == Part.Plane:
        Path.Log.debug("Drilling on non-planar faces not supported")
        return False

    if (
        len(candidate.Edges) == 1 and type(candidate.Edges[0].Curve) == Part.Circle
    ):  # Regular circular face
        Path.Log.debug("Face is circular - 1 edge")
        edge = candidate.Edges[0]
    elif (
        len(candidate.Edges) == 2
        and type(candidate.Edges[0].Curve) == Part.Circle
        and type(candidate.Edges[1].Curve) == Part.Circle
    ):  # process a donut
        Path.Log.debug("Face is a donut - 2 edges")
        e1 = candidate.Edges[0]
        e2 = candidate.Edges[1]
        edge = e1 if e1.Curve.Radius < e2.Curve.Radius else e2
    else:
        Path.Log.debug(
            "expected a Face with one or two circular edges got a face with {} edges".format(
                len(candidate.Edges)
            )
        )
        return False
    if vector is not None:  # Check for blind hole alignment
        if not compareVecs(candidate.normalAt(0, 0), vector, exact=True):
            Path.Log.debug("Vector not aligned")
            return False
    if matchToolDiameter and edge.Curve.Radius < tooldiameter / 2:
        Path.Log.debug("Failed diameter check")
        return False
    else:
        Path.Log.debug("Face is drillable")
        return True


def isDrillableEdge(
    obj, candidate, tooldiameter=None, vector=App.Vector(0, 0, 1), allowPartial=False
):
    """
    checks if an edge is drillable
    """

    matchToolDiameter = tooldiameter is not None
    matchVector = vector is not None
    Path.Log.debug(
        "\n match tool diameter {} \n match vector {}".format(matchToolDiameter, matchVector)
    )

    edge = candidate
    if not (isinstance(edge.Curve, Part.Circle)):
        Path.Log.debug("expected a circular edge")
        return False

    if isinstance(edge.Curve, Part.Circle):
        if not (allowPartial or edge.isClosed()):
            Path.Log.debug("expected a closed circular edge or allow partial")
            return False

    if not hasattr(edge.Curve, "Radius"):
        Path.Log.debug("The Feature edge has no radius - Ellipse.")
        return False

    if not matchToolDiameter and not matchVector:
        return True

    if matchToolDiameter and tooldiameter / 2 > edge.Curve.Radius:
        Path.Log.debug("The tool is larger than the target")
        return False

    if matchVector and not (compareVecs(edge.Curve.Axis, vector)):
        Path.Log.debug("The feature is not aligned with the given vector")
        return False
    else:
        return True


def isDrillable(obj, candidate, tooldiameter=None, vector=App.Vector(0, 0, 1), allowPartial=False):
    """
    Checks candidates to see if they can be drilled at the given vector.
    Candidates can be either faces - circular or cylindrical or circular edges.
    The tooldiameter can be optionally passed.  if passed, the check will return
    False for any holes smaller than the tooldiameter.

    vector defaults to (0,0,1) which aligns with the Z axis.  By default will return False
    for any candidate not drillable in this orientation.  Pass 'None' to vector to test whether
    the hole is drillable at any orientation.

    allowPartial will permit selecting partial circular arcs manually.

    obj=Shape
    candidate = Face or Edge
    tooldiameter=float
    vector=App.Vector or None
    allowPartial boolean

    """
    Path.Log.debug(
        "obj: {} candidate: {} tooldiameter {} vector {}".format(
            obj, candidate, tooldiameter, vector
        )
    )

    if list == type(obj):
        for shape in obj:
            if isDrillable(shape, candidate, tooldiameter, vector):
                return (True, shape)
        return (False, None)

    if candidate.ShapeType not in ["Face", "Edge"]:
        raise TypeError("expected a Face or Edge. Got a {}".format(candidate.ShapeType))

    try:
        if candidate.ShapeType == "Face":
            if isinstance(candidate.Surface, Part.Cylinder):
                return isDrillableCylinder(obj, candidate, tooldiameter, vector)
            else:
                return isDrillableFace(obj, candidate, tooldiameter, vector)
        if candidate.ShapeType == "Edge":
            return isDrillableEdge(obj, candidate, tooldiameter, vector, allowPartial)
        else:
            return False

    except TypeError as e:
        Path.Log.debug(e)
        return False
        # raise TypeError("{}".format(e))


def compareVecs(vec1, vec2, exact=False):
    """
    compare the two vectors to see if they are aligned for drilling.
    if exact is True, vectors must match direction. Otherwise,
    alignment can indicate the vectors are the same or exactly opposite
    """

    angle = vec1.getAngle(vec2)
    angle = 0 if math.isnan(angle) else math.degrees(angle)
    Path.Log.debug("vector angle: {}".format(angle))
    if exact:
        return numpy.isclose(angle, 0, rtol=1e-05, atol=1e-06)
    else:
        return numpy.isclose(angle, 0, rtol=1e-05, atol=1e-06) or numpy.isclose(
            angle, 180, rtol=1e-05, atol=1e-06
        )


def getDrillableTargets(obj, ToolDiameter=None, vector=App.Vector(0, 0, 1)):
    """
    Returns a list of tuples for drillable subelements from the given object
    [(obj,'Face1'),(obj,'Face3')]

    Finds cylindrical faces that are larger than the tool diameter (if provided) and
    oriented with the vector.  If vector is None, all drillables are returned

    """

    shp = obj.Shape

    results = []
    for i in range(1, len(shp.Faces) + 1):
        fname = "Face{}".format(i)
        Path.Log.debug(fname)
        candidate = obj.getSubObject(fname)

        if not isinstance(candidate.Surface, Part.Cylinder):
            continue

        try:
            drillable = isDrillable(shp, candidate, tooldiameter=ToolDiameter, vector=vector)
            Path.Log.debug("fname: {} : drillable {}".format(fname, drillable))
        except Exception as e:
            Path.Log.debug(e)
            continue

        if drillable:
            results.append((obj, fname))

    return results