示例#1
0
    def getArrowPosition(self):
        """"
         Find out the vector and rotation of the arrow to be drawn.
        """
        #      For now the arrow will be at the top
        rotation = [0.0, 0.0, 0.0, 0.0]
        self.direction = faced.getDirectionAxis()  # Must be getSelectionEx

        if (self.direction == "+x"):
            rotation = [0.0, -1.0, 0.0, 90.0]
        elif (self.direction == "-x"):
            rotation = [0.0, 1.0, 0.0, 90.0]
        elif (self.direction == "+y"):
            rotation = [1.0, 0.0, 0.0, 90.0]
        elif (self.direction == "-y"):
            rotation = [-1.0, 0.0, 0.0, 90.0]
        elif (self.direction == "+z"):
            rotation = [1.0, 0.0, 0.0, 180.0]
        elif (self.direction == "-z"):
            rotation = [1.0, 0.0, 0.0, 0.0]

        if self.objectType == 'Shape':
            # 'Shape'
            # The whole object is selected
            if (self.direction == "+x" or self.direction == "-x"):
                if (self.direction == "+x"):
                    self._vector.x = self.selectedObj[0].Object.Shape.BoundBox.XMax + \
                        self.AwayFrom3DObject
                else:  # (direction=="-x"):
                    self._vector.x = self.selectedObj[0].Object.Shape.BoundBox.XMax - \
                        self.AwayFrom3DObject

                self._vector.y = self.selectedObj[
                    0].Object.Shape.BoundBox.YMax / 2
                self._vector.z = self.selectedObj[
                    0].Object.Shape.BoundBox.ZMax / 2

            elif (self.direction == "+y" or self.direction == "-y"):
                if (self.direction == "+y"):
                    self._vector.y = self.selectedObj[0].Object.Shape.BoundBox.YMax + \
                        self.AwayFrom3DObject
                else:  # (direction=="-y"):
                    self._vector.y = self.selectedObj[0].Object.Shape.BoundBox.YMax - \
                        self.AwayFrom3DObject
                self._vector.x = self.selectedObj[
                    0].Object.Shape.BoundBox.XMax / 2
                self._vector.z = self.selectedObj[
                    0].Object.Shape.BoundBox.ZMax / 2

            elif (self.direction == "+z" or self.direction == "-z"):
                if (self.direction == "+z"):
                    self._vector.z = self.selectedObj[0].Object.Shape.BoundBox.ZMax + \
                        self.AwayFrom3DObject
                else:  # (direction=="-z"):
                    self._vector.z = self.selectedObj[0].Object.Shape.BoundBox.ZMax - \
                        self.AwayFrom3DObject
                    self._vector.x = self.selectedObj[
                        0].Object.Shape.BoundBox.XMax / 2
                    self._vector.y = self.selectedObj[
                        0].Object.Shape.BoundBox.YMax / 2
            return rotation

        vectors = self.selectedObj[0].SubObjects[0].Vertexes
        if self.objectType == 'Face':
            self._vector.z = vectors[0].Z
            for i in vectors:
                self._vector.x += i.X
                self._vector.y += i.Y
                self._vector.z += i.Z
            self._vector.x = self._vector.x / 4
            self._vector.y = self._vector.y / 4
            self._vector.z = self._vector.z / 4

        elif self.objectType == 'Edge':
            # One edge is selected
            self._vector.z = vectors[0].Z
            for i in vectors:
                self._vector.x += i.X
                self._vector.y += i.Y
                self._vector.z += i.Z
            self._vector.x = self._vector.x / 2
            self._vector.y = self._vector.y / 2
            self._vector.z = self._vector.z / 2

        if self.direction == "+x":
            self._vector.x = self._vector.x + self.AwayFrom3DObject
        elif self.direction == "-x":
            self._vector.x = self._vector.x - self.AwayFrom3DObject
        elif self.direction == "+y":
            self._vector.y = self._vector.y + self.AwayFrom3DObject
        elif self.direction == "-y":
            self._vector.y = self._vector.y - self.AwayFrom3DObject
        elif self.direction == "+z":
            self._vector.z = self._vector.z + self.AwayFrom3DObject
        elif self.direction == "-z":
            self._vector.z = self._vector.z - self.AwayFrom3DObject

        return rotation
    def runClass(self):
        try:
            sel = Gui.Selection.getSelectionEx()
            if (len(sel) < 1 or len(sel) > 1 or len(
                    Gui.Selection.getSelectionEx()[0].SubElementNames) == 0):
                # Two object must be selected
                errMessage = "Select a face to use LoftOnDirection Tool"
                faced.getInfo(sel[0]).errorDialog(errMessage)
                return

            selectedEdge = Gui.Selection.getSelectionEx()[0].SubObjects[
                0]  # select one element
            SubElementName = Gui.Selection.getSelectionEx(
            )[0].SubElementNames[0]

            #### configuration ####
            ValueLength = -(float)(self.inLength.value())
            ValueScaleX = (float)(self.inScaleX.value())
            ValueScaleY = (float)(self.inScaleY.value())
            ValueScaleZ = (float)(self.inScaleZ.value())

            ####
            createAxis = self.chkAxis.isChecked()  # 0 = not Axis, other = Axis
            createLoft = self.chkLoft.isChecked()  # 0 = not loft, other = loft
            #### configuration ####
            App.ActiveDocument.openTransaction(
                translate("Design456", "LoftOnDirection"))
            if hasattr(selectedEdge, 'Surface'):
                plr = plDirection = App.Placement()

                # section direction
                yL = selectedEdge.CenterOfMass
                uv = selectedEdge.Surface.parameter(yL)
                nv = selectedEdge.normalAt(uv[0], uv[1])
                direction = yL.sub(nv + yL)
                r = App.Rotation(App.Vector(0, 0, 0), direction)
                plDirection.Rotation.Q = r.Q
                #print(r.Q)
                plDirection.Base = yL
                plr = plDirection
                #print("surface : ", sel[0].Name, " ",SubElementName, "  ", direction)
                # section direction

                # section axis
                if createAxis != 0:
                    # section axis
                    points = [
                        App.Vector(0.0, 0.0, 0.0),
                        App.Vector(0.0, 0.0, ValueLength)
                    ]
                    centerX = _draft.makeWire(points,
                                              closed=False,
                                              face=False,
                                              support=None)
                    centerX.Placement = plr
                    centerX.Label = "Axis_" + SubElementName
                    # section axis

                #### section scale ####
                if createLoft != 0:
                    #### section scale ####
                    _part.show(selectedEdge.copy())
                    firstFace = App.ActiveDocument.ActiveObject
                    objClone = _draft.scale(
                        firstFace,
                        App.Vector(ValueScaleX, ValueScaleY, ValueScaleZ),
                        center=App.Vector(plDirection.Base),
                        copy=True)  # False

                    # section placement face in length and direction
                    newLocation = (App.Vector(direction).scale(
                        ValueLength, ValueLength, ValueLength))
                    if (direction.x != 0 and abs(direction.x) == direction.x):
                        newLocation.x = newLocation.x + selectedEdge.Placement.Base.x * direction.x
                    elif (direction.x != 0
                          and abs(direction.x) != direction.x):
                        newLocation.x = newLocation.x - selectedEdge.Placement.Base.x * direction.x
                    else:
                        newLocation.x = selectedEdge.Placement.Base.x
                    if (direction.y != 0
                            and abs(direction.y) == direction.y):  #positive >0
                        newLocation.y = newLocation.y + selectedEdge.Placement.Base.y * direction.y
                    elif (direction.y != 0
                          and abs(direction.x) != direction.y):  #negative <0
                        newLocation.y = newLocation.y - selectedEdge.Placement.Base.y * direction.y
                    else:
                        newLocation.y = selectedEdge.Placement.Base.y
                    if (direction.z != 0 and abs(direction.z) == direction.z):
                        newLocation.z = newLocation.z + selectedEdge.Placement.Base.z * direction.z
                    elif (direction.z != 0
                          and abs(direction.z) != direction.z):  #negative <0:
                        newLocation.z = newLocation.z - selectedEdge.Placement.Base.z * direction.z
                    else:
                        newLocation.z = selectedEdge.Placement.Base.z
                    objClone.Placement.Base = newLocation

                    # section loft
                    newObj = App.ActiveDocument.addObject('Part::Loft', 'Loft')
                    App.ActiveDocument.ActiveObject.Sections = [
                        App.ActiveDocument.getObject(firstFace.Name),
                        App.ActiveDocument.getObject(objClone.Name),
                    ]
                    App.ActiveDocument.ActiveObject.Solid = True
                    newObj = App.ActiveDocument.ActiveObject
                    App.ActiveDocument.recompute()

                    # copy
                    App.ActiveDocument.addObject('Part::Feature', newObj.Name +
                                                 'N').Shape = _part.getShape(
                                                     newObj,
                                                     '',
                                                     needSubElement=False,
                                                     refine=True)
                    App.ActiveDocument.recompute()

                    # Remove Old objects. I don't like to keep so many objects without any necessity.

                    for obj in newObj.Sections:
                        App.ActiveDocument.removeObject(obj.Name)
                    App.ActiveDocument.removeObject(newObj.Name)
                    App.ActiveDocument.commitTransaction()
                    App.ActiveDocument.recompute()
                    # section hidden faces work
            self.window.hide()
        except Exception as err:
            App.Console.PrintError("'Design456_loftOnDirection' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def makeIt(self, commandType):
        self.commandType = commandType
        selection = Gui.Selection.getSelectionEx()
        # Two object must be selected
        if(len(selection) < 2 or len(selection) > 2):
            errMessage = "Select two objects to use Common 2D Tool"
            faced.getInfo(selection).errorDialog(errMessage)
        else:
            nObjects = []
            nObjects.clear()
            GlobalPlacement = App.activeDocument().getObject(
                selection[0].Object.Name).Placement
            for a2dobj in selection:
                m = App.activeDocument().getObject(a2dobj.Object.Name)
                f = App.activeDocument().addObject('Part::Extrusion', 'ExtrudeOriginal')
                f.Base = App.activeDocument().getObject(m.Name)
                f.DirMode = "Normal"
                f.DirLink = a2dobj.Object
                f.LengthFwd = 1.00
                f.LengthRev = 0.0
                f.Solid = True
                f.Reversed = False
                f.Symmetric = False
                f.TaperAngle = 0.0
                f.TaperAngleRev = 0.0
                App.ActiveDocument.recompute()

                # Make a simple copy of the object
                newShape = Part.getShape(
                    f, '', needSubElement=False, refine=True)
                newObj = App.ActiveDocument.addObject(
                    'Part::Feature', 'Extrude')
                newObj.Shape = newShape
                App.ActiveDocument.recompute()
                App.ActiveDocument.ActiveObject.Label = f.Label
                App.ActiveDocument.recompute()
                App.ActiveDocument.removeObject(f.Name)
                App.ActiveDocument.removeObject(m.Name)
                App.ActiveDocument.recompute()
                nObjects.append(newObj)

            tempResult = self.DoCommand(self.commandType)
            if(commandType == 1):
                tempResult.Shapes = nObjects
            elif(commandType == 2 or commandType == 3):
                tempResult.Tool = nObjects[1]
                tempResult.Base = nObjects[0]
            App.ActiveDocument.recompute()
            newShape = Part.getShape(
                tempResult, '', needSubElement=False, refine=True)
            Result = App.ActiveDocument.addObject('Part::Feature', 'Shape')
            Result.Shape = newShape
            for name in nObjects:
                App.ActiveDocument.removeObject(name.Name)
            App.ActiveDocument.removeObject(tempResult.Name)
            Gui.Selection.clearSelection()
            App.ActiveDocument.recompute()
            Gui.Selection.addSelection(App.ActiveDocument.Name, Result.Name)
            s = Gui.Selection.getSelectionEx()[0]
            obFace = faced.getInfo(s)
            faceName = obFace.SelectTopFace()
            # Extract the face
            sh = Result.Shape.copy()
            sh.Placement = GlobalPlacement  # Result.Placement
            sh.Placement.Base.z = -1
            newobj = Result.Document.addObject(
                "Part::Feature", self.localShapeName)
            newobj.Shape = sh.getElement(faceName)
            App.ActiveDocument.removeObject(Result.Name)
            del nObjects[:]
示例#4
0
    def calculateRotatedNormal(self, Wheelaxis):
        """[calculate placement, angle of rotation, axis of rotation based on the]

        Args:
            Wheelaxis ([str]): [Direction of the wheel coin widget - Axis type ]

        Returns:
            [Base.placement]: [Placement, rotation angle and axis of rotation for face2]
        """
        if self.isItRotation is True:
            return  # We shouldn't be here.

        faceRotation = 0
        # TODO: Lets take only X axis first , then Y ..etc and so on.
        face1Obj = self.ExtractedFaces[0]
        pl = self.ExtractedFaces[0].Placement
        self.faceDir = faced.getDirectionAxis(self.selected)  # face direction

        # THIS PART WILL BE COMPLICATED AND MUST BE WELL WRITTEN.

        # Wheelaxis color: RED is X , GREEN is Y,  FR_BLUEVIOLET is 45 and ORANGE is 135
        s = self.ExtractedFaces[1]
        # Reset the placement of the object if was not correct
        s.Placement = self.ExtractedFaces[0].Placement
        ax = self.selectedObj.Object.Shape.CenterOfMass
        if self.faceDir == "+x" and Wheelaxis == "X":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 90, 0)
            self.ExtractedFaces[1].Placement.Base.x = self.ExtractedFaces[1].Placement.Base.x + \
                self.ExtractedFaces[1].Shape.BoundBox.XLength
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-x" and Wheelaxis == "X":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 90, 0)
            self.ExtractedFaces[1].Placement.Base.x = self.ExtractedFaces[1].Placement.Base.x - \
                self.ExtractedFaces[1].Shape.BoundBox.XLength
            pl = self.ExtractedFaces[1].Placement

        elif (self.faceDir == "+x"
              and Wheelaxis == "Y") or (self.faceDir == "-x"
                                        and Wheelaxis == "Y"):
            # We do nothing .. it is ok to not change
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "+y" and Wheelaxis == "X":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 0, -90)
            self.ExtractedFaces[1].Placement.Base.y = self.ExtractedFaces[1].Placement.Base.y + \
                self.ExtractedFaces[1].Shape.BoundBox.YLength
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-y" and Wheelaxis == "X":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 0, 90)
            self.ExtractedFaces[1].Placement.Base.y = self.ExtractedFaces[1].Placement.Base.y - \
                self.ExtractedFaces[1].Shape.BoundBox.YLength
            pl = self.ExtractedFaces[1].Placement

        elif (self.faceDir == "+y"
              and Wheelaxis == "Y") or (self.faceDir == "-y"
                                        and Wheelaxis == "Y"):
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-z" and Wheelaxis == "X" or (
                self.faceDir == "+z" and Wheelaxis == "X"):
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "+z" and Wheelaxis == "Y":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 0, -90)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-z" and Wheelaxis == "Y":
            faced.RealRotateObjectToAnAxis(s, ax, 0, 0, 90)
            pl = self.ExtractedFaces[1].Placement

        # Now we have 45Degrees :
        if self.faceDir == "+x" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 45, 0)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-x" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 45, 0)
            pl = self.ExtractedFaces[1].Placement

        # Now we have 45 Degrees :
        if self.faceDir == "+y" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 0, -45)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-y" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 0, -45)
            pl = self.ExtractedFaces[1].Placement

            # Now we have 45 and 135 Degrees :
        if self.faceDir == "+z" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 0, 45)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-z" and Wheelaxis == "45":
            faced.RotateObjectToCenterPoint(s, 0, 0, 45)
            pl = self.ExtractedFaces[1].Placement

        # Now we have 135 Degrees :
        if self.faceDir == "+x" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 135, 0)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-x" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 135, 0)
            pl = self.ExtractedFaces[1].Placement

        if self.faceDir == "+y" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 0, -135)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-y" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 0, -135)
            pl = self.ExtractedFaces[1].Placement

        if self.faceDir == "+z" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 0, 135)
            pl = self.ExtractedFaces[1].Placement

        elif self.faceDir == "-z" and Wheelaxis == "135":
            faced.RotateObjectToCenterPoint(s, 0, 0, 135)
            pl = self.ExtractedFaces[1].Object.Placement

        return pl
