diff --git a/src/Mod/Path/PathScripts/PathCircularHoleBase.py b/src/Mod/Path/PathScripts/PathCircularHoleBase.py index de3050af29..0ca353ea0c 100644 --- a/src/Mod/Path/PathScripts/PathCircularHoleBase.py +++ b/src/Mod/Path/PathScripts/PathCircularHoleBase.py @@ -21,6 +21,12 @@ # * USA * # * * # *************************************************************************** +# * * +# * Additional modifications and contributions beginning 2019 * +# * Focus: 4th-axis integration * +# * by Russell Johnson * +# * * +# *************************************************************************** import ArchPanel import FreeCAD @@ -31,17 +37,28 @@ import PathScripts.PathOp as PathOp import PathScripts.PathUtils as PathUtils from PySide import QtCore +import PathScripts.PathGeom as PathGeom + +import math +import Draft +if FreeCAD.GuiUp: + import FreeCADGui __title__ = "Path Circular Holes Base Operation" __author__ = "sliptonic (Brad Collette)" __url__ = "http://www.freecadweb.org" __doc__ = "Base class an implementation for operations on circular holes." +__contributors__ = "russ4262 (Russell Johnson)" +__created__ = "2017" +__scriptVersion__ = "1c testing" +__lastModified__ = "2019-06-25 14:49 CST" # Qt translation handling def translate(context, text, disambig=None): return QtCore.QCoreApplication.translate(context, text, disambig) + LOGLEVEL = False if LOGLEVEL: @@ -53,6 +70,12 @@ else: class ObjectOp(PathOp.ObjectOp): '''Base class for proxy objects of all operations on circular holes.''' + # These are static while document is open, if it contains a CircularHole Op + initOpFinalDepth = None + initOpStartDepth = None + initWithRotation = False + defValsSet = False + docRestored = False def opFeatures(self, obj): '''opFeatures(obj) ... calls circularHoleFeatures(obj) and ORs in the standard features required for processing circular holes. @@ -68,6 +91,7 @@ class ObjectOp(PathOp.ObjectOp): '''initOperation(obj) ... adds Disabled properties and calls initCircularHoleOperation(obj). Do not overwrite, implement initCircularHoleOperation(obj) instead.''' obj.addProperty("App::PropertyStringList", "Disabled", "Base", QtCore.QT_TRANSLATE_NOOP("Path", "List of disabled features")) + self.initCircularHoleOperation(obj) def initCircularHoleOperation(self, obj): @@ -154,26 +178,177 @@ class ObjectOp(PathOp.ObjectOp): calculated and assigned. Do not overwrite, implement circularHoleExecute(obj, holes) instead.''' PathLog.track() + PathLog.debug("\nopExecute() in PathCircularHoleBase.py") + + holes = [] + baseSubsTuples = [] + subCount = 0 + allTuples = [] + self.cloneNames = [] + self.guiMsgs = [] # list of message tuples (title, msg) to be displayed in GUI + self.rotateFlag = False + self.useTempJobClones('Delete') # Clear temporary group and recreate for temp job clones + self.stockBB = PathUtils.findParentJob(obj).Stock.Shape.BoundBox + self.clearHeight = obj.ClearanceHeight.Value + self.safeHeight = obj.SafeHeight.Value + self.axialFeed = 0.0 + self.axialRapid = 0.0 + trgtDep = None def haveLocations(self, obj): if PathOp.FeatureLocations & self.opFeatures(obj): return len(obj.Locations) != 0 return False - holes = [] + if obj.EnableRotation == 'Off': + # maxDep = self.stockBB.ZMax + # minDep = self.stockBB.ZMin + self.strDep = obj.StartDepth.Value + self.finDep = obj.FinalDepth.Value + else: + # Calculate operation heights based upon rotation radii + opHeights = self.opDetermineRotationRadii(obj) + (self.xRotRad, self.yRotRad, self.zRotRad) = opHeights[0] + (self.clrOfset, self.safOfst) = opHeights[1] + PathLog.debug("Exec. opHeights[0]: " + str(opHeights[0])) + PathLog.debug("Exec. opHeights[1]: " + str(opHeights[1])) - for base, subs in obj.Base: + # Set clearnance and safe heights based upon rotation radii + if obj.EnableRotation == 'A(x)': + self.strDep = self.xRotRad + elif obj.EnableRotation == 'B(y)': + self.strDep = self.yRotRad + else: + self.strDep = max(self.xRotRad, self.yRotRad) + self.finDep = -1 * self.strDep + + obj.ClearanceHeight.Value = self.strDep + self.clrOfset + obj.SafeHeight.Value = self.strDep + self.safOfst + + # Create visual axises when debugging. + if PathLog.getLevel(PathLog.thisModule()) == 4: + self.visualAxis() + + # Set axial feed rates based upon horizontal feed rates + safeCircum = 2 * math.pi * obj.SafeHeight.Value + self.axialFeed = 360 / safeCircum * self.horizFeed + self.axialRapid = 360 / safeCircum * self.horizRapid + + # Complete rotational analysis and temp clone creation as needed + if obj.EnableRotation == 'Off': + PathLog.info("Enable Rotation setting is 'Off' for {}.".format(obj.Name)) + stock = PathUtils.findParentJob(obj).Stock + for (base, subList) in obj.Base: + baseSubsTuples.append((base, subList, 0.0, 'A', stock)) + else: + for p in range(0, len(obj.Base)): + (base, subsList) = obj.Base[p] + for sub in subsList: + if self.isHoleEnabled(obj, base, sub): + shape = getattr(base.Shape, sub) + rtn = False + (norm, surf) = self.getFaceNormAndSurf(shape) + (rtn, angle, axis, praInfo) = self.faceRotationAnalysis(obj, norm, surf) + if rtn is True: + (clnBase, angle, clnStock, tag) = self.applyRotationalAnalysis(obj, base, angle, axis, subCount) + # Verify faces are correctly oriented - InverseAngle might be necessary + PathLog.debug("Verifing {} orientation: running faceRotationAnalysis() again.".format(sub)) + faceIA = getattr(clnBase.Shape, sub) + (norm, surf) = self.getFaceNormAndSurf(faceIA) + (rtn, praAngle, praAxis, praInfo) = self.faceRotationAnalysis(obj, norm, surf) + if rtn is True: + msg = obj.Name + ":: " + msg += translate("Path", "{} might be misaligned after initial rotation.".format(sub)) + " " + if obj.AttemptInverseAngle is True and obj.InverseAngle is False: + (clnBase, clnStock, angle) = self.applyInverseAngle(obj, clnBase, clnStock, axis, angle) + msg += translate("Path", "Rotated to 'InverseAngle' to attempt access.") + else: + if len(subsList) == 1: + msg += translate("Path", "Consider toggling the 'InverseAngle' property and recomputing.") + else: + msg += translate("Path", "Consider transfering '{}' to independent operation.".format(sub)) + PathLog.warning(msg) + # title = translate("Path", 'Rotation Warning') + # self.guiMessage(title, msg, False) + else: + PathLog.debug("Face appears to be oriented correctly.") + + cmnt = "{}: {} @ {}; ".format(sub, axis, str(round(angle, 5))) + if cmnt not in obj.Comment: + obj.Comment += cmnt + + tup = clnBase, sub, tag, angle, axis, clnStock + allTuples.append(tup) + else: + if self.warnDisabledAxis(obj, axis, sub) is True: + pass # Skip drill feature due to access issue + else: + PathLog.debug(str(sub) + ": No rotation used") + axis = 'X' + angle = 0.0 + tag = base.Name + '_' + axis + str(angle).replace('.', '_') + stock = PathUtils.findParentJob(obj).Stock + tup = base, sub, tag, angle, axis, stock + allTuples.append(tup) + # Eif + # Eif + subCount += 1 + # Efor + # Efor + (Tags, Grps) = self.sortTuplesByIndex(allTuples, 2) # return (TagList, GroupList) + subList = [] + for o in range(0, len(Tags)): + PathLog.debug('hTag: {}'.format(Tags[o])) + subList = [] + for (base, sub, tag, angle, axis, stock) in Grps[o]: + subList.append(sub) + pair = base, subList, angle, axis, stock + baseSubsTuples.append(pair) + # Efor + + for base, subs, angle, axis, stock in baseSubsTuples: for sub in subs: if self.isHoleEnabled(obj, base, sub): pos = self.holePosition(obj, base, sub) if pos: - holes.append({'x': pos.x, 'y': pos.y, 'r': self.holeDiameter(obj, base, sub)}) + # Default is treat selection as 'Face' shape + finDep = base.Shape.getElement(sub).BoundBox.ZMin + if base.Shape.getElement(sub).ShapeType == 'Edge': + msg = translate("Path", "Verify Final Depth of holes based on edges. {} depth is: {} mm".format(sub, round(finDep, 4))) + " " + msg += translate("Path", "Always select the bottom edge of the hole when using an edge.") + PathLog.warning(msg) + + # If user has not adjusted Final Depth value, attempt to determine from sub + if obj.OpFinalDepth.Value == obj.FinalDepth.Value: + PathLog.info(translate('Path', 'Auto detecting Final Depth based on {}.'.format(sub))) + trgtDep = finDep + else: + trgtDep = max(obj.FinalDepth.Value, finDep) + + holes.append({'x': pos.x, 'y': pos.y, 'r': self.holeDiameter(obj, base, sub), + 'angle': angle, 'axis': axis, 'trgtDep': trgtDep, + 'stkTop': stock.Shape.BoundBox.ZMax}) + if haveLocations(self, obj): for location in obj.Locations: - holes.append({'x': location.x, 'y': location.y, 'r': 0}) + # holes.append({'x': location.x, 'y': location.y, 'r': 0, 'angle': 0.0, 'axis': 'X', 'finDep': obj.FinalDepth.Value}) + trgtDep = obj.FinalDepth.Value + holes.append({'x': location.x, 'y': location.y, 'r': 0, + 'angle': 0.0, 'axis': 'X', 'trgtDep': trgtDep, + 'stkTop': PathUtils.findParentJob(obj).stock.Shape.BoundBox.ZMax}) + + # If all holes based upon edges, set post-operation Final Depth to highest edge height + if obj.OpFinalDepth.Value == obj.FinalDepth.Value: + if len(holes) == 1: + PathLog.info(translate('Path', "Single-hole operation. Saving Final Depth determined from hole base.")) + obj.FinalDepth.Value = trgtDep if len(holes) > 0: - self.circularHoleExecute(obj, holes) + self.circularHoleExecute(obj, holes) # circularHoleExecute() located in PathDrilling.py + + self.useTempJobClones('Delete') # Delete temp job clone group and contents + self.guiMessage('title', None, show=True) # Process GUI messages to user + PathLog.debug("obj.Name: " + str(obj.Name)) def circularHoleExecute(self, obj, holes): '''circularHoleExecute(obj, holes) ... implement processing of holes. @@ -248,3 +423,443 @@ class ObjectOp(PathOp.ObjectOp): PathLog.debug("holes found: {}".format(holelist)) return features + + # Rotation-related methods + def opDetermineRotationRadii(self, obj): + '''opDetermineRotationRadii(obj) + Determine rotational radii for 4th-axis rotations, for clearance/safe heights ''' + + parentJob = PathUtils.findParentJob(obj) + # bb = parentJob.Stock.Shape.BoundBox + xlim = 0.0 + ylim = 0.0 + zlim = 0.0 + xRotRad = 0.01 + yRotRad = 0.01 + xRotRad = 0.01 + + # Determine boundbox radius based upon xzy limits data + if math.fabs(self.stockBB.ZMin) > math.fabs(self.stockBB.ZMax): + zlim = self.stockBB.ZMin + else: + zlim = self.stockBB.ZMax + + if obj.EnableRotation != 'B(y)': + # Rotation is around X-axis, cutter moves along same axis + if math.fabs(self.stockBB.YMin) > math.fabs(self.stockBB.YMax): + ylim = self.stockBB.YMin + else: + ylim = self.stockBB.YMax + + if obj.EnableRotation != 'A(x)': + # Rotation is around Y-axis, cutter moves along same axis + if math.fabs(self.stockBB.XMin) > math.fabs(self.stockBB.XMax): + xlim = self.stockBB.XMin + else: + xlim = self.stockBB.XMax + + if ylim != 0.0: + xRotRad = math.sqrt(ylim**2 + zlim**2) + if xlim != 0.0: + yRotRad = math.sqrt(xlim**2 + zlim**2) + zRotRad = math.sqrt(xlim**2 + ylim**2) + + clrOfst = parentJob.SetupSheet.ClearanceHeightOffset.Value + safOfst = parentJob.SetupSheet.SafeHeightOffset.Value + + return [(xRotRad, yRotRad, zRotRad), (clrOfst, safOfst)] + + def faceRotationAnalysis(self, obj, norm, surf): + '''faceRotationAnalysis(obj, norm, surf) + Determine X and Y independent rotation necessary to make normalAt = Z=1 (0,0,1) ''' + PathLog.track() + + praInfo = "faceRotationAnalysis(): " + rtn = True + axis = 'X' + orientation = 'X' + angle = 500.0 + precision = 6 + + for i in range(0, 13): + if PathGeom.Tolerance * (i * 10) == 1.0: + precision = i + break + + def roundRoughValues(precision, val): + # Convert VALxe-15 numbers to zero + if PathGeom.isRoughly(0.0, val) is True: + return 0.0 + # Convert VAL.99999999 to next integer + elif math.fabs(val % 1) > 1.0 - PathGeom.Tolerance: + return round(val) + else: + return round(val, precision) + + nX = roundRoughValues(precision, norm.x) + nY = roundRoughValues(precision, norm.y) + nZ = roundRoughValues(precision, norm.z) + praInfo += "\n -normalAt(0,0): " + str(nX) + ", " + str(nY) + ", " + str(nZ) + + saX = roundRoughValues(precision, surf.x) + saY = roundRoughValues(precision, surf.y) + saZ = roundRoughValues(precision, surf.z) + praInfo += "\n -Surface.Axis: " + str(saX) + ", " + str(saY) + ", " + str(saZ) + + # Determine rotation needed and current orientation + if saX == 0.0: + if saY == 0.0: + orientation = "Z" + if saZ == 1.0: + angle = 0.0 + elif saZ == -1.0: + angle = -180.0 + else: + praInfo += "_else_X" + str(saZ) + elif saY == 1.0: + orientation = "Y" + angle = 90.0 + elif saY == -1.0: + orientation = "Y" + angle = -90.0 + else: + if saZ != 0.0: + angle = math.degrees(math.atan(saY / saZ)) + orientation = "Y" + elif saY == 0.0: + if saZ == 0.0: + orientation = "X" + if saX == 1.0: + angle = -90.0 + elif saX == -1.0: + angle = 90.0 + else: + praInfo += "_else_X" + str(saX) + else: + orientation = "X" + ratio = saX / saZ + angle = math.degrees(math.atan(ratio)) + if ratio < 0.0: + praInfo += " NEG-ratio" + # angle -= 90 + else: + praInfo += " POS-ratio" + angle = -1 * angle + if saX < 0.0: + angle = angle + 180.0 + elif saZ == 0.0: + if saY != 0.0: + angle = math.degrees(math.atan(saX / saY)) + orientation = "Y" + + if saX + nX == 0.0: + angle = -1 * angle + if saY + nY == 0.0: + angle = -1 * angle + if saZ + nZ == 0.0: + angle = -1 * angle + + if saY == -1.0 or saY == 1.0: + if nX != 0.0: + angle = -1 * angle + + # Enforce enabled rotation in settings + praInfo += "\n -Initial orientation: {}".format(orientation) + if orientation == 'Y': + axis = 'X' + if obj.EnableRotation == 'B(y)': # Required axis disabled + if angle == 180.0 or angle == -180.0: + axis = 'Y' + else: + rtn = False + elif orientation == 'X': + axis = 'Y' + if obj.EnableRotation == 'A(x)': # Required axis disabled + if angle == 180.0 or angle == -180.0: + axis = 'X' + else: + rtn = False + + if math.fabs(angle) == 0.0: + angle = 0.0 + rtn = False + + if angle == 500.0: + angle == 0.0 + rtn = False + + if rtn is False: + if orientation == 'Z' and angle == 0.0 and obj.ReverseDirection is True: + if obj.EnableRotation == 'B(y)': + axis = 'Y' + rtn = True + + if rtn is True: + self.rotateFlag = True + # rtn = True + if obj.ReverseDirection is True: + if angle < 180.0: + angle = angle + 180.0 + else: + angle = angle - 180.0 + angle = round(angle, precision) + + praInfo += "\n -Rotation analysis: angle: " + str(angle) + ", axis: " + str(axis) + if rtn is True: + praInfo += "\n - ... rotation triggered" + else: + praInfo += "\n - ... NO rotation triggered" + + PathLog.debug("\n" + str(praInfo)) + + return (rtn, angle, axis, praInfo) + + def guiMessage(self, title, msg, show=False): + '''guiMessage(title, msg, show=False) + Handle op related GUI messages to user''' + if msg is not None: + self.guiMsgs.append((title, msg)) + if show is True: + if len(self.guiMsgs) > 0: + if FreeCAD.GuiUp: + from PySide.QtGui import QMessageBox + for entry in self.guiMsgs: + (title, msg) = entry + QMessageBox.warning(None, title, msg) + self.guiMsgs = [] # Reset messages + return True + else: + for entry in self.guiMsgs: + (title, msg) = entry + PathLog.warning("{}:: {}".format(title, msg)) + self.guiMsgs = [] # Reset messages + return True + return False + + def visualAxis(self): + '''visualAxis() + Create visual X & Y axis for use in orientation of rotational operations + Triggered only for PathLog.debug''' + + if not FreeCAD.ActiveDocument.getObject('xAxCyl'): + xAx = 'xAxCyl' + yAx = 'yAxCyl' + FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", "visualAxis") + if FreeCAD.GuiUp: + FreeCADGui.ActiveDocument.getObject('visualAxis').Visibility = False + vaGrp = FreeCAD.ActiveDocument.getObject("visualAxis") + + FreeCAD.ActiveDocument.addObject("Part::Cylinder", xAx) + cyl = FreeCAD.ActiveDocument.getObject(xAx) + cyl.Label = xAx + cyl.Radius = self.xRotRad + cyl.Height = 0.01 + cyl.Placement = FreeCAD.Placement(FreeCAD.Vector(0, 0, 0), FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90)) + cyl.purgeTouched() + if FreeCAD.GuiUp: + cylGui = FreeCADGui.ActiveDocument.getObject(xAx) + cylGui.ShapeColor = (0.667, 0.000, 0.000) + cylGui.Transparency = 85 + cylGui.Visibility = False + vaGrp.addObject(cyl) + + FreeCAD.ActiveDocument.addObject("Part::Cylinder", yAx) + cyl = FreeCAD.ActiveDocument.getObject(yAx) + cyl.Label = yAx + cyl.Radius = self.yRotRad + cyl.Height = 0.01 + cyl.Placement = FreeCAD.Placement(FreeCAD.Vector(0, 0, 0), FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), 90)) + cyl.purgeTouched() + if FreeCAD.GuiUp: + cylGui = FreeCADGui.ActiveDocument.getObject(yAx) + cylGui.ShapeColor = (0.000, 0.667, 0.000) + cylGui.Transparency = 85 + cylGui.Visibility = False + vaGrp.addObject(cyl) + + def useTempJobClones(self, cloneName): + '''useTempJobClones(cloneName) + Manage use of temporary model clones for rotational operation calculations. + Clones are stored in 'rotJobClones' group.''' + if FreeCAD.ActiveDocument.getObject('rotJobClones'): + if cloneName == 'Start': + if PathLog.getLevel(PathLog.thisModule()) < 4: + for cln in FreeCAD.ActiveDocument.getObject('rotJobClones').Group: + FreeCAD.ActiveDocument.removeObject(cln.Name) + elif cloneName == 'Delete': + if PathLog.getLevel(PathLog.thisModule()) < 4: + for cln in FreeCAD.ActiveDocument.getObject('rotJobClones').Group: + FreeCAD.ActiveDocument.removeObject(cln.Name) + FreeCAD.ActiveDocument.removeObject('rotJobClones') + else: + FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", "rotJobClones") + if FreeCAD.GuiUp: + FreeCADGui.ActiveDocument.getObject('rotJobClones').Visibility = False + + if cloneName != 'Start' and cloneName != 'Delete': + FreeCAD.ActiveDocument.getObject('rotJobClones').addObject(FreeCAD.ActiveDocument.getObject(cloneName)) + if FreeCAD.GuiUp: + FreeCADGui.ActiveDocument.getObject(cloneName).Visibility = False + + def cloneBaseAndStock(self, obj, base, angle, axis, subCount): + '''cloneBaseAndStock(obj, base, angle, axis, subCount) + Method called to create a temporary clone of the base and parent Job stock. + Clones are destroyed after usage for calculations related to rotational operations.''' + # Create a temporary clone and stock of model for rotational use. + rndAng = round(angle, 8) + if rndAng < 0.0: # neg sign is converted to underscore in clone name creation. + tag = axis + '_' + axis + '_' + str(math.fabs(rndAng)).replace('.', '_') + else: + tag = axis + str(rndAng).replace('.', '_') + clnNm = obj.Name + '_base_' + '_' + str(subCount) + '_' + tag + stckClnNm = obj.Name + '_stock_' + '_' + str(subCount) + '_' + tag + if clnNm not in self.cloneNames: + self.cloneNames.append(clnNm) + self.cloneNames.append(stckClnNm) + if FreeCAD.ActiveDocument.getObject(clnNm): + FreeCAD.ActiveDocument.getObject(clnNm).Shape = base.Shape + else: + FreeCAD.ActiveDocument.addObject('Part::Feature', clnNm).Shape = base.Shape + self.useTempJobClones(clnNm) + if FreeCAD.ActiveDocument.getObject(stckClnNm): + FreeCAD.ActiveDocument.getObject(stckClnNm).Shape = PathUtils.findParentJob(obj).Stock.Shape + else: + FreeCAD.ActiveDocument.addObject('Part::Feature', stckClnNm).Shape = PathUtils.findParentJob(obj).Stock.Shape + self.useTempJobClones(stckClnNm) + if FreeCAD.GuiUp: + FreeCADGui.ActiveDocument.getObject(stckClnNm).Transparency = 90 + FreeCADGui.ActiveDocument.getObject(clnNm).ShapeColor = (1.000, 0.667, 0.000) + clnBase = FreeCAD.ActiveDocument.getObject(clnNm) + clnStock = FreeCAD.ActiveDocument.getObject(stckClnNm) + tag = base.Name + '_' + tag + return (clnBase, clnStock, tag) + + def getFaceNormAndSurf(self, face): + '''getFaceNormAndSurf(face) + Return face.normalAt(0,0) or face.normal(0,0) and face.Surface.Axis vectors + ''' + norm = FreeCAD.Vector(0.0, 0.0, 0.0) + surf = FreeCAD.Vector(0.0, 0.0, 0.0) + + if face.ShapeType == 'Edge': + edgToFace = Part.Face(Part.Wire(Part.__sortEdges__([face]))) + face = edgToFace + + if hasattr(face, 'normalAt'): + n = face.normalAt(0, 0) + elif hasattr(face, 'normal'): + n = face.normal(0, 0) + if hasattr(face.Surface, 'Axis'): + s = face.Surface.Axis + else: + s = n + + norm.x = n.x + norm.y = n.y + norm.z = n.z + surf.x = s.x + surf.y = s.y + surf.z = s.z + return (norm, surf) + + def applyRotationalAnalysis(self, obj, base, angle, axis, subCount): + '''applyRotationalAnalysis(obj, base, angle, axis, subCount) + Create temp clone and stock and apply rotation to both. + Return new rotated clones + ''' + if axis == 'X': + vect = FreeCAD.Vector(1, 0, 0) + elif axis == 'Y': + vect = FreeCAD.Vector(0, 1, 0) + + if obj.InverseAngle is True: + angle = -1 * angle + if math.fabs(angle) == 0.0: + angle = 0.0 + + # Create a temporary clone of model for rotational use. + (clnBase, clnStock, tag) = self.cloneBaseAndStock(obj, base, angle, axis, subCount) + + # Rotate base to such that Surface.Axis of pocket bottom is Z=1 + clnBase = Draft.rotate(clnBase, angle, center=FreeCAD.Vector(0.0, 0.0, 0.0), axis=vect, copy=False) + clnStock = Draft.rotate(clnStock, angle, center=FreeCAD.Vector(0.0, 0.0, 0.0), axis=vect, copy=False) + + clnBase.purgeTouched() + clnStock.purgeTouched() + return (clnBase, angle, clnStock, tag) + + def applyInverseAngle(self, obj, clnBase, clnStock, axis, angle): + '''applyInverseAngle(obj, clnBase, clnStock, axis, angle) + Apply rotations to incoming base and stock objects.''' + if axis == 'X': + vect = FreeCAD.Vector(1, 0, 0) + elif axis == 'Y': + vect = FreeCAD.Vector(0, 1, 0) + # Rotate base to inverse of original angle + clnBase = Draft.rotate(clnBase, (-2 * angle), center=FreeCAD.Vector(0.0, 0.0, 0.0), axis=vect, copy=False) + clnStock = Draft.rotate(clnStock, (-2 * angle), center=FreeCAD.Vector(0.0, 0.0, 0.0), axis=vect, copy=False) + clnBase.purgeTouched() + clnStock.purgeTouched() + # Update property and angle values + obj.InverseAngle = True + obj.AttemptInverseAngle = False + angle = -1 * angle + return (clnBase, clnStock, angle) + + def calculateStartFinalDepths(self, obj, shape, stock): + '''calculateStartFinalDepths(obj, shape, stock) + Calculate correct start and final depths for the shape(face) object provided.''' + finDep = max(obj.FinalDepth.Value, shape.BoundBox.ZMin) + stockTop = stock.Shape.BoundBox.ZMax + if obj.EnableRotation == 'Off': + strDep = obj.StartDepth.Value + if strDep <= finDep: + strDep = stockTop + else: + strDep = min(obj.StartDepth.Value, stockTop) + if strDep <= finDep: + strDep = stockTop # self.strDep + msg = translate('Path', "Start depth <= face depth.\nIncreased to stock top.") + PathLog.error(msg) + return (strDep, finDep) + + def sortTuplesByIndex(self, TupleList, tagIdx): + '''sortTuplesByIndex(TupleList, tagIdx) + sort list of tuples based on tag index provided + return (TagList, GroupList) + ''' + # Separate elements, regroup by orientation (axis_angle combination) + TagList = ['X34.2'] + GroupList = [[(2.3, 3.4, 'X')]] + for tup in TupleList: + if tup[tagIdx] in TagList: + # Determine index of found string + i = 0 + for orn in TagList: + if orn == tup[4]: + break + i += 1 + GroupList[i].append(tup) + else: + TagList.append(tup[4]) # add orientation entry + GroupList.append([tup]) # add orientation entry + # Remove temp elements + TagList.pop(0) + GroupList.pop(0) + return (TagList, GroupList) + + def warnDisabledAxis(self, obj, axis, sub=''): + '''warnDisabledAxis(self, obj, axis) + Provide user feedback if required axis is disabled''' + if axis == 'X' and obj.EnableRotation == 'B(y)': + msg = translate('Path', "{}:: {} is inaccessible.".format(obj.Name, sub)) + " " + msg += translate('Path', "Selected feature(s) require 'Enable Rotation: A(x)' for access.") + PathLog.warning(msg) + return True + elif axis == 'Y' and obj.EnableRotation == 'A(x)': + msg = translate('Path', "{}:: {} is inaccessible.".format(obj.Name, sub)) + " " + msg += translate('Path', "Selected feature(s) require 'Enable Rotation: B(y)' for access.") + PathLog.warning(msg) + return True + else: + return False diff --git a/src/Mod/Path/PathScripts/PathDrilling.py b/src/Mod/Path/PathScripts/PathDrilling.py index ab7e1090b2..70b3306832 100644 --- a/src/Mod/Path/PathScripts/PathDrilling.py +++ b/src/Mod/Path/PathScripts/PathDrilling.py @@ -21,6 +21,12 @@ # * USA * # * * # *************************************************************************** +# * * +# * Additional modifications and contributions beginning 2019 * +# * Focus: 4th-axis integration * +# * by Russell Johnson * +# * * +# *************************************************************************** from __future__ import print_function @@ -37,6 +43,10 @@ __title__ = "Path Drilling Operation" __author__ = "sliptonic (Brad Collette)" __url__ = "http://www.freecadweb.org" __doc__ = "Path Drilling operation." +__contributors__ = "russ4262 (Russell Johnson)" +__created__ = "2014" +__scriptVersion__ = "1c testing" +__lastModified__ = "2019-06-25 14:49 CST" LOGLEVEL = False @@ -57,6 +67,7 @@ class ObjectDrilling(PathCircularHoleBase.ObjectOp): def circularHoleFeatures(self, obj): '''circularHoleFeatures(obj) ... drilling works on anything, turn on all Base geometries and Locations.''' + # return PathOp.FeatureBaseGeometry | PathOp.FeatureLocations | PathOp.FeatureRotation return PathOp.FeatureBaseGeometry | PathOp.FeatureLocations def initCircularHoleOperation(self, obj): @@ -71,9 +82,26 @@ class ObjectDrilling(PathCircularHoleBase.ObjectOp): obj.addProperty("App::PropertyDistance", "RetractHeight", "Drill", QtCore.QT_TRANSLATE_NOOP("App::Property", "The height where feed starts and height during retract tool when path is finished")) + # Rotation related properties + if not hasattr(obj, 'EnableRotation'): + obj.addProperty("App::PropertyEnumeration", "EnableRotation", "Rotation", QtCore.QT_TRANSLATE_NOOP("App::Property", "Enable rotation to gain access to pockets/areas not normal to Z axis.")) + obj.EnableRotation = ['Off', 'A(x)', 'B(y)', 'A & B'] + if not hasattr(obj, 'ReverseDirection'): + obj.addProperty('App::PropertyBool', 'ReverseDirection', 'Rotation', QtCore.QT_TRANSLATE_NOOP('App::Property', 'Reverse direction of pocket operation.')) + if not hasattr(obj, 'InverseAngle'): + obj.addProperty('App::PropertyBool', 'InverseAngle', 'Rotation', QtCore.QT_TRANSLATE_NOOP('App::Property', 'Inverse the angle. Example: -22.5 -> 22.5 degrees.')) + if not hasattr(obj, 'B_AxisErrorOverride'): + obj.addProperty('App::PropertyBool', 'B_AxisErrorOverride', 'Rotation', QtCore.QT_TRANSLATE_NOOP('App::Property', 'Match B rotations to model (error in FreeCAD rendering).')) + if not hasattr(obj, 'AttemptInverseAngle'): + obj.addProperty('App::PropertyBool', 'AttemptInverseAngle', 'Rotation', QtCore.QT_TRANSLATE_NOOP('App::Property', 'Attempt the inverse angle for face access if original rotation fails.')) + def circularHoleExecute(self, obj, holes): '''circularHoleExecute(obj, holes) ... generate drill operation for each hole in holes.''' PathLog.track() + PathLog.debug("\ncircularHoleExecute() in PathDrilling.py") + + lastAxis = None + lastAngle = 0.0 self.commandlist.append(Path.Command("(Begin Drilling)")) @@ -89,36 +117,91 @@ class ObjectDrilling(PathCircularHoleBase.ObjectOp): self.commandlist.append(Path.Command(obj.ReturnLevel)) # ml: I'm not sure whey these were here, they seem redundant - ## rapid to first hole location, with spindle still retracted: - #p0 = holes[0] - #self.commandlist.append(Path.Command('G0', {'X': p0['x'], 'Y': p0['y'], 'F': self.horizRapid})) - ## move tool to clearance plane - #self.commandlist.append(Path.Command('G0', {'Z': obj.ClearanceHeight.Value, 'F': self.vertRapid})) - - cmd = "G81" - cmdParams = {} - cmdParams['Z'] = obj.FinalDepth.Value - tiplength - cmdParams['F'] = self.vertFeed - cmdParams['R'] = obj.RetractHeight.Value - if obj.PeckEnabled and obj.PeckDepth.Value > 0: - cmd = "G83" - cmdParams['Q'] = obj.PeckDepth.Value - elif obj.DwellEnabled and obj.DwellTime > 0: - cmd = "G82" - cmdParams['P'] = obj.DwellTime + # # rapid to first hole location, with spindle still retracted: + # p0 = holes[0] + # self.commandlist.append(Path.Command('G0', {'X': p0['x'], 'Y': p0['y'], 'F': self.horizRapid})) + # # move tool to clearance plane + # self.commandlist.append(Path.Command('G0', {'Z': obj.ClearanceHeight.Value, 'F': self.vertRapid})) for p in holes: + cmd = "G81" + cmdParams = {} + cmdParams['Z'] = p['trgtDep'] - tiplength + cmdParams['F'] = self.vertFeed + cmdParams['R'] = obj.RetractHeight.Value + if obj.PeckEnabled and obj.PeckDepth.Value > 0: + cmd = "G83" + cmdParams['Q'] = obj.PeckDepth.Value + elif obj.DwellEnabled and obj.DwellTime > 0: + cmd = "G82" + cmdParams['P'] = obj.DwellTime + params = {} params['X'] = p['x'] params['Y'] = p['y'] params.update(cmdParams) - self.commandlist.append(Path.Command(cmd, params)) + if obj.EnableRotation != 'Off': + angle = p['angle'] + axis = p['axis'] + # Rotate model to index for hole + if axis == 'X': + axisOfRot = 'A' + elif axis == 'Y': + axisOfRot = 'B' + # Reverse angle temporarily to match model. Error in FreeCAD render of B axis rotations + if obj.B_AxisErrorOverride is True: + angle = -1 * angle + elif axis == 'Z': + axisOfRot = 'C' + else: + axisOfRot = 'A' - self.commandlist.append(Path.Command('G80')) + # Set initial values for last axis and angle + if lastAxis is None: + lastAxis = axisOfRot + lastAngle = angle + + # Handle axial and angular transitions + if axisOfRot != lastAxis: + self.commandlist.append(Path.Command('G0', {'Z': obj.SafeHeight.Value, 'F': self.vertRapid})) + self.commandlist.append(Path.Command('G0', {lastAxis: 0.0, 'F': self.axialRapid})) + elif angle != lastAngle: + self.commandlist.append(Path.Command('G0', {'Z': obj.SafeHeight.Value, 'F': self.vertRapid})) + + # Prepare for drilling cycle + self.commandlist.append(Path.Command('G0', {axisOfRot: angle, 'F': self.axialRapid})) + self.commandlist.append(Path.Command('G0', {'X': p['x'], 'Y': p['y'], 'F': self.horizRapid})) + self.commandlist.append(Path.Command('G1', {'Z': p['stkTop'], 'F': self.vertFeed})) + + # Perform and cancel canned drilling cycle + self.commandlist.append(Path.Command(cmd, params)) + self.commandlist.append(Path.Command('G80')) + + # shift axis and angle values + if obj.EnableRotation != 'Off': + lastAxis = axisOfRot + lastAngle = angle + + if obj.EnableRotation != 'Off': + self.commandlist.append(Path.Command('G0', {'Z': obj.SafeHeight.Value, 'F': self.vertRapid})) + self.commandlist.append(Path.Command('G0', {lastAxis: 0.0, 'F': self.axialRapid})) def opSetDefaultValues(self, obj, job): '''opSetDefaultValues(obj, job) ... set default value for RetractHeight''' - obj.RetractHeight = 10 + obj.RetractHeight = 10.0 + obj.ReverseDirection = False + obj.InverseAngle = False + obj.B_AxisErrorOverride = False + obj.AttemptInverseAngle = False + + # Initial setting for EnableRotation is taken from Job SetupSheet + # User may override on per-operation basis as needed. + parentJob = PathUtils.findParentJob(obj) + if hasattr(parentJob.SetupSheet, 'SetupEnableRotation'): + obj.EnableRotation = parentJob.SetupSheet.SetupEnableRotation + else: + obj.EnableRotation = 'Off' + def SetupProperties(): setup = [] @@ -129,9 +212,15 @@ def SetupProperties(): setup.append("AddTipLength") setup.append("ReturnLevel") setup.append("RetractHeight") + setup.append("EnableRotation") + setup.append("ReverseDirection") + setup.append("InverseAngle") + setup.append("B_AxisErrorOverride") + setup.append("AttemptInverseAngle") return setup -def Create(name, obj = None): + +def Create(name, obj=None): '''Create(name) ... Creates and returns a Drilling operation.''' if obj is None: obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", name)