示例#5
0
    def Activated(self):
        """[ Executes when the tool is used   ]
        """
        import ThreeDWidgets.fr_coinwindow as win
        try:

            print("Smart ExtrudeRotate")
            self.selected = Gui.Selection.getSelectionEx()
            if len(self.selected) == 0:
                # An object must be selected
                errMessage = "Select an object, one face to Extrude"
                faced.errorDialog(errMessage)
                return
            self.selectedObj = self.selected[0]
            faced.EnableAllToolbar(False)
            self.faceDir = faced.getDirectionAxis(
                self.selected)  # face direction

            # Undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "SmartExtrudeRotate"))
            self.ExtractedFaces.clear()
            if self.isFaceOf3DObj(
            ):  # We must know if the selection is a 2D face or a face from a 3D object
                # We have a 3D Object. Extract a face and start to Extrude
                self.extractFaces()
            else:
                # We have a 2D Face - Extract it directly
                sh = self.selectedObj.Object.Shape.copy()
                o = App.ActiveDocument.addObject("Part::Feature",
                                                 "MovableFace")
                o.Shape = sh
                self.ExtractedFaces.append(self.selectedObj.Object)
                self.ExtractedFaces.append(App.ActiveDocument.getObject(
                    o.Name))
            facingdir = self.faceDir.upper()
            facingdir = facingdir[1:]
            print(facingdir, "facingdir")
            # Decide how the Degree Wheel be drawn
            self.setupRotation = self.calculateNewVector()
            if self.faceDir == "+z" or self.faceDir == "-z":
                self.wheelObj = Fr_DegreeWheel_Widget(
                    [self.FirstLocation,
                     App.Vector(0, 0, 0)],
                    str(round(self.w_rotation[3], 2)) + "°", 1,
                    FR_COLOR.FR_RED, [0, 0, 0, 0], self.setupRotation,
                    [2.0, 2.0, 2.0], 2, facingdir)
            else:
                self.wheelObj = Fr_DegreeWheel_Widget(
                    [self.FirstLocation,
                     App.Vector(0, 0, 0)],
                    str(round(self.w_rotation[3], 2)) + "°", 1,
                    FR_COLOR.FR_RED, [0, 0, 0, 0], self.setupRotation,
                    [2.0, 2.0, 2.0], 1, facingdir)

            # Define the callbacks. We have many callbacks here.
            # TODO: FIXME:

            # Different callbacks for each action.
            self.wheelObj.w_wheel_cb_ = callback_Rotate
            self.wheelObj.w_xAxis_cb_ = callback_moveX
            self.wheelObj.w_yAxis_cb_ = callback_moveY
            self.wheelObj.w_45Axis_cb_ = callback_move45
            self.wheelObj.w_135Axis_cb_ = callback_move135

            self.wheelObj.w_callback_ = callback_release
            self.wheelObj.w_userData.callerObject = self
            self.newObject = App.ActiveDocument.addObject(
                'Part::Loft', 'ExtendFace')
            self.newObject.Sections = self.ExtractedFaces
            self.newObject.Solid = True
            self.newObject.Ruled = False  # TODO: SHOULD THIS BE RULED?
            self.newObject.Closed = False  # TODO: SHOULD THIS BE CLOSED?
            self.ExtractedFaces[0].Visibility = False
            self.ExtractedFaces[1].Visibility = False
            if self._mywin is None:
                self._mywin = win.Fr_CoinWindow()

            self._mywin.addWidget(self.wheelObj)
            mw = self.getMainWindow()
            self._mywin.show()

            # TODO: FIXME:
            # loft will be used . make some experementations.
            # But when should we use sweep???? don't know now

            App.ActiveDocument.recompute()

        except Exception as err:
            faced.EnableAllToolbar(True)
            App.Console.PrintError(
                "'Design456_ExtrudeRotate' ExtractFace-Failed. "
                "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#6
0
    def Activated(self):
        """[Executes when the tool is used]
        """
        import ThreeDWidgets.fr_coinwindow as win
        try:
            print("Smart Extrusion")
            sel = Gui.Selection.getSelectionEx()
            if len(sel) == 0:
                # An object must be selected
                errMessage = "Select a face to Extrude"
                faced.errorDialog(errMessage)
                return
            self.selectedObj = sel[0]
            # Whole object is selected TODO: FIXME: Check if this works always.
            if len(self.selectedObj.SubObjects) == 0:
                errMessage = "Select a face to Extrude"
                faced.errorDialog(errMessage)
                return
            faced.EnableAllToolbar(False)
            # Undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "SmartExtrude"))
            self.WasFaceFrom3DObject = self.isFaceOf3DObj()
            if self.WasFaceFrom3DObject is True:  # We must know if the selection is a 2D face or a face from a 3D object
                # We have a 3D Object. Extract a face and start to Extrude
                self.targetFace = self.extractFace()
            else:
                # We have a 2D Face - Extract it directly
                self.targetFace = self.selectedObj.Object

            rotation = self.getArrowPosition()
            self.smartInd = Fr_Arrow_Widget(self._vector, [
                "  Length 0.0",
            ], 1, FR_COLOR.FR_RED, FR_COLOR.FR_WHITE, rotation,
                                            [1.2, 1.2, 1.2], 3, 0.0)

            self.smartInd.w_callback_ = callback_release
            self.smartInd.w_move_callback_ = callback_move
            self.smartInd.w_userData.callerObject = self
            if self._mywin is None:
                self._mywin = win.Fr_CoinWindow()

            self._mywin.addWidget(self.smartInd)
            mw = self.getMainWindow()
            self._mywin.show()

            self.newObject = App.ActiveDocument.addObject(
                'Part::Extrusion', 'Extrude')
            self.newObject.Base = self.targetFace
            self.newObject.DirMode = "Normal"  # Don't use Custom as it causes a PROBLEM!
            # Above statement is not always correct. Some faces require 'custom'
            self.newObject.DirLink = None
            self.newObject.LengthFwd = self.extrudeLength  # Must be negative
            self.newObject.LengthRev = 0.0
            self.newObject.Solid = True
            self.newObject.Reversed = False
            self.newObject.Symmetric = False
            self.newObject.TaperAngle = 0.0
            self.newObject.TaperAngleRev = 0.0
            self.newObject.Dir = Gui.ActiveDocument.getObject(
                self.targetFace.Name).Object.Shape.Faces[0].normalAt(0, 0)
            if (self.newObject.Dir.x != 1 or self.newObject.Dir.y != 1
                    or self.newObject.Dir.z != 1):
                self.newObject.DirMode = "Custom"

            App.ActiveDocument.recompute()

        except Exception as err:
            faced.EnableAllToolbar(True)
            App.Console.PrintError("'Design456_Extrude' Activated-Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#7
0
    def Activated(self):

        try:
            sel = Gui.Selection.getSelectionEx()
            if len(sel) < 1:
                # several selections - Error
                errMessage = "Select one or more edges to trim"
                faced.getInfo(sel).errorDialog(errMessage)
                return
            SelectedPoints = []
            sel1 = sel[0]

            if sel1.HasSubObjects:
                # We have several objects that has subobject(Edges) that should be trimmed

                # Save position and angle
                _placement = sel1.Object.Placement
                _placement.Rotation.Q = sel1.Object.Placement.Rotation.Q
                currentObject = App.ActiveDocument.getObject(sel1.Object.Name)
                SelectedPoints.clear(
                )  # points in the targeted line to be trimmed
                _edg = sel1.SubObjects[0]
                # TODO: trim only 2 points at the moment
                Vert = _edg.Vertexes

                # Save all points we have in the edge or line/wire which should be trimmed
                for n in Vert:
                    SelectedPoints.append(App.Vector(n.Point))

                WireOrEdgeMadeOfPoints = []
                # Bring all points from the object
                for item in sel1.Object.Shape.Vertexes:
                    WireOrEdgeMadeOfPoints.append(App.Vector(item.Point))
                totalPoints = len(WireOrEdgeMadeOfPoints)
                position1 = position2 = None
                count = 0
                # First find their locations

                for j in range(totalPoints):
                    if SelectedPoints[0] == WireOrEdgeMadeOfPoints[j]:
                        position1 = count
                    elif (SelectedPoints[1] == WireOrEdgeMadeOfPoints[j]):
                        position2 = count
                    count = count + 1
                # Try to reconstruct the shape/wire
                TestTwoObjectCreate = False
                _all_points2 = []
                objType = faced.getInfo(sel1).selectedObjectType()
                closedShape = None
                EndPoint = StartPoint = None
                if (objType == 'Wire' or objType == 'Line'):
                    closedShape = sel1.Object.Closed
                elif objType == 'Unknown':
                    closedShape = False
                    return  # We don't know what the shape is
                elif objType == 'Arc':
                    App.ActiveDocument.removeObject(sel1.Object.Name)
                    return
                else:
                    closedShape = True
                if closedShape == True:
                    # We have a shape with closed lines
                    # Here we need to do 2 things, 1 remove closed, 2 rearrange start-end
                    scan1 = min(position1, position2)
                    scan2 = max(position1, position2)
                    sortAll = 0
                    Index = scan2
                    EndPoint = WireOrEdgeMadeOfPoints[scan1]
                    StartPoint = WireOrEdgeMadeOfPoints[scan2]
                    while (sortAll < totalPoints):
                        _all_points2.append(WireOrEdgeMadeOfPoints[Index])
                        Index = Index + 1
                        if Index >= totalPoints:
                            Index = 0
                        sortAll = sortAll + 1
                    WireOrEdgeMadeOfPoints.clear()
                    WireOrEdgeMadeOfPoints = _all_points2

                elif (abs(position2 - position1) == 1):
                    # It must be a line and not closed
                    if position1 != 0 and position2 != totalPoints - 1:
                        # In the middle of the array.
                        # Two objects must be created.
                        print("between first and last")
                        _all_points2.clear()
                        plusOrMinus = 0
                        scan1 = min(position1, position2)
                        scan2 = max(position1, position2)
                        SaveValue = None
                        index = 0
                        while (index <= scan1):
                            _all_points2.append(WireOrEdgeMadeOfPoints[index])
                            index = index + 1
                        index = 0
                        StartPoint = WireOrEdgeMadeOfPoints[scan2]
                        EndPoint = WireOrEdgeMadeOfPoints[
                            len(WireOrEdgeMadeOfPoints) - 1]

                        for index in range(0, scan2):
                            print(index)
                            WireOrEdgeMadeOfPoints.pop(index)

                        pnew2DObject1 = _draft.makeWire(_all_points2,
                                                        placement=None,
                                                        closed=False,
                                                        face=False,
                                                        support=None)
                        pnew2DObject1.Label = 'Wire'
                        pnew2DObject1.Start = _all_points2[0]
                        pnew2DObject1.End = _all_points2[len(_all_points2) - 1]

                    elif position1 == 0 and position2 != totalPoints - 1:
                        # First Points, remove  'closed' and start = pos+1
                        print("in the beginning")
                        StartPoint = WireOrEdgeMadeOfPoints[position2]
                        WireOrEdgeMadeOfPoints.pop(position1)
                        EndPoint = WireOrEdgeMadeOfPoints[
                            len(WireOrEdgeMadeOfPoints) - 1]
                        # don't add first point
                    elif position2 == totalPoints - 1:
                        # point 2 is the last point in the shape
                        print("at the end")
                        StartPoint = WireOrEdgeMadeOfPoints[0]
                        EndPoint = WireOrEdgeMadeOfPoints[position2 - 1]
                        WireOrEdgeMadeOfPoints.pop(position2 - 1)

                        # don't add last point

                pnew2DObject2 = _draft.makeWire(WireOrEdgeMadeOfPoints,
                                                placement=None,
                                                closed=False,
                                                face=False,
                                                support=None)
                App.ActiveDocument.removeObject(sel1.ObjectName)
                App.ActiveDocument.recompute()
                pnew2DObject2.Label = 'Wire'

                pnew2DObject2.End = EndPoint
                pnew2DObject2.Start = StartPoint

                # If nothing left, remove the object
                if len(pnew2DObject2.Shape.Vertexes) == 0:
                    App.ActiveDocument.removeObject(pnew2DObject2.Label)
                App.ActiveDocument.recompute()

            else:
                # No Edges found
                errMessage = "Select one or more edges to trim"
                faced.getInfo(sel1).errorDialog(errMessage)
                return
        except Exception as err:
            App.Console.PrintError("'Trim 2D' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def Activated(self):
        import DraftGeomUtils
        try:
            s = Gui.Selection.getSelectionEx()
            if hasattr(s, "Point"):
                return
            e1 = None
            e2 = None
            if len(s) > 2:
                # Two objects must be selected
                errMessage = "Select only two vertices "
                faced.errorDialog(errMessage)
                return
            elif len(s) == 1:
                errMessage = "Not implemented "
                faced.errorDialog(errMessage)
                return
            elif len(s) == 2:
                s1 = s[0]
                s2 = s[1]
                if ('Vertex' in str(s1.SubElementNames)):
                    # Vertexes are selected
                    p1 = s1.SubObjects[0].Vertexes[0].Point
                    p2 = s2.SubObjects[0].Vertexes[0].Point
                elif ('Edge' in str(s1.SubElementNames)):
                    # Edges are selected
                    # We have to find the nearest two vector.
                    # Joining here means the two edges will
                    # attach to each other while they are
                    # separate.
                    vert1 = []
                    for e in s1.Object.Shape.OrderedEdges:
                        for v in e.Vertexes:
                            vert1.append(v.Point)
                    vert2 = []
                    for e in s2.Object.Shape.OrderedEdges:
                        for v in e.Vertexes:
                            vert2.append(v.Point)
                    # Now we need to find one point from each edge
                    # that are nearest to each other
                    index1 = DraftGeomUtils.findClosest(vert1[0], vert2)
                    index2 = DraftGeomUtils.findClosest(
                        vert1[len(vert1) - 1], vert2)
                    dist1 = math.sqrt(
                        pow((vert1[0].x - vert2[index1].x), 2) +
                        pow((vert1[0].y - vert2[index1].y), 2) +
                        pow((vert1[0].z - vert2[index1].z), 2))
                    dist2 = math.sqrt(
                        pow((vert1[len(vert1) - 1].x - vert2[index2].x), 2) +
                        pow((vert1[len(vert1) - 1].y - vert2[index2].y), 2) +
                        pow((vert1[len(vert1) - 1].y - vert2[index2].z), 2))

                    if dist1 == dist2 or dist1 < dist2:
                        p1 = vert1[0]
                        p2 = vert2[index1]
                    elif dist2 < dist1:
                        p1 = vert1[len(vert1) - 1]
                        p2 = vert2[index2]

                if hasattr(s1.Object.Shape, "OrderedEdges"):
                    Edges1 = s1.Object.Shape.OrderedEdges
                else:
                    Edges1 = s1.Object.Shape.Edges
                if hasattr(s2.Object.Shape, "OrderedEdges"):
                    Edges2 = s2.Object.Shape.OrderedEdges
                else:
                    Edges2 = s2.Object.Shape.Edges

                if len(Edges1) > 1:
                    for ed in Edges1:
                        for v in ed.Vertexes:
                            if v.Point == p1:
                                e1 = ed
                                Edges1.remove(e1)
                                break
                else:
                    e1 = Edges1[0]
                    Edges1 = []

            # We have the edges and the points
            if e1 is not None:
                if (e1.Vertexes[0].Point != p1):
                    p1 = e1.Vertexes[0].Point
                else:
                    p1 = e1.Vertexes[1].Point
            p1 = App.Vector(p1.x, p1.y, p1.z)
            p2 = App.Vector(p2.x, p2.y, p2.z)
            App.ActiveDocument.openTransaction(
                translate("Design456", "Join2Lines"))
            l1 = _draft.makeLine(p1, p2)
            App.ActiveDocument.recompute()
            newEdg = l1.Shape.Edges[0]
            if type(Edges1) == list and type(Edges2) == list:
                totalE = Edges1 + Edges2 + [newEdg]
            elif type(Edges1) == list and type(Edges2) != list:
                totalE = Edges1 + [Edges2] + [newEdg]
            elif type(Edges1) != list and type(Edges2) == list:
                # Only one edge in the first line, so not included
                totalE = Edges2 + [newEdg]
            else:
                # None of them is multiple edges. so only new edge should be use
                totalE = [Edges2] + [newEdg]

            newList = []
            for e in totalE:
                newList.append(e.copy())
            sortEdg = _part.sortEdges(newList)
            W = [_part.Wire(e) for e in sortEdg]
            for wire in W:
                newobj = App.ActiveDocument.addObject("Part::Feature", "Wire")
                newobj.Shape = wire
            App.ActiveDocument.removeObject(l1.Name)
            App.ActiveDocument.removeObject(s1.Object.Name)
            App.ActiveDocument.removeObject(s2.Object.Name)
            App.ActiveDocument.recompute()
            App.ActiveDocument.commitTransaction()  # undo reg.de here

        except Exception as err:
            App.Console.PrintError("'Part Surface' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def Activated(self):
        result = []
        try:
            s = Gui.Selection.getSelectionEx()
            if len(s) > 1:
                errMessage = "Select edges from one object"
                faced.errorDialog(errMessage)
                return
            if hasattr(s[0], "SubObjects"):
                if s[0].HasSubObjects:
                    selectedObj = s[0].SubObjects
                else:
                    selectedObj = s[0].Object.Shape.Edges[0]
            else:
                return
            edges = []
            _resultFaces = []
            AllFaces = s[0].Object.Shape.Faces
            for i in range(0, len(AllFaces)):
                edges.clear()
                edges = (AllFaces[i].OuterWire.OrderedEdges)
                temp = []
                temp.clear()
                for j in range(0, len(edges)):
                    found = False
                    for obj in selectedObj:
                        if ((edges[j]).isEqual(obj)):
                            found = True
                            print("found")
                        else:
                            temp.append(edges[j].copy())
                if (len(temp) > 0):
                    #recreate the shape
                    #Register undo
                    App.ActiveDocument.openTransaction(
                        translate("Design456", "RemoveEdge"))
                    nFace = None
                    nWire = _part.Wire(temp)
                    if nWire.isClosed():
                        try:
                            nFace = _part.makeFilledFace(temp)
                        except:
                            pass
                    if (nFace is None) or (nFace.isNull()):
                        print("failed")
                        nF = App.ActiveDocument.addObject(
                            "Part::Feature", "nWire")
                        nF.Shape = nWire
                    else:
                        _resultFaces.append(nFace)
            App.ActiveDocument.recompute()
            shell = _part.makeShell(_resultFaces)
            App.ActiveDocument.recompute()
            final = App.ActiveDocument.addObject("Part::Feature", "RemoveEdge")
            final.Shape = shell
            App.ActiveDocument.recompute()
            App.ActiveDocument.removeObject(s[0].Object.Name)

        except Exception as err:
            App.Console.PrintError("'Design456_RemoveEdge' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#10
0
    def Activated(self):
        try:
            sel = Gui.Selection.getSelection()
            if (len(sel) != 2):
                # Two object must be selected
                errMessage = "Select two objects to use the Tool"
                faced.getInfo(sel).errorDialog(errMessage)
                return
            reply = self.askQuestion()
            App.ActiveDocument.openTransaction(
                translate("Design456", "UnifySplitFuse1"))
            Gui.ActiveDocument.getObject(sel[0].Name).Visibility = False
            Gui.ActiveDocument.getObject(sel[1].Name).Visibility = False

            #### Config Begin ####

            switchRemoveConstructionObject = self.askQuestion(
            )  # if 0 (NO) not removed creation objects 1= (YES) remove objects
            colorCommon = (0.9373, 0.1608, 0.1608)
            colorCut1 = (0.4471, 0.6235, 0.8118)
            colorCut2 = (0.0235, 0.6902, 0.6902)
            colorFuse = (1.0000, 0.6667, 0.0000)
            #### Config End ####

            ##### Begin command _part_Common
            #### create copy
            shapeCommon = _part.getShape(App.ActiveDocument.getObject(
                sel[0].Name),
                                         '',
                                         needSubElement=False,
                                         refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Common1').Shape = shapeCommon
            newObjectCut_A1 = App.ActiveDocument.ActiveObject
            shapeCommon = _part.getShape(App.ActiveDocument.getObject(
                sel[1].Name),
                                         '',
                                         needSubElement=False,
                                         refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Common2').Shape = shapeCommon
            newObjectCut_A2 = App.ActiveDocument.ActiveObject
            ####
            commonObject = App.ActiveDocument.addObject(
                "Part::MultiCommon", "Common")
            commonObjectMake = App.ActiveDocument.getObject(
                commonObject.Name).Shapes = [
                    App.ActiveDocument.getObject(newObjectCut_A1.Name),
                    App.ActiveDocument.getObject(newObjectCut_A2.Name),
                ]
            shapeCommonMake = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()
            Gui.ActiveDocument.activeObject().ShapeColor = colorCommon
            ####
            shapeCommon = _part.getShape(App.ActiveDocument.getObject(
                shapeCommonMake.Name),
                                         '',
                                         needSubElement=False,
                                         refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'shapeCommon').Shape = shapeCommon
            Gui.ActiveDocument.activeObject().ShapeColor = colorCommon
            if switchRemoveConstructionObject == 1:
                App.ActiveDocument.removeObject(shapeCommonMake.Name)
                App.ActiveDocument.removeObject(newObjectCut_A1.Name)
                App.ActiveDocument.removeObject(newObjectCut_A2.Name)
            #### End command Part_Common

            #### Begin command Part_Cut First
            #### create copy
            shapeCut1 = _part.getShape(App.ActiveDocument.getObject(
                sel[0].Name),
                                       '',
                                       needSubElement=False,
                                       refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Cut01').Shape = shapeCut1
            newObjectCut_A1 = App.ActiveDocument.ActiveObject
            shapeCut1 = _part.getShape(App.ActiveDocument.getObject(
                sel[1].Name),
                                       '',
                                       needSubElement=False,
                                       refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Cut02').Shape = shapeCut1
            newObjectCut_A2 = App.ActiveDocument.ActiveObject
            ####
            App.ActiveDocument.addObject("Part::Cut", "Cut_01")
            App.ActiveDocument.Cut_01.Base = App.ActiveDocument.getObject(
                newObjectCut_A1.Name)
            App.ActiveDocument.Cut_01.Tool = App.ActiveDocument.getObject(
                newObjectCut_A2.Name)
            shapeCutMake = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()
            Gui.ActiveDocument.activeObject().ShapeColor = colorCut1
            ####
            shapeCut01 = _part.getShape(App.ActiveDocument.getObject(
                shapeCutMake.Name),
                                        '',
                                        needSubElement=False,
                                        refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'shapeCut01').Shape = shapeCut01
            Gui.ActiveDocument.activeObject().ShapeColor = colorCut1
            if switchRemoveConstructionObject == 1:
                App.ActiveDocument.removeObject(shapeCutMake.Name)
                App.ActiveDocument.removeObject(newObjectCut_A1.Name)
                App.ActiveDocument.removeObject(newObjectCut_A2.Name)
            #### End command Part_Cut First

            #### Begin command Part_Cut Second
            #### create copy
            shapeCut2 = _part.getShape(App.ActiveDocument.getObject(
                sel[1].Name),
                                       '',
                                       needSubElement=False,
                                       refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Cut01').Shape = shapeCut2
            newObjectCut_A1 = App.ActiveDocument.ActiveObject
            shapeCut2 = _part.getShape(App.ActiveDocument.getObject(
                sel[0].Name),
                                       '',
                                       needSubElement=False,
                                       refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Cut02').Shape = shapeCut2
            newObjectCut_A2 = App.ActiveDocument.ActiveObject
            ####
            App.ActiveDocument.addObject("Part::Cut", "Cut_02")
            App.ActiveDocument.Cut_02.Base = App.ActiveDocument.getObject(
                newObjectCut_A1.Name)
            App.ActiveDocument.Cut_02.Tool = App.ActiveDocument.getObject(
                newObjectCut_A2.Name)
            shapeCutMake = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()
            Gui.ActiveDocument.activeObject().ShapeColor = colorCut2
            ####
            shapeCut02 = _part.getShape(App.ActiveDocument.getObject(
                shapeCutMake.Name),
                                        '',
                                        needSubElement=False,
                                        refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'shapeCut02').Shape = shapeCut02
            Gui.ActiveDocument.activeObject().ShapeColor = colorCut2
            if switchRemoveConstructionObject == 1:
                App.ActiveDocument.removeObject(shapeCutMake.Name)
                App.ActiveDocument.removeObject(newObjectCut_A1.Name)
                App.ActiveDocument.removeObject(newObjectCut_A2.Name)
            #### End command Part_Cut Second

            #### Begin command Part_Fuse
            #### create copy
            shapeFuse1 = _part.getShape(App.ActiveDocument.getObject(
                sel[1].Name),
                                        '',
                                        needSubElement=False,
                                        refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Fuse01').Shape = shapeFuse1
            newObjectFuse1 = App.ActiveDocument.ActiveObject
            shapeFuse2 = _part.getShape(App.ActiveDocument.getObject(
                sel[0].Name),
                                        '',
                                        needSubElement=False,
                                        refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'Fuse02').Shape = shapeFuse2
            newObjectFuse2 = App.ActiveDocument.ActiveObject
            ####
            App.ActiveDocument.addObject("Part::MultiFuse", "Fusion")
            App.ActiveDocument.Fusion.Shapes = [
                App.ActiveDocument.getObject(newObjectFuse1.Name),
                App.ActiveDocument.getObject(newObjectFuse2.Name),
            ]
            shapeCutFusion = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()
            Gui.ActiveDocument.activeObject().ShapeColor = colorFuse
            ####
            shapeFusion = _part.getShape(App.ActiveDocument.getObject(
                shapeCutFusion.Name),
                                         '',
                                         needSubElement=False,
                                         refine=False)
            App.ActiveDocument.addObject('Part::Feature',
                                         'shapeFusion').Shape = shapeFusion
            Gui.ActiveDocument.activeObject().ShapeColor = colorFuse
            if switchRemoveConstructionObject == 1:
                App.ActiveDocument.removeObject(shapeCutFusion.Name)
                App.ActiveDocument.removeObject(newObjectFuse1.Name)
                App.ActiveDocument.removeObject(newObjectFuse2.Name)
            #### End command Part_Fuse
            App.ActiveDocument.commitTransaction()  #undo reg.
        except Exception as err:
            App.Console.PrintError("'makeIt' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#11
0
    def Activated(self):
        try:
            #### Config Begin ####
            switchRemoveConstructionObject = self.askQuestion(
            )  # if 0= (NO) not removed creation objects 1= (YES) remove objects
            #### Config End ####
            App.ActiveDocument.openTransaction(
                translate("Design456", "UnifySplitFuse1"))
            selectedEdge = Gui.Selection.getSelectionEx()
            sel = selObjects = Gui.Selection.getSelection()
            try:
                subElementName = Gui.Selection.getSelectionEx(
                )[0].SubElementNames[0]  # for color first face selected
            except:
                subElementName = Gui.Selection.getSelectionEx(
                )[0].SubObjects[0]

            if (len(sel) != 2):
                # Two object must be selected
                errMessage = "Select two objects to use the Tool"
                faced.getInfo(sel).errorDialog(errMessage)
                return

            try:
                colorFace = App.ActiveDocument.getObject(
                    sel[0].Name).ViewObject.DiffuseColor[int(
                        SubElementName[4:]) - 1]  # color face selected
                ##App.ActiveDocument.getObject(sel[0].Name).ViewObject.DiffuseColor[int(SubElementName[4:])-1] = colorFace# give color on face
            except Exception:
                colorFace = App.ActiveDocument.getObject(
                    sel[0].Name).ViewObject.DiffuseColor[
                        0]  # color face selected [0]

            ### Begin command Part_ElementCopy First selection
            newFace1 = _part.getShape(App.ActiveDocument.getObject(
                sel[0].Name),
                                      selectedEdge[0].SubElementNames[0],
                                      needSubElement=True,
                                      refine=False).copy()
            App.ActiveDocument.addObject('Part::Feature',
                                         'Face1').Shape = newFace1
            shapeFace1 = App.ActiveDocument.ActiveObject
            ####

            ### Begin command Part_ElementCopy Second selection
            try:  # independent object
                newFace2 = _part.getShape(App.ActiveDocument.getObject(
                    sel[1].Name),
                                          selectedEdge[1].SubElementNames[0],
                                          needSubElement=True,
                                          refine=False).copy()
            except Exception:
                # same object other face  TODO: This will fail if you have a sphere shape or a ball Mariwan 2021-03-18
                newFace2 = _part.getShape(App.ActiveDocument.getObject(
                    sel[0].Name),
                                          selectedEdge[0].SubElementNames[1],
                                          needSubElement=True,
                                          refine=False).copy()

            App.ActiveDocument.addObject('Part::Feature',
                                         'Face2').Shape = newFace2
            shapeFace2 = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()
            ### End command Part_ElementCopy

            ### Begin command Part_Loft
            attached = App.ActiveDocument.addObject('Part::Loft', 'Attached')
            attached.Sections = [
                App.ActiveDocument.Face1,
                App.ActiveDocument.Face2,
            ]
            attached.Solid = True
            attached.Ruled = False
            attached.Closed = False
            ### End command Part_Loft

            ### Begin command Part_Fuse
            fusion = App.ActiveDocument.addObject("Part::MultiFuse", "Fusion")
            try:  # multiple objects
                App.ActiveDocument.Fusion.Shapes = [
                    App.ActiveDocument.getObject(selObjects[0].Name),
                    App.ActiveDocument.Attached,
                    App.ActiveDocument.getObject(selObjects[1].Name),
                ]
            except Exception:  # single object
                App.ActiveDocument.Fusion.Shapes = [
                    App.ActiveDocument.getObject(selObjects[0].Name),
                    App.ActiveDocument.Attached,
                    App.ActiveDocument.getObject(selObjects[0].Name),
                ]
            App.ActiveDocument.recompute()
            ### End command Part_Fuse

            # create single object
            _part.show(fusion.Shape.copy())
            App.ActiveDocument.ActiveObject.ViewObject.DiffuseColor = colorFace  # give face color on object
            App.ActiveDocument.ActiveObject.Label = sel[
                0].Label + "_" + subElementName

            ##### removeObject work
            if switchRemoveConstructionObject == 1:
                App.ActiveDocument.removeObject(selObjects[0].Name)
                try:  # multiple objects
                    App.ActiveDocument.removeObject(selObjects[1].Name)
                except Exception:  # single object
                    None
                App.ActiveDocument.removeObject(attached.Name)
                App.ActiveDocument.removeObject(fusion.Name)
                App.ActiveDocument.removeObject(shapeFace1.Name)
                App.ActiveDocument.removeObject(shapeFace2.Name)
            App.ActiveDocument.commitTransaction()  #undo reg.
        except Exception as err:
            App.Console.PrintError("'UnifySplitFuse1' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#12
0
    def Activated(self):
        try:
            selection = Gui.Selection.getSelectionEx()
            if (len(selection) < 1):
                # An object must be selected
                errMessage = "Select a face to use Extrude"
                faced.getInfo(selection).errorDialog(errMessage)
                return
            m = selection[0].Object
            f = App.activeDocument().addObject('Part::Extrusion',
                                               'ExtrudeOriginal')
            faceSelected = faced.getInfo(selection[0]).getFaceName()
            f.Base = m
            #f.Base = App.activeDocument().getObject(m.Name)
            f.DirMode = "Normal"  #Dont use Custom as it leads to PROBLEM!
            f.DirLink = None
            degreeAngle = m.Placement.Rotation.Angle * 180 * 22 / 7  # Convert to Radians
            print(degreeAngle)
            """
            YOU SHOULD NOT SPECIFY THIS .. OTHERWISE WOULD BE WRONG!!
            if degreeAngle == 0:
                f.Dir = m.Placement.Rotation.Axis
            elif ((degreeAngle== 90) or (degreeAngle== -90)):
                f.Dir = (0, 1, 0)
            elif ((degreeAngle == 120) or (degreeAngle== -120)):
                f.Dir = (1, 0, 0)
            """
            f.LengthFwd = QtGui.QInputDialog.getDouble(None, "Get length",
                                                       "Length:", 0, -10000.0,
                                                       10000.0, 2)[0]
            while (f.LengthFwd == 0):
                _sleep(.1)
                Gui.updateGui()
            f.LengthRev = 0.0
            f.Solid = True
            f.Reversed = False
            f.Symmetric = False
            f.TaperAngle = 0.0
            f.TaperAngleRev = 0.0

            # Make a simple copy of the object
            App.ActiveDocument.recompute()
            newShape = Part.getShape(f, '', needSubElement=False, refine=False)
            newObj = App.ActiveDocument.addObject('Part::Feature',
                                                  'Extrude').Shape = newShape
            App.ActiveDocument.ActiveObject.Label = f.Label
            App.ActiveDocument.recompute()
            # if something went wrong .. delete all new objecst.
            if newObj.isValid() == False:
                App.ActiveDocument.removeObject(newObj.Name)
                App.ActiveDocument.removeObject(f.Name)
                # Shape is not OK
                errMessage = "Failed to extrude the shape"
                faced.getInfo(m).errorDialog(errMessage)
            else:
                # Remove old objects
                App.ActiveDocument.clearUndos()
                App.ActiveDocument.recompute()
                App.ActiveDocument.removeObject(f.Name)
                App.ActiveDocument.removeObject(m.Name)
                return
            App.ActiveDocument.recompute()
        except Exception as err:
            App.Console.PrintError("'Design456_Extrude' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def cb_discRotate(self, userData: userDataObject = None):
        """
        Internal callback function, runs when the disc
        rotation event happens.
        self.w_discEnabled must be True
        """
        boundary = self.getWidgetsBoundary(self.w_discSeparator)
        center = self.getWidgetsCentor(self.w_discSeparator)
        try:

            self.endVector = App.Vector(self.w_parent.w_lastEventXYZ.Coin_x,
                                        self.w_parent.w_lastEventXYZ.Coin_y,
                                        self.w_parent.w_lastEventXYZ.Coin_z)
            if self.run_Once is False:
                self.run_Once = True
                self.startVector = self.endVector

                # Keep the old value only first time when drag start
                self.startVector = self.endVector
                if not self.has_focus():
                    self.take_focus()
            newValue = self.endVector

            print(center, "center")
            mx = my = mz = 0.0

            if self.axisType == 'X':  # Right
                # It means that we have changes in Z and Y only
                # If the mouse moves at the >center in Z direction :
                # Z++  means   -Angel, Z--  means  +Angle    --> When Y is +                   ^
                # Z++  means   +Angel, Z--  means  -Angle    --> When Y is -                   v
                # Y++  means   +Angel, Y--  means  -Angel    -->  when Z is +
                # Y++  means   -Angel, Y--  means  +Angel    -->  when Z is -
                my = (newValue.y - center.y)
                mz = (newValue.z - center.z)
                if (mz == 0):
                    return  # Invalid
                self.w_discAngle = faced.calculateMouseAngle(my, mz)

            if self.axisType == 'Y':  # Front
                # It means that we have changes in Z and X only
                # Z++  means   -Angel, Z--  means  +Angle    -->  When X is +                   ^
                # Z++  means   +Angel, Z--  means  -Angle    -->  When X is -                   v
                # X++  means   -Angel, x--  means  +Angel    -->  when Z is +
                # X++  means   +Angel, x--  means  -Angel    -->  when Z is -
                mx = (newValue.x - center.x)
                mz = (newValue.z - center.z)
                if (mz == 0):
                    return  # Invalid
                self.w_discAngle = faced.calculateMouseAngle(mx, mz)

            if self.axisType == 'Z':
                # It means that we have changes in X and Y only
                # Y++  means   -Angel, Y--  means  +Angle    -->  When X is +                   ^
                # Y++  means   +Angel, Y--  means  -Angle    -->  When X is -                   v
                # x++  means   -Angel, X--  means  +Angel    -->  when Y is +
                # x++  means   +Angel, X--  means  -Angel    -->  when Y is -
                mx = (newValue.x - center.x)
                my = (newValue.y - center.y)
                if (my == 0):
                    return  # Invalid
                self.w_discAngle = faced.calculateMouseAngle(mx, my)
            if (self.w_discAngle == 360):
                self.w_discAngle = 0
            if (self.oldAngle < 45
                    and self.oldAngle >= 0) and (self.w_discAngle > 270):
                self.rotationDirection = -1
                self.w_discAngle = self.w_discAngle - 360

            elif (self.rotationDirection == -1 and self.w_discAngle > 0
                  and self.w_discAngle < 45 and self.oldAngle < -270):
                self.rotationDirection = 1

            # we don't accept an angel grater or smaller than 360 degrees
            if (self.rotationDirection < 0):
                self.w_discAngle = self.w_discAngle - 360

            if (self.w_discAngle > 359):
                self.w_discAngle = 359
            elif (self.w_discAngle < -359):
                self.w_discAngle = -359
            if self.w_discAngle == -360:
                self.w_discAngle = 0
            self.oldAngle = self.w_discAngle
            print("Angle=", self.w_discAngle)
            self.redraw()

        except Exception as err:
            App.Console.PrintError("'disc Callback' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#14
0
    def ExtrudeFace(self, allObjects):
        try:
            for obj in allObjects:
                App.ActiveDocument.openTransaction(
                    translate("Design456", "Extrude"))
                m = obj
                f = App.ActiveDocument.addObject('Part::Extrusion',
                                                 'ExtrudeOriginal')
                # section direction
                yL = m.Shape.Faces[0].CenterOfMass
                uv = m.Shape.Faces[0].Surface.parameter(yL)
                nv = m.Shape.Faces[0].normalAt(uv[0], uv[1])
                direction = yL.sub(nv + yL)
                direction = App.Vector(round(direction.x, 2),
                                       round(direction.y, 2),
                                       round(direction.z, 2))
                f.Dir = direction
                f.Base = m
                # F.DirMode causes too many failure. Some faces needs custom, other needs Normal.
                # Difficult to know when you use each of them.
                if (f.Dir.x != 1 or f.Dir.y != 1 or f.Dir.z != 1):
                    f.DirMode = "Custom"
                else:
                    f.DirMode = "Normal"
                f.DirLink = None  # Above statement != always correct. Some faces require 'custom'
                f.LengthFwd = self.extrusionLength
                f.LengthRev = 0.0
                f.Solid = True
                f.Reversed = False
                f.Symmetric = False
                f.TaperAngle = 0.0
                f.TaperAngleRev = 0.0
                r = App.Rotation(App.Vector(0, 0, 0), direction)
                f.Dir = direction

                # Make a simple copy of the object
                App.ActiveDocument.recompute()
                newShape = Part.getShape(f,
                                         '',
                                         needSubElement=False,
                                         refine=False)
                newObj = App.ActiveDocument.addObject(
                    'Part::Feature', 'Extrude').Shape = newShape
                App.ActiveDocument.recompute()
                # if something went wrong .. delete all new objects.
                if newObj.isValid() is False:
                    App.ActiveDocument.removeObject(newObj.Name)
                    App.ActiveDocument.removeObject(f.Name)
                    # Shape != OK
                    errMessage = "Failed to extrude the shape"
                    faced.getInfo(m).errorDialog(errMessage)
                else:
                    App.ActiveDocument.recompute()
                    App.ActiveDocument.removeObject(f.Name)
                    App.ActiveDocument.removeObject(m.Name)
            App.ActiveDocument.commitTransaction()  # undo reg.
            App.ActiveDocument.recompute()

        except Exception as err:
            App.Console.PrintError("'Design456_Extrude' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def Activated(self):
        try:
            s = Gui.Selection.getSelectionEx()
            if (len(s) < 1):
                # One object must be selected at least
                errMessage = "Select a face or an edge use Fillet"
                faced.errorDialog(errMessage)
                return
            App.ActiveDocument.openTransaction(
                translate("Design456", "Part Fillet"))
            Radius = QtGui.QInputDialog.getDouble(None, "Fillet Radius",
                                                  "Radius:", 0, 1.0, 20.0,
                                                  2)[0]
            if (Radius == 0):
                return
            tempNewObj = App.ActiveDocument.addObject("Part::Fillet",
                                                      "tempFillet")
            sub1 = s[0]
            tempNewObj.Base = sub1.Object
            names = sub1.SubElementNames
            EdgesToBeChanged = []
            if (len(names) != 0):
                """ we need to take the rest of the string
                            i.e. 'Edge15' --> take out 'Edge'-->4 bytes
                            len('Edge')] -->4
                """
                for name in names:
                    edgeNumbor = int(name[4:len(name)])
                    EdgesToBeChanged.append((edgeNumbor, Radius, Radius))
                print(EdgesToBeChanged)
                tempNewObj.Edges = EdgesToBeChanged
            else:
                errMessage = "Fillet failed. No subelements found"
                faced.errorDialog(errMessage)
                return

            if tempNewObj.isValid() is False:
                App.ActiveDocument.removeObject(tempNewObj.Name)
                # Shape != OK
                errMessage = "Failed to fillet the objects"
                faced.errorDialog(errMessage)
            else:
                # Make a simple copy of the object
                App.ActiveDocument.recompute()
                newShape = Part.getShape(tempNewObj,
                                         '',
                                         needSubElement=False,
                                         refine=False)
                newObj = App.ActiveDocument.addObject(
                    'Part::Feature', 'Fillet').Shape = newShape
                App.ActiveDocument.recompute()
                App.ActiveDocument.ActiveObject.Label = 'Fillet'

                App.ActiveDocument.removeObject(sub1.Object.Name)
                App.ActiveDocument.removeObject(tempNewObj.Name)
            App.ActiveDocument.commitTransaction()  #undo reg.
            del EdgesToBeChanged[:]
            App.ActiveDocument.recompute()

        except Exception as err:
            App.Console.PrintError("'Fillet' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#16
0
    def Activated(self):
        """[ Executes when the tool is used   ]
        """
        import ThreeDWidgets.fr_coinwindow as win
        self.coinFaces = coin.SoSeparator()
        self.w_rotation = [0.0, 0.0, 0.0]  # disc rotation
        self.setupRotation = [0, 0, 0, 0]  # Whole widget rotation
        self._Vector = App.Vector(0.0, 0.0, 0.0)  # disc POSITION
        self.counter = 0
        self.run_Once = False
        self.tweakLength = 0
        self.oldTweakLength = 0
        self.newFaces = []
        self.savedVertexes = [[]]
        self.tweakLength = 0

        try:
            self.view = Gui.ActiveDocument.ActiveView
            self.sg = self.view.getSceneGraph()
            sel = Gui.Selection.getSelectionEx()

            if len(sel) > 2:
                errMessage = "Please select only one face and try again"
                faced.errorDialog(errMessage)
                return
            # Register undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "ExtendFace"))
            self.selectedObj = sel[0].Object
            self.selectedObj.Visibility = False
            if (hasattr(sel[0], "SubObjects")):
                self.selectedFace = sel[0].SubObjects[0]
            else:
                raise Exception("Not implemented")

            if self.selectedFace.ShapeType != 'Face':
                errMessage = "Please select only one face and try again, was: " + \
                    str(self.selectedFace.ShapeType)
                faced.errorDialog(errMessage)
                return

            # Recreate the object in separated shapes.
            self.saveVertexes()

            if (hasattr(self.selectedFace, "Vertexes")):
                #self.oldFaceVertexes = self.selectedFace.OuterWire.OrderedVertexes
                self.oldFaceVertexes = self.selectedFace.Vertexes
            if not hasattr(self.selectedFace, 'Faces'):
                raise Exception("Please select only one face and try again")
            # TODO: FIXME: WHAT SHOULD WE DO WHEN IT IS A CURVED FACE???
            # if not(type(self.selectedFace.Curve) == _part.Line or
            #       type(self.selectedFace.Curve) == _part.BezierCurve):
            #    msg = "Curve Faces are not supported yet"
            #    faced.errorDialog(msg)
            #    self.hide()

            self.setupRotation = self.calculateNewVector()

            self.ExtractFace()
            self.newFaceVertexes = self.newFace.Shape.Vertexes
            App.ActiveDocument.removeObject(self.selectedObj.Name)

            # Undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "ExtendFace"))

            # Decide how the Degree pad be drawn
            self.discObj = Fr_ThreeArrows_Widget(
                [self.FirstLocation, App.Vector(0, 0, 0)],  #
                # label
                [
                    (str(round(self.w_rotation[0], 2)) + "°" +
                     str(round(self.w_rotation[1], 2)) + "°" +
                     str(round(self.w_rotation[2], 2)) + "°"),
                ],
                FR_COLOR.FR_WHITE,  # lblcolor
                [FR_COLOR.FR_RED, FR_COLOR.FR_GREEN, FR_COLOR.FR_BLUE
                 ],  # arrows color
                # rotation of the disc main
                [0, 0, 0, 0],
                self.setupRotation,  # setup rotation
                [30.0, 30.0, 30.0],  # scale
                1,  # type
                0,  # opacity
                10)  # distance between them
            self.discObj.enableDiscs()

            # Different callbacks for each action.
            self.discObj.w_xAxis_cb_ = self.MouseDragging_cb
            self.discObj.w_yAxis_cb_ = self.MouseDragging_cb
            self.discObj.w_zAxis_cb_ = self.MouseDragging_cb

            self.discObj.w_discXAxis_cb_ = self.RotatingFace_cb
            self.discObj.w_discYAxis_cb_ = self.RotatingFace_cb
            self.discObj.w_discZAxis_cb_ = self.RotatingFace_cb

            self.discObj.w_callback_ = self.callback_release
            self.discObj.w_userData.callerObject = self

            self.COIN_recreateObject()

            if self._mywin is None:
                self._mywin = win.Fr_CoinWindow()

            self._mywin.addWidget(self.discObj)
            mw = self.getMainWindow()
            self._mywin.show()

            App.ActiveDocument.recompute()

        except Exception as err:

            App.Console.PrintError("'Activated' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#17
0
def callback_release(userData: fr_arrow_widget.userDataObject = None):
    """
       Callback after releasing the left mouse button. 
       This callback will finalize the Extrude operation. 
       Deleting the original object will be done when the user press 'OK' button
    """
    try:
        if (userData is None):
            print("userData is None")
            raise TypeError

        ArrowObject = userData.ArrowObj
        linktocaller = userData.callerObject
        # Avoid activating this part several times,
        if (linktocaller.startVector is None):
            return
        ArrowObject.remove_focus()
        linktocaller.run_Once = False
        linktocaller.endVector = App.Vector(
            ArrowObject.w_parent.w_lastEventXYZ.Coin_x,
            ArrowObject.w_parent.w_lastEventXYZ.Coin_y,
            ArrowObject.w_parent.w_lastEventXYZ.Coin_z)
        # Undo
        App.ActiveDocument.openTransaction(
            translate("Design456", "SmartExtrude"))
        App.ActiveDocument.recompute()
        linktocaller.startVector = None
        App.ActiveDocument.commitTransaction()  # undo reg.
        newObjcut = []
        # Do final operation. Either leave it as it is, merge or subtract
        if (linktocaller.OperationOption == 1):
            createFusionObjectBase(linktocaller)
            App.ActiveDocument.recompute()
            # subtraction will continue to work here
        elif linktocaller.OperationOption == 2:
            # Subtraction is complex. I have to cut from each object the same extruded part.
            if (linktocaller.objChangedTransparency != []):
                base = createFusionObjectBase(linktocaller)
                # Create a cut object for each transparency object
                if (linktocaller.WasFaceFrom3DObject is True):
                    # It is a 3D drawing object
                    tool = createFusionObjectTool(linktocaller)
                    for i in range(0,
                                   len(linktocaller.objChangedTransparency)):
                        newObjcut.append(
                            App.ActiveDocument.addObject(
                                "Part::Cut", "CUT" + str(i)))
                        newObjcut[i].Base = base
                        # Subtracted shape/object
                        newObjcut[i].Tool = tool
                        newObjcut[i].Refine = True
                    tool.Visibility = False
                else:
                    for i in range(0,
                                   len(linktocaller.objChangedTransparency)):
                        newObjcut.append(
                            App.ActiveDocument.addObject(
                                "Part::Cut", "CUT" + str(i)))
                        newObjcut[i].Base = base
                        # Subtracted shape/object
                        newObjcut[i].Tool = linktocaller.newObject
                        newObjcut[i].Refine = True

                App.ActiveDocument.recompute()

        elif linktocaller.OperationOption == 0:
            # is here just to make the code more readable.
            pass  # nothing to do .

        App.ActiveDocument.recompute()
        App.ActiveDocument.commitTransaction()  # undo reg.

    except Exception as err:
        faced.EnableAllToolbar(True)
        App.Console.PrintError("'Design456_Extrude' Release Filed. "
                               "{err}\n".format(err=str(err)))
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
示例#18
0
    def Activated(self):
        try:

            s = Gui.Selection.getSelectionEx()
            if (len(s) < 1):
                # An object must be selected
                errMessage = "Select an object to use Extrude Face"
                faced.getInfo(s).errorDialog(errMessage)
                return
            lengthForward = QtGui.QInputDialog.getDouble(
                None, "Get value", "Input:", 0, -10000.0, 10000.0, 2)[0]
            if(lengthForward == 0):
                return  # nothing to do here

            objName = s[0].ObjectName
            sh = s[0].Object.Shape.copy()
            if hasattr(s[0].Object, "getGlobalPlacement"):
                gpl = s[0].Object.getGlobalPlacement()
                sh.Placement = gpl
            name = s[0].SubElementNames[0]
            fullname = objName+"_"+name  # Name of the face extracted
            newobj = s[0].Document.addObject("Part::Feature", fullname)
            newobj.Shape = sh.getElement(name)
            selection = newobj  # The face extraced
            activeSel = Gui.Selection.getSelection(App.ActiveDocument.Name)
            Gui.Selection.removeSelection(activeSel[0])
            # Select the face extracted before
            Gui.Selection.addSelection(selection)
            App.ActiveDocument.recompute()
            m = App.activeDocument().getObject(fullname)
            f = App.activeDocument().addObject(
                'Part::Extrusion', 'ExtrudeFace')	  # Add extrusion
            f.Base = newobj				# App.activeDocument().getObject(fullname)
            f.DirMode = "Normal"
            f.DirLink = None
            f.LengthFwd = lengthForward
            f.LengthRev = 0.0
            f.Solid = True
            f.Reversed = False
            f.Symmetric = False
            f.TaperAngle = 0.0
            f.TaperAngleRev = 0.0
            App.ActiveDocument.recompute()
            newPart_ = App.ActiveDocument.addObject(
                'Part::Feature', f.Name+'N')
            newPart_.Shape = Part.getShape(
                f, '', needSubElement=False, refine=False)
            if newPart_.isValid() == False:
                App.ActiveDocument.removeObject(newPart_.Name)
                App.ActiveDocument.removeObject(f.Name)
                # Shape is not OK
                errMessage = "Failed to extrude the Face"
                faced.getInfo(m).errorDialog(errMessage)
            else:
                # remove old objects
                App.ActiveDocument.removeObject(f.Name)
                App.ActiveDocument.removeObject(m.Name)
                # This will not work for split objects as they are not two separate objects.2021-02-22
                # Make the two objects merged
                obj1 = App.ActiveDocument.getObject(s[0].ObjectName)
                obj2 = newPart_
                selections = Gui.Selection.getSelectionEx()
                for i in selections:
                    Gui.Selection.removeSelection(selections)
                    Gui.Selection.addSelection(obj1)
                    Gui.Selection.addSelection(obj2)
                    Gui.runCommand('Design456_Part_Merge', 0)
            App.ActiveDocument.recompute()

            return
        except Exception as err:
            App.Console.PrintError("'ExtrudeFace' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#19
0
    def getMainWindow(self):
        """[Create the tab for the tool]

        Raises:
            Exception: [If no tabs were found]
            Exception: [If something unusual happen]

        Returns:
            [dialog]: [the new dialog which will be added as a tab to the tab section of FreeCAD]
        """
        try:
            toplevel = QtGui.QApplication.topLevelWidgets()
            self.mw = None
            for i in toplevel:
                if i.metaObject().className() == "Gui::MainWindow":
                    self.mw = i
            if self.mw is None:
                raise Exception("No main window found")
            dw = self.mw.findChildren(QtGui.QDockWidget)
            for i in dw:
                if str(i.objectName()) == "Combo View":
                    self.tab = i.findChild(QtGui.QTabWidget)
                elif str(i.objectName()) == "Python Console":
                    self.tab = i.findChild(QtGui.QTabWidget)
            if self.tab is None:
                raise Exception("No tab widget found")

            self.dialog = QtGui.QDialog()
            oldsize = self.tab.count()
            self.tab.addTab(self.dialog, "Smart Extrude")
            self.tab.setCurrentWidget(self.dialog)
            self.dialog.resize(200, 450)
            self.dialog.setWindowTitle("Smart Extrude")
            self.la = QtGui.QVBoxLayout(self.dialog)
            self.e1 = QtGui.QLabel(
                "(Smart Extrude)\nFor quicker\nApplying Extrude")

            commentFont = QtGui.QFont("Times", 14, True)
            self.ExtrudeLBL = QtGui.QLabel("Extrude Length=")
            self.e1.setFont(commentFont)

            okbox = QtGui.QDialogButtonBox(self.dialog)
            okbox.setOrientation(QtCore.Qt.Horizontal)
            okbox.setStandardButtons(QtGui.QDialogButtonBox.Ok)

            self.lblExtrudeSize = QtGui.QLabel("Extrude Step Size = " +
                                               str(self.ExtrusionStepSize))
            self.lblExtrudeSize.setObjectName("lblExtrudeSize")
            comboFont = QtGui.QFont("Times", 13, True)

            self.lblExtrudeSize.setFont(comboFont)
            self.combListExtrudeStep = QtGui.QComboBox(self.dialog)
            self.combListExtrudeStep.addItem("0.1mm")  # 0.1 mm
            self.combListExtrudeStep.addItem("0.5mm")  # 0.5 mm
            self.combListExtrudeStep.addItem("1.0mm")  # 1.0 mm
            self.combListExtrudeStep.addItem("10mm")  # 1   cm
            self.combListExtrudeStep.addItem("100mm")  # 10   cm
            self.combListExtrudeStep.addItem("1000mm")  # 100  cm
            self.combListExtrudeStep.addItem("10000mm")  # 10    m
            self.combListExtrudeStep.addItem("100000mm")  # 100   m
            self.combListExtrudeStep.setCurrentIndex(2)
            #self.combListExtrudeStep.move (10, 400)

            self.combListExtrudeStep.activated[str].connect(self.comboChanged)
            self.combListExtrudeStep.setObjectName("combListExtrudeStep")

            self.groupBox = QtGui.QGroupBox(self.dialog)
            self.groupBox.setGeometry(QtCore.QRect(60, 130, 120, 80))
            self.groupBox.setObjectName("Extrusion Type")

            self.radAsIs = QtGui.QRadioButton(self.groupBox)
            self.radAsIs.setObjectName("radAsIs")
            self.radAsIs.setText("As Is")

            self.radMerge = QtGui.QRadioButton(self.groupBox)
            self.radMerge.setObjectName("radMerge")
            self.radMerge.setText("Merge")

            self.radSubtract = QtGui.QRadioButton(self.groupBox)
            self.radSubtract.setObjectName("radSubtract")
            self.radSubtract.setText("Subtract")

            self.la.addWidget(self.e1)
            self.la.addWidget(self.ExtrudeLBL)
            self.la.addWidget(self.lblExtrudeSize)
            self.la.addWidget(self.combListExtrudeStep)
            self.la.addWidget(okbox)

            # Adding checkbox for Merge, Subtract Or just leave it "As is"
            self.la.addWidget(self.radAsIs)
            self.la.addWidget(self.radMerge)
            self.la.addWidget(self.radSubtract)

            self.radAsIs.setChecked(True)
            self.radAsIs.toggled.connect(lambda: self.btnState(self.radAsIs))
            self.radMerge.toggled.connect(lambda: self.btnState(self.radMerge))
            self.radSubtract.toggled.connect(
                lambda: self.btnState(self.radSubtract))

            QtCore.QObject.connect(okbox, QtCore.SIGNAL("accepted()"),
                                   self.hide)
            QtCore.QMetaObject.connectSlotsByName(self.dialog)

            return self.dialog

        except Exception as err:
            faced.EnableAllToolbar(True)
            App.Console.PrintError("'Design456_Extrude' getMainWindow-Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
def smartlbl_callback(smartLine, obj, parentlink):
    """
        callback when label is double clicked
    """
    # clone the object
    p1 = smartLine.w_vector[0]
    p2 = smartLine.w_vector[1]
    deltaX = p2.x - p1.x
    deltaY = p2.y - p1.y
    deltaZ = p2.z - p1.z
    side = None
    if deltaX == 0 and deltaZ == 0:
        side = 'y'
    elif deltaY == 0.0 and deltaZ == 0.0:
        side = 'x'
    elif deltaY == 0.0 and deltaX == 0.0 and deltaZ != 0.0:
        side = 'z'
    newValue = 0
    # all lines has a 4 mm more size due to the way we calculate them. Remove that
    newValue = faced.GetInputValue().getDoubleValue()
    if newValue == 0 or newValue is None:
        # User canceled the value
        return -1

    if obj is None:
        # Only one object must be selected
        errMessage = "Select an object to scale"
        faced.errorDialog(errMessage)
        return

    cloneObj = Draft.clone(obj, forcedraft=True)
    scaleX = 1
    scaleY = 1
    scaleZ = 1

    if side == 'y':
        scaleY = newValue / (deltaY - SeperateLinesFromObject)
    elif side == 'x':
        scaleX = newValue / (deltaX - SeperateLinesFromObject)
    elif side == 'z':
        scaleZ = newValue / deltaZ
    else:
        print("error")
    try:
        App.ActiveDocument.openTransaction(translate("Design456",
                                                     "SmartScale"))
        cloneObj.Scale = App.Vector(scaleX, scaleY, scaleZ)

        obj.Visibility = False
        App.ActiveDocument.recompute()
        _name = obj.Label
        obj.Label = obj.Label + "old"
        __shape = Part.getShape(cloneObj,
                                '',
                                needSubElement=False,
                                refine=False)
        _simpleCopy = App.ActiveDocument.addObject('Part::Feature', _name)
        _simpleCopy.Shape = __shape
        App.ActiveDocument.recompute()
        App.ActiveDocument.removeObject(obj.Name)
        App.ActiveDocument.removeObject(cloneObj.Name)
        Gui.Selection.clearSelection()
        Gui.Selection.addSelection(_simpleCopy)
        _simpleCopy.Label = _name
        App.ActiveDocument.recompute()
        # All objects must get link to the new targeted object
        (_vectors,
         _lengths) = parentlink.returnVectorsFromBoundaryBox(_simpleCopy)
        for i in range(0, 3):
            parentlink.smartInd[i].set_target(_simpleCopy)
            parentlink.smartInd[i].w_vector = _vectors[i]
            parentlink.smartInd[i].changeLabelfloat(_lengths[i])
            parentlink.smartInd[i].redraw()  # Update the vertices here
        App.ActiveDocument.recompute()
        App.ActiveDocument.commitTransaction()  # undo reg.

    except Exception as err:
        App.Console.PrintError("'Design456_SmartScale' Failed. "
                               "{err}\n".format(err=str(err)))
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
示例#21
0
    def Activated(self):
        try:
            _points = []
            s = Gui.Selection.getSelectionEx()
            if len(s) > 2:
                # Two object must be selected
                errMessage = "Select only two vertices "
                faced.getInfo(s).errorDialog(errMessage)
                return
            elif len(s) == 1:
                #We have one line .. end and start will be one.
                for pnt in s[0].Object.Shape.Vertexes:
                    if (pnt != s[0].Object.End):
                        _points.append(pnt.Point)
                newObj = _draft.makeWire(_points)
                newObj.Start = _points[0]
                newObj.End = _points[0]
                App.ActiveDocument.removeObject(s[0].Object.Name)
                App.ActiveDocument.recompute()
            elif len(s) == 2:
                s1 = s[0]
                s2 = s[1]
                tempPoint = None

                p1 = []
                p2 = []
                p1.append(s1.Object.Start)
                p1.append(s1.Object.End)
                p2.append(s2.Object.Start)
                p2.append(s2.Object.End)
                if p2[0] == s2.SubObjects[0].Point:
                    for pnt in reversed(s2.Object.Shape.Vertexes):
                        _points.append(pnt.Point)
                else:
                    for pnt in s2.Object.Shape.Vertexes:
                        _points.append(pnt.Point)

                if p1[0] != s1.SubObjects[0].Point:
                    for pnt in reversed(s1.Object.Shape.Vertexes):
                        if pnt.Point != p1[0]:
                            #Start and selected is the same ignore it
                            _points.append(pnt.Point)
                else:
                    for pnt in s1.Object.Shape.Vertexes:
                        if pnt.Point != p1[1]:
                            #End and selected is the same ignore it
                            _points.append(pnt.Point)

                plc = s2.Object.Placement
                plc.Rotation.Q = s2.Object.Placement.Rotation.Q
                ang = s2.Object.Placement.Rotation.Angle
                axes = s2.Object.Placement.Rotation.Axis
                newObj = _draft.makeWire(_points)
                newObj.Start = _points[0]
                newObj.End = _points[len(_points) - 1]

                #newObj.Placement=plc
                #newObj.Placement.Rotation.Axis=axes
                #newObj.Placement.Rotation.Angle=ang

                App.ActiveDocument.removeObject(s1.Object.Name)
                App.ActiveDocument.removeObject(s2.Object.Name)
            App.ActiveDocument.recompute()

        except Exception as err:
            App.Console.PrintError("'Part Surface' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#22
0
    def Activated(self):
        try:
            # Save object name that will be divided.
            selection = Gui.Selection.getSelectionEx()
            if (len(selection) < 1):
                # An object must be selected
                errMessage = "Select an object to use Split Tool"
                faced.getInfo(selection).errorDialog(errMessage)
                return
            shape = selection[0].Object.Shape
            bb = shape.BoundBox
            length = max(bb.XLength, bb.YLength, bb.ZLength)

            nameOfselectedObject = selection[0].ObjectName
            totalName = nameOfselectedObject + '_cs'
            """ slow function . . you need to use wait before getting 
				the answer as the execution is continuing down """
            Gui.runCommand('Part_CrossSections', 0)
            gcompund = App.ActiveDocument.addObject("Part::Compound",
                                                    "Compound")

            App.ActiveDocument.recompute()

            # get object name
            # We need this delay to let user choose the split form. And
            getExtrude_cs = None  # Dummy variable used to wait for the Extrude_cs be made
            while (getExtrude_cs is None):
                getExtrude_cs = App.ActiveDocument.getObject(totalName)
                _sleep(.1)
                Gui.updateGui()
            # Begin command Part_Compound
            gcompund.Links = [
                getExtrude_cs,
            ]

            # Begin command Part_BooleanFragments
            j = SPLIT.makeBooleanFragments(name='BooleanFragments')
            j.Objects = [
                gcompund,
                App.ActiveDocument.getObject(nameOfselectedObject)
            ]
            j.Mode = 'Standard'
            j.Proxy.execute(j)
            j.purgeTouched()
            App.ActiveDocument.recompute()
            if j.isValid() == False:
                App.ActiveDocument.removeObject(j.Name)
                # Shape is not OK
                errMessage = "Failed to fillet the objects"
                faced.getInfo(selection).errorDialog(errMessage)
            else:
                # Make a simple copy
                newShape = Part.getShape(j,
                                         '',
                                         needSubElement=False,
                                         refine=False)
                NewJ = App.ActiveDocument.addObject(
                    'Part::Feature', 'SplitedObject').Shape = newShape
                # Remove Old objects
                for obj in j.Objects:
                    App.ActiveDocument.removeObject(obj.Name)
                App.ActiveDocument.removeObject(totalName)
                App.ActiveDocument.removeObject(j.Name)

            App.ActiveDocument.recompute()
        except Exception as err:
            App.Console.PrintError("'SplitObject' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#23
0
    def calculateNewVector(self):
        """[Calculate the new position that will be used for the Wheel drawing]
        Returns:
            [App.Vector]: [Position where the Wheel will be moved to]
        """
        # For now the Wheel will be at the top
        rotAxis = App.Vector(0, 0, 0)  # Axis of the rotation for face2
        faceAngle = 0  # New angle due to the rotation of face2
        # New location for Face2 due to the rotation of the face
        base = App.Vector(0, 0, 0)
        try:
            # TODO:FIXME
            pl = self.calculateRotatedNormal(self.direction)
            if (self.ExtractedFaces[1] is not None):
                self.ExtractedFaces[1].Placement = pl
            face2 = None
            if (self.isFaceOf3DObj()):
                # The whole object is selected
                sub1 = self.ExtractedFaces[1]
                face2 = sub1.Shape
            else:
                face2 = self.ExtractedFaces[1].Shape

            yL = face2.CenterOfMass
            uv = face2.Surface.parameter(yL)
            nv = face2.normalAt(uv[0], uv[1])
            self.normalVector = nv
            # Setup calculation.
            if (face2.Surface.Rotation is None):
                calAn = math.degrees(nv.getAngle(App.Vector(1, 1, 0)))
                rotation = [0, 0, 1, calAn]

            else:
                rotation = [
                    face2.Surface.Rotation.Axis.x,
                    face2.Surface.Rotation.Axis.y,
                    face2.Surface.Rotation.Axis.z,
                    math.degrees(face2.Surface.Rotation.Angle)
                ]

            if (self.extrudeLength == 0):
                d = self.extrudeLength = 1
            else:
                d = self.extrudeLength
            # The face itself
            self.ExtractedFaces[
                1].Placement.Base = face2.Placement.Base + d * nv
            if (self.wheelObj is not None):
                self.wheelObj.w_vector[0] = yL + d * nv  # the wheel

            self.FirstLocation = yL + d * nv  # the wheel
            App.ActiveDocument.recompute()
            return rotation

        except Exception as err:
            faced.EnableAllToolbar(True)
            App.Console.PrintError("'ExtractFace getWheelPosition-Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#24
0
    def Activated(self):
        try:
            App.ActiveDocument.openTransaction(
                translate("Design456", "Part Pyramid"))
            obj = App.Placement()
            Faces = QtGui.QInputDialog.getInt(None, "Faces", "Faces:")[0]
            if (Faces == 0):
                return  # Nothing to do here
            obj.Rotation.Q = (0.0, 0.0, 0, 1.0)
            obj.Base = App.Vector(0.0, 0.0, 0.0)
            newObj = _draft.makePolygon(Faces,
                                        radius=10,
                                        inscribed=True,
                                        placement=obj,
                                        face=True,
                                        support=None)
            _draft.autogroup(newObj)
            App.ActiveDocument.recompute()
            Gui.Selection.clearSelection()
            Gui.Selection.addSelection(App.ActiveDocument.Name, newObj.Name,
                                       'Face1', 0, 0, 0)
            selectedEdge = Gui.Selection.getSelectionEx()[0].SubObjects[
                0]  # select one element

            # loft
            plr = plDirection = App.Placement()
            yL = selectedEdge.CenterOfMass
            uv = selectedEdge.Surface.parameter(yL)
            nv = selectedEdge.normalAt(uv[0], uv[1])
            direction = yL.sub(nv + yL)
            r = App.Rotation(App.Vector(0, 0, 1), direction)
            plDirection.Rotation.Q = r.Q
            plDirection.Base = yL
            plr = plDirection

            firstFace = newObj
            point = _draft.makePoint(0, 0.0, 10.0)

            newObj1 = App.ActiveDocument.addObject('Part::Loft', 'tempPyramid')
            App.ActiveDocument.ActiveObject.Sections = [
                firstFace,
                point,
            ]
            App.ActiveDocument.ActiveObject.Solid = True
            newObj1 = App.ActiveDocument.ActiveObject
            App.ActiveDocument.recompute()

            # copy
            newOBJ = App.ActiveDocument.addObject(
                'Part::Feature',
                'Pyramid').Shape = _part.getShape(newObj1,
                                                  '',
                                                  needSubElement=False,
                                                  refine=False)
            App.ActiveDocument.recompute()

            # Remove Old objects. I don't like to keep so many objects without any necessity.
            for obj in newObj1.Sections:
                App.ActiveDocument.removeObject(obj.Name)
            # Gui.SendMsgToActiveView("ViewFit")
            App.ActiveDocument.removeObject(newObj1.Name)
            # App.ActiveDocument.removeObject(point)
            App.ActiveDocument.commitTransaction()  #undo reg.
            App.ActiveDocument.recompute()
            v = Gui.ActiveDocument.ActiveView
            faced.PartMover(v,
                            App.ActiveDocument.ActiveObject,
                            deleteOnEscape=True)

        except Exception as err:
            App.Console.PrintError("'Part::Pyramid' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#25
0
    def getMainWindow(self):
        """[Create the tab for the tool]

        Raises:
            Exception: [If no tabs were found]
            Exception: [If something unusual happen]

        Returns:
            [dialog]: [the new dialog which will be added as a tab to the tab section of FreeCAD]
        """
        try:
            toplevel = QtGui.QApplication.topLevelWidgets()
            self.mw = None
            for i in toplevel:
                if i.metaObject().className() == "Gui::MainWindow":
                    self.mw = i
            if self.mw is None:
                raise Exception("No main window found")
            dw = self.mw.findChildren(QtGui.QDockWidget)
            for i in dw:
                if str(i.objectName()) == "Combo View":
                    self.tab = i.findChild(QtGui.QTabWidget)
                elif str(i.objectName()) == "Python Console":
                    self.tab = i.findChild(QtGui.QTabWidget)
            if self.tab is None:
                raise Exception("No tab widget found")
            oldsize = self.tab.count()
            self.dialog = QtGui.QDialog()
            self.tab.addTab(self.dialog, "Smart Extrude Rotate")
            self.frmRotation = QtGui.QFrame(self.dialog)
            self.dialog.resize(200, 450)
            self.frmRotation.setGeometry(QtCore.QRect(10, 190, 231, 181))
            self.frame_2 = QtGui.QFrame(self.dialog)
            self.frame_2.setGeometry(QtCore.QRect(10, 195, 231, 151))
            self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
            self.frame_2.setFrameShadow(QtGui.QFrame.Sunken)
            self.frame_2.setObjectName("frame_2")
            self.gridLayoutWidget_3 = QtGui.QWidget(self.frame_2)
            self.gridLayoutWidget_3.setGeometry(QtCore.QRect(10, 40, 211, 101))
            self.gridLayoutWidget_3.setObjectName("gridLayoutWidget_3")
            self.gridExtrusionResult = QtGui.QGridLayout(
                self.gridLayoutWidget_3)
            self.gridExtrusionResult.setContentsMargins(0, 0, 0, 0)
            self.gridExtrusionResult.setObjectName("gridExtrusionResult")
            self.radioAsIs = QtGui.QRadioButton(self.gridLayoutWidget_3)
            self.radioAsIs.setObjectName("radioAsIs")
            self.gridExtrusionResult.addWidget(self.radioAsIs, 0, 0, 1, 1)
            self.radioMerge = QtGui.QRadioButton(self.gridLayoutWidget_3)
            self.radioMerge.setObjectName("radioMerge")
            self.gridExtrusionResult.addWidget(self.radioMerge, 1, 0, 1, 1)
            self.lblExtrusionResult = QtGui.QLabel(self.frame_2)
            self.lblExtrusionResult.setGeometry(QtCore.QRect(10, 0, 191, 61))
            font = QtGui.QFont()
            font.setPointSize(10)
            self.lblExtrusionResult.setFont(font)
            self.lblExtrusionResult.setObjectName("lblExtrusionResult")
            self.btnOK = QtGui.QDialogButtonBox(self.dialog)
            self.btnOK.setGeometry(QtCore.QRect(270, 360, 111, 61))
            font = QtGui.QFont()
            font.setPointSize(10)
            font.setBold(True)
            font.setWeight(75)
            self.btnOK.setFont(font)
            self.btnOK.setObjectName("btnOK")
            self.btnOK.setStandardButtons(QtGui.QDialogButtonBox.Ok)
            self.lblTitle = QtGui.QLabel(self.dialog)
            self.lblTitle.setGeometry(QtCore.QRect(10, 10, 281, 91))
            font = QtGui.QFont()
            font.setFamily("Times New Roman")
            font.setPointSize(10)
            self.lblTitle.setFont(font)
            self.lblTitle.setObjectName("lblTitle")
            self.ExtrudeLBL = QtGui.QLabel(self.dialog)
            self.ExtrudeLBL.setGeometry(QtCore.QRect(10, 145, 321, 40))
            font = QtGui.QFont()
            font.setPointSize(10)
            self.ExtrudeLBL.setFont(font)
            self.ExtrudeLBL.setObjectName("ExtrudeLBL")
            self.RotateLBL = QtGui.QLabel(self.dialog)
            self.RotateLBL.setGeometry(QtCore.QRect(10, 100, 281, 40))
            font = QtGui.QFont()
            font.setPointSize(10)
            self.RotateLBL.setFont(font)
            self.RotateLBL.setObjectName("RotateLBL")

            _translate = QtCore.QCoreApplication.translate
            self.dialog.setWindowTitle(
                _translate("Dialog", "Smart Extrude Rotate"))

            self.radioAsIs.setText(_translate("Dialog", "As Is"))
            self.radioMerge.setText(_translate("Dialog", "Merge"))
            self.lblExtrusionResult.setText(
                _translate("Dialog", "Extrusion Result"))
            self.lblTitle.setText(
                _translate(
                    "Dialog", "(Smart Extrude Rotate)\n"
                    "For quicker applying Extrude"))
            self.ExtrudeLBL.setText(_translate("Dialog", "Extrusion Length="))
            self.RotateLBL.setText(_translate("Dialog", "Extrusion Angle="))

            self.radioAsIs.setChecked(True)
            # self.radioBottom.setChecked(True)

            self.radioAsIs.toggled.connect(
                lambda: self.btnState(self.radioAsIs))
            self.radioMerge.toggled.connect(
                lambda: self.btnState(self.radioMerge))

            QtCore.QObject.connect(self.btnOK, QtCore.SIGNAL("accepted()"),
                                   self.hide)
            QtCore.QMetaObject.connectSlotsByName(self.dialog)
            self.tab.setCurrentWidget(self.dialog)

            return self.dialog

        except Exception as err:
            faced.EnableAllToolbar(True)
            App.Console.PrintError(
                "'Design456_ExtrudeRotate' ExtractFace-Failed. "
                "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#26
0
    def Activated(self):
        """[ Executes when the tool is used   ]
        """
        import ThreeDWidgets.fr_coinwindow as win
        self.coinFaces = coin.SoSeparator()
        self.w_rotation = [0.0, 0.0, 0.0]  #
        self.setupRotation = [0, 0, 0, 0]
        self.counter = 0
        self.run_Once = False
        self.tweakLength = 0
        self.oldTweakLength = 0
        self.isItRotation = False
        self.newFaces = []
        self.savedVertices = [[]]
        self.tweakLength = 0
        self.oldTweakLength = 0

        try:
            self.view = Gui.ActiveDocument.ActiveView
            self.sg = self.view.getSceneGraph()
            sel = Gui.Selection.getSelectionEx()

            if len(sel) > 2:
                errMessage = "Please select only one edge and try again"
                faced.errorDialog(errMessage)

            App.ActiveDocument.openTransaction(
                translate("Design456", "ExtendEdge"))

            self.MoveMentDirection = 'A'

            self.selectedObj = sel[0].Object
            self.selectedObj.Visibility = False
            if (hasattr(sel[0], "SubObjects")):
                self.selectedEdge = sel[0].SubObjects[0]
            else:
                raise Exception("Not implemented")

            if (not hasattr(self.selectedEdge, "Curve")):
                errmsg = "Please select an edge "
                faced.errorDialog(errmsg)
                self.selectedObj.Visibility = True
                self.__del__()
                return

            # Register undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "EdgeExtend"))

            # Recreate the object in separated shapes.
            self.saveVertices()

            if (hasattr(self.selectedEdge, "Vertexes")):
                self.oldEdgeVertexes = self.selectedEdge.Vertexes
            if not hasattr(self.selectedEdge, 'Edges'):
                raise Exception("Please select only one edge and try again")
            if not (type(self.selectedEdge.Curve) == _part.Line
                    or type(self.selectedEdge.Curve) == _part.BezierCurve):
                msg = "Curve edges are not supported yet"
                faced.errorDialog(msg)
                return

            self.setupRotation = self.calculateNewVector()

            self.ExtractTheEdge()
            self.newEdgeVertexes = self.newEdge.Shape.Vertexes
            App.ActiveDocument.removeObject(self.selectedObj.Name)

            # Undo
            App.ActiveDocument.openTransaction(
                translate("Design456", "ExtendEdge"))

            if self.oldEdgeVertexes[
                    0].Point.z < self.selectedObj.Shape.BoundBox.ZMin:
                self.FirstLocation.z = self.selectedObj.Shape.BoundBox.ZMin - self.awayFromObj

            # Decide how the Degree disc be drawn
            self.discObj = Fr_ThreeArrows_Widget(
                [self.FirstLocation, App.Vector(0, 0, 0)],  #
                # label
                (str(round(self.w_rotation[0], 2)) + "°" +
                 str(round(self.w_rotation[1], 2)) + "°" +
                 str(round(self.w_rotation[2], 2)) + "°"),
                FR_COLOR.FR_WHITE,  # lblcolor
                [FR_COLOR.FR_RED, FR_COLOR.FR_GREEN, FR_COLOR.FR_BLUE
                 ],  # arrows color
                # rotation
                [0.0, 0.0, 0.0, 0.0],
                self.setupRotation,  # setup rotation
                [15.0, 15.0, 15.0],  # scale
                0,  # type
                0,  # opacity
                10)  # distance between them

            # Different callbacks for each action.
            self.discObj.w_xAxis_cb_ = self.MouseMovement_cb
            self.discObj.w_yAxis_cb_ = self.MouseMovement_cb
            self.discObj.w_zAxis_cb_ = self.MouseMovement_cb

            self.discObj.w_discXAxis_cb_ = self.callback_Rotate
            self.discObj.w_discYAxis_cb_ = self.callback_Rotate
            self.discObj.w_discZAxis_cb_ = self.callback_Rotate

            self.discObj.w_callback_ = self.callback_release
            self.discObj.w_userData.callerObject = self

            self.COIN_recreateObject()

            if self._mywin is None:
                self._mywin = win.Fr_CoinWindow()

            self._mywin.addWidget(self.discObj)
            mw = self.getMainWindow()
            self._mywin.show()

            App.ActiveDocument.recompute()

        except Exception as err:

            App.Console.PrintError("'Activated' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
    def Activated(self):
        try:

            s = Gui.Selection.getSelectionEx()
            if (len(s) < 1 or len(s) > 2):
                # Two object must be selected
                errMessage = "Select two edges or two wire to make a face or "
                faced.errorDialog(errMessage)
                return
            elementsName = None
            subObj = None
            obj1 = None
            obj2 = None
            if len(s) == 1:
                obj1shp = s[0].SubObjects[0].copy()
                obj1 = App.ActiveDocument.addObject('Part::Feature', "E1")
                obj1.Shape = obj1shp
                obj2shp = s[0].SubObjects[1].copy()
                obj2 = App.ActiveDocument.addObject('Part::Feature', "E2")
                obj2.Shape = obj2shp
                App.ActiveDocument.recompute()
                elementsName = [obj1.Name, obj2.Name]
                subObj = [obj1, obj2]
            elif len(s) == 2:
                obj1shp = s[0].SubObjects[0].copy()
                obj1 = App.ActiveDocument.addObject('Part::Feature', "E1")
                obj1.Shape = obj1shp
                obj2shp = s[1].SubObjects[0].copy()
                obj2 = App.ActiveDocument.addObject('Part::Feature', "E2")
                obj2.Shape = obj2shp
                elementsName = [obj1.Name, obj2.Name]
                subObj = [obj1, obj2]
            for ss in s:
                word = ss.FullName
                if (word.find('Vertex') != -1):
                    # Two lines or curves or wires must be selected
                    errMessage = "Select two edges or two wires not Vertex"
                    faced.errorDialog(errMessage)
                    return
            App.ActiveDocument.openTransaction(
                translate("Design456", "Surface"))

            newObj = App.ActiveDocument.addObject('Part::RuledSurface',
                                                  'tempSurface')

            newObj.Curve1 = subObj[0]
            newObj.Curve2 = subObj[1]
            App.ActiveDocument.recompute()

            # Make a simple copy of the object
            newShape = _part.getShape(newObj,
                                      '',
                                      needSubElement=False,
                                      refine=True)
            tempNewObj = App.ActiveDocument.addObject('Part::Feature',
                                                      'Surface')
            tempNewObj.Shape = newShape
            App.ActiveDocument.ActiveObject.Label = 'Surface'
            App.ActiveDocument.recompute()
            if tempNewObj.isValid() is False:
                App.ActiveDocument.removeObject(tempNewObj.Name)
                # Shape != OK
                errMessage = "Failed to create the face"
                faced.errorDialog(errMessage)
            else:
                App.ActiveDocument.removeObject(newObj.Name)
                App.ActiveDocument.commitTransaction()  # undo reg.de here
                App.ActiveDocument.recompute()
                if (obj1 is not None and obj2 is not None):
                    App.ActiveDocument.removeObject(obj1.Name)
                    App.ActiveDocument.removeObject(obj2.Name)

        except Exception as err:
            App.Console.PrintError("'Part Surface' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
示例#28
0
    def makeIt(self, commandType):
        try:
            nObjects = []
            newShape = None
            simpl_cpy = None
            self.commandType = commandType
            selection = Gui.Selection.getSelectionEx()
            # Two object must be selected
            if (len(selection) < 2 or len(selection) > 2):
                errMessage = "Select two objects to use Common 2D Tool"
                faced.getInfo(selection).errorDialog(errMessage)
                return None
            else:
                nObjects.clear()
                GlobalPlacement = App.ActiveDocument.getObject(
                    selection[0].Object.Name).Placement
                for a2dobj in selection:
                    m = App.ActiveDocument.getObject(a2dobj.Object.Name)
                    f = App.ActiveDocument.addObject('Part::Extrusion',
                                                     'ExtrudeOriginal')
                    f.Base = App.ActiveDocument.getObject(m.Name)
                    f.DirMode = "Normal"
                    f.DirLink = a2dobj.Object
                    if faced.getDirectionAxis() == "x":
                        f.Dir = (1, 0, 0)
                    elif faced.getDirectionAxis() == "y":
                        f.Dir = (0, 1, 0)
                    else:
                        f.Dir = (0, 0, 1)

                    f.LengthFwd = 1.00
                    f.LengthRev = 0.0
                    f.Solid = True
                    f.Reversed = False
                    f.Symmetric = False
                    f.TaperAngle = 0.0
                    f.TaperAngleRev = 0.0
                    App.ActiveDocument.recompute()

                    # Make a simple copy of the object
                    newShape = _part.getShape(f,
                                              '',
                                              needSubElement=False,
                                              refine=True)
                    newObj = App.ActiveDocument.addObject(
                        'Part::Feature', 'Extrude')
                    newObj.Shape = newShape
                    App.ActiveDocument.recompute()
                    App.ActiveDocument.ActiveObject.Label = f.Label
                    App.ActiveDocument.recompute()
                    App.ActiveDocument.removeObject(f.Name)
                    App.ActiveDocument.removeObject(m.Name)
                    App.ActiveDocument.recompute()
                    nObjects.append(newObj)

                tempResult = self.DoCommand(
                    self.commandType)  #Create the common 3D shape
                if (self.commandType == 1 or self.commandType == 3):
                    tempResult.Shapes = nObjects
                    tempResult.Refine = True
                elif (self.commandType == 2):
                    tempResult.Tool = nObjects[1]
                    tempResult.Base = nObjects[0]
                App.ActiveDocument.recompute()
                #Make a simple version
                newShape = _part.getShape(tempResult,
                                          '',
                                          needSubElement=False,
                                          refine=False)
                simpl_cpy = App.ActiveDocument.addObject(
                    'Part::Feature', 'Shape')
                simpl_cpy.Shape = newShape  #simple version of the 3D common
                App.ActiveDocument.recompute()
                for name in nObjects:
                    App.ActiveDocument.removeObject(name.Name)
                App.ActiveDocument.removeObject(tempResult.Name)
                App.ActiveDocument.recompute()
            # Extract the face
            sh = simpl_cpy.Shape.copy()
            #sh.Placement = GlobalPlacement  # Result.Placement
            sh.Placement.Base.z = -1

            Gui.Selection.clearSelection()
            App.ActiveDocument.recompute()
            Gui.Selection.addSelection(App.ActiveDocument.Name, simpl_cpy.Name)
            s = Gui.Selection.getSelectionEx()[0]
            faceName = faced.SelectTopFace(simpl_cpy).Activated()

            newobj = App.ActiveDocument.addObject("Part::Feature",
                                                  self.localShapeName)
            print(faceName)
            newobj.Shape = sh.getElement(faceName)
            App.ActiveDocument.removeObject(simpl_cpy.Name)
            del nObjects[:]
        except Exception as err:
            App.Console.PrintError("'makeIt' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)