Python Part.Shape() Examples

The following are 30 code examples of Part.Shape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Part , or try the search function .
Example #1
Source File: profile_editor.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, points, sh=None):
        super(MarkerOnShape, self).__init__(points, True)
        self._shape = None
        self._sublink = None
        self._tangent = None
        self._translate = coin.SoTranslation()
        self._text_font = coin.SoFont()
        self._text_font.name = "Arial:Bold"
        self._text_font.size = 13.0
        self._text = coin.SoText2()
        self._text_switch = coin.SoSwitch()
        self._text_switch.addChild(self._translate)
        self._text_switch.addChild(self._text_font)
        self._text_switch.addChild(self._text)
        self.on_drag_start.append(self.add_text)
        self.on_drag_release.append(self.remove_text)
        self.addChild(self._text_switch)
        
        if isinstance(sh,Part.Shape):
            self.snap_shape = sh
        elif isinstance(sh,(tuple,list)):
            self.sublink = sh 
Example #2
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def sweep(cls, outerWire, innerWires, path, makeSolid=True, isFrenet=False):
        """
        Attempt to sweep the list of wires  into a prismatic solid along the provided path

        :param outerWire: the outermost wire
        :param innerWires: a list of inner wires
        :param path: The wire to sweep the face resulting from the wires over
        :return: a Solid object
        """

        # FreeCAD allows this in one operation, but others might not
        freeCADWires = [outerWire.wrapped]
        for w in innerWires:
            freeCADWires.append(w.wrapped)

        # f = FreeCADPart.Face(freeCADWires)
        wire = FreeCADPart.Wire([path.wrapped])
        result = wire.makePipeShell(freeCADWires, makeSolid, isFrenet)

        return Shape.cast(result) 
Example #3
Source File: dev.py    From NodeEditor with MIT License 6 votes vote down vote up
def cylindricprojection(self,*args, **kwargs):

    s=App.activeDocument().ReflectLines001.Shape

    eds=[]
    for e in s.Edges:
        pts2=[]
        pts=e.discretize(100)
        for p in pts:
            h=p.y
            arc=np.arctan2(p.x,p.z)
            r=FreeCAD.Vector(p.x,p.z).Length
            R=150
            p2=FreeCAD.Vector(np.sin(arc)*R,h,np.cos(arc)*R)
            pts2 += [p2]

        Part.show(Part.makePolygon(pts2))

 


#-------------------------- 
Example #4
Source File: dev.py    From NodeEditor with MIT License 6 votes vote down vote up
def mapEdgesLines( uvedges,face):

    if face == None:
        sayW("no face")
        return Part.Shape()
    col=[]
    say("face",face)
    umin,umax,vmin,vmax=face.ParameterRange
    sf=face.Surface
    for edge in uvedges:
        ua,va,ub,vb=edge
        ua=umin+ua*(umax-umin)
        va=vmin+va*(vmax-vmin)

        ub=umin+ub*(umax-umin)
        vb=vmin+vb*(vmax-vmin)
        
        pa=sf.value(ua,va)
        pb=sf.value(ub,vb)
        say(pa)
        col += [Part.makePolygon([pa,pb])]

    shape=Part.Compound(col)
    return shape 
Example #5
Source File: anyShape.py    From flamingo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, obj,name="valve",fileName='ballDN15.stp',ports='0:0:0'):
    #obj.Proxy = self
    super(AnyThing,self).__init__(obj)
    # define common properties
    obj.PType="Any"
    # define specific properties
    obj.addProperty("App::PropertyString","FileName","AnyThing","The file of the shape (inside ./shapes)").FileName=fileName
    portslist=list()
    if ports:
      for port in ports.split('/'):
        portslist.append(FreeCAD.Vector([float(i) for i in port.split(":")]))
    obj.Ports=portslist
    if fileName:
      s=Part.Shape()
      path=join(dirname(abspath(__file__)),"shapes",fileName)
      if exists(path):
        s.read(path)
        obj.Shape=s
      else:
        FreeCAD.Console.PrintError("%s file doesn't exist" %fileName) 
Example #6
Source File: dev.py    From NodeEditor with MIT License 6 votes vote down vote up
def run_FreeCAD_Nurbs(self):
    
    #shape=FreeCAD.ActiveDocument.Cone.Shape.Face1
    #shape=FreeCAD.ActiveDocument.Sphere.Shape.Face1
    shape=self.getPinObject("shape")
    if shape is None:
        sayErOb(self,"no shape")
        return

        return
    n=shape.toNurbs()
    say(n.Faces)
    say(n.Edges)
    sf=n.Face1.Surface
    ssff=Part.BSplineSurface()
    ssff.buildFromPolesMultsKnots(sf.getPoles(),
        sf.getUMultiplicities(), sf.getVMultiplicities(),
        sf.getUKnots(),sf.getVKnots(),False,False,sf.UDegree,sf.VDegree)
    
    ff=ssff.toShape()
    self.setPinObject("Shape_out",ff) 
Example #7
Source File: Sketch_On_Surface.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def Activated(self):
        doc = FreeCAD.ActiveDocument
        sketch, face_link = self.get_selection()
        if not sketch and not face_link:
            FreeCAD.Console.PrintMessage("Please select a face (in the 3D view) or a sketch\n")
            return
        if not sketch:
            sketch = doc.addObject('Sketcher::SketchObject','Mapped_Sketch')
            sketch.Support = face_link
            n = eval(face_link[1][0].lstrip('Face'))
            fa = face_link[0].Shape.Faces[n-1]
            build_sketch(sketch, fa)
            doc.recompute()
        sos = doc.addObject("Part::FeaturePython","Sketch On Surface")
        sketchOnSurface(sos)
        sos.Sketch = sketch
        sosVP(sos.ViewObject)
        doc.recompute()
        sketch.ViewObject.Visibility = False 
Example #8
Source File: FC_interaction_example.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_guide_params():
    sel = Gui.Selection.getSelectionEx()
    pts = list()
    for so in sel:
        pts.extend(so.PickedPoints)
    edges = list()
    for so in sel:
        for sen in so.SubElementNames:
            n = eval(sen.lstrip("Edge"))
            e = so.Object.Shape.Edges[n-1]
            edges.append(e)
    inter = list()
    for pt in pts:
        sol = None
        min = 1e50
        for e in edges:
            d,points,info = e.distToShape(Part.Vertex(pt))
            if d < min:
                min = d
                sol = [e,e.Curve.parameter(points[0][0])]
        inter.append(sol)
    return(inter) 
Example #9
Source File: manipulators.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, points, sh=None):
        super(MarkerOnShape, self).__init__(points, True)
        self._shape = None
        self._sublink = None
        self._tangent = None
        self._text_translate = coin.SoTranslation()
        self._text = coin.SoText2()
        self._text_switch = coin.SoSwitch()
        self._text_switch.addChild(self._text_translate)
        self._text_switch.addChild(self._text)
        self.on_drag_start.append(self.add_text)
        self.on_drag_release.append(self.remove_text)
        self.addChild(self._text_switch)
        
        if isinstance(sh,Part.Shape):
            self.snap_shape = sh
        elif isinstance(sh,(tuple,list)):
            self.sublink = sh 
Example #10
Source File: ParametricBlendCurve.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def update_shape(self):
        e1 = _utils.getShape(self.Object, "Edge1", "Edge")
        e2 = _utils.getShape(self.Object, "Edge2", "Edge")
        if e1 and e2:
            bc = nurbs_tools.blendCurve(e1,e2)
            v = Part.Vertex(self.m1.point)
            proj = v.distToShape(self.m1.snap_shape)[1][0][1]
            bc.param1 = e1.Curve.parameter(proj)
            #bc.param1 = (pa1 - self.m1.snap_shape.FirstParameter) / (self.m1.snap_shape.LastParameter - self.m1.snap_shape.FirstParameter)
            bc.scale1 = self.t1.parameter
            bc.cont1 = self.Object.Proxy.getContinuity(self.c1.text[0])

            v = Part.Vertex(self.m2.point)
            proj = v.distToShape(self.m2.snap_shape)[1][0][1]
            bc.param2 = e2.Curve.parameter(proj)
            #bc.param2 = (pa2 - self.m2.snap_shape.FirstParameter) / (self.m2.snap_shape.LastParameter - self.m2.snap_shape.FirstParameter)
            bc.scale2 = self.t2.parameter
            bc.cont2 = self.Object.Proxy.getContinuity(self.c2.text[0])
            bc.maxDegree = self.Object.DegreeMax
            bc.compute()
            self.Object.Shape = bc.Curve.toShape()
            return bc 
Example #11
Source File: splitCurves_2.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def Activated(self):
        edges = []
        sel = FreeCADGui.Selection.getSelectionEx()
        if sel == []:
            FreeCAD.Console.PrintError("Select the edges to split first !\n")
        for selobj in sel:
            if selobj.HasSubObjects:
                for i in range(len(selobj.SubObjects)):
                    if isinstance(selobj.SubObjects[i], Part.Edge):
                        self.makeSplitFeature((selobj.Object, selobj.SubElementNames[i]))
                        if selobj.Object.Shape:
                            if len(selobj.Object.Shape.Edges) == 1:
                                selobj.Object.ViewObject.Visibility = False
            else:
                self.makeSplitFeature((selobj.Object, []))
                if hasattr(selobj.Object,"ViewObject"):
                    selobj.Object.ViewObject.Visibility = False 
Example #12
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def transformGeometry(self, tMatrix):
        """
            tMatrix is a matrix object.

            returns a copy of the object, but with geometry transformed instead of just
            rotated.

            WARNING: transformGeometry will sometimes convert lines and circles to splines,
            but it also has the ability to handle skew and stretching transformations.

            If your transformation is only translation and rotation, it is safer to use transformShape,
            which doesn't change the underlying type of the geometry, but cannot handle skew transformations
        """
        tmp = self.wrapped.copy()
        tmp = tmp.transformGeometry(tMatrix)
        return Shape.cast(tmp) 
Example #13
Source File: utils.py    From FreeCAD_assembly3 with GNU General Public License v3.0 6 votes vote down vote up
def getElement(shape, element):
    res = None
    if not isinstance(shape, Part.Shape):
        try:
            res = getElementShape(shape, element)
            if res and not res.isNull():
                return res
        except Exception:
            return

    try:
        res = shape.getElement(element, True)
    except TypeError:
        try:
            # older FC does not accept the second 'silent' argument
            res = shape.getElement(element)
        except Exception:
            return
    except Exception:
        return
    if res and not res.isNull():
        return res 
Example #14
Source File: splitCurves_2.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def getShape(self, fp):
        if fp.Source is None:
            return None, None
        if fp.Source[1] == []: # No subshape given, take wire 1
            if fp.Source[0].Shape.Wires:
                w = fp.Source[0].Shape.Wire1
                e = w.approximate(1e-7, 1e-5, len(w.Edges), 7).toShape()
                #double tol2d = gp::Resolution();
                #double tol3d = 0.0001;
                #int maxseg=10, maxdeg=3;
                #static char* kwds_approx[] = {"Tol2d","Tol3d","MaxSegments","MaxDegree",NULL};
            else:
                return None, None
        else:
            e = _utils.getShape(fp, "Source", "Edge")
            w = False
        return e, w 
Example #15
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def rotate(self, startVector, endVector, angleDegrees):
        """
        Rotates a shape around an axis
        :param startVector: start point of rotation axis  either a 3-tuple or a Vector
        :param endVector:  end point of rotation axis, either a 3-tuple or a Vector
        :param angleDegrees:  angle to rotate, in degrees
        :return: a copy of the shape, rotated
        """
        if type(startVector) == tuple:
            startVector = Vector(startVector)

        if type(endVector) == tuple:
            endVector = Vector(endVector)

        tmp = self.wrapped.copy()
        tmp.rotate(startVector.wrapped, endVector.wrapped, angleDegrees)
        return Shape.cast(tmp) 
Example #16
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeLoft(cls, listOfWire, ruled=False):
        """
            makes a loft from a list of wires
            The wires will be converted into faces when possible-- it is presumed that nobody ever actually
            wants to make an infinitely thin shell for a real FreeCADPart.
        """
        # the True flag requests building a solid instead of a shell.

        return Shape.cast(FreeCADPart.makeLoft([i.wrapped for i in listOfWire], True, ruled)) 
Example #17
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeSphere(cls, radius, pnt=None, dir=None, angleDegrees1=None, angleDegrees2=None, angleDegrees3=None):
        """
        Make a sphere with a given radius
        By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360
        """
        return Shape.cast(FreeCADPart.makeSphere(radius, pnt.wrapped, dir.wrapped, angleDegrees1, angleDegrees2, angleDegrees3)) 
Example #18
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeTorus(cls, radius1, radius2, pnt=None, dir=None, angleDegrees1=None, angleDegrees2=None):
        """
        makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) --
        Make a torus with agiven radii and angles
        By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0
        ,angle1=360 and angle=360'
        """
        return Shape.cast(FreeCADPart.makeTorus(radius1, radius2, pnt, dir, angleDegrees1, angleDegrees2)) 
Example #19
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def Center(self):
        # A Part.Shape object doesn't have the CenterOfMass function, but it's wrapped Solid(s) does
        if isinstance(self.wrapped, FreeCADPart.Shape):
            # If there are no Solids, we're probably dealing with a Face or something similar
            if len(self.Solids()) == 0:
                return Vector(self.wrapped.CenterOfMass)
            elif len(self.Solids()) == 1:
                return Vector(self.Solids()[0].wrapped.CenterOfMass)
            elif len(self.Solids()) > 1:
                return self.CombinedCenter(self.Solids())
        elif isinstance(self.wrapped, FreeCADPart.Solid):
            return Vector(self.wrapped.CenterOfMass)
        else:
            raise ValueError("Cannot find the center of %s object type" % str(type(self.Solids()[0].wrapped))) 
Example #20
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeWedge(cls, xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max, pnt=None, dir=None):
        """
        Make a wedge located in pnt
        By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)
        """
        return Shape.cast(
            FreeCADPart.makeWedge(xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max, pnt, dir)) 
Example #21
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def fuse(self, solidToJoin):
        return Shape.cast(self.wrapped.fuse(solidToJoin.wrapped)) 
Example #22
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def intersect(self, toIntersect):
        """
        computes the intersection between this solid and the supplied one
        The result could be a face or a compound of faces
        """
        return Shape.cast(self.wrapped.common(toIntersect.wrapped)) 
Example #23
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def CombinedCenter(objects):
        """
        Calculates the center of mass of multiple objects.

        :param objects: a list of objects with mass
        """
        total_mass = sum(Shape.computeMass(o) for o in objects)
        weighted_centers = [o.wrapped.CenterOfMass.multiply(Shape.computeMass(o)) for o in objects]

        sum_wc = weighted_centers[0]
        for wc in weighted_centers[1:] :
            sum_wc = sum_wc.add(wc)

        return Vector(sum_wc.multiply(1./total_mass)) 
Example #24
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def CenterOfBoundBox(self, tolerance = 0.1):
        self.wrapped.tessellate(tolerance)
        if isinstance(self.wrapped, FreeCADPart.Shape):
            # If there are no Solids, we're probably dealing with a Face or something similar
            if len(self.Solids()) == 0:
                return Vector(self.wrapped.BoundBox.Center)
            elif len(self.Solids()) == 1:
                return Vector(self.Solids()[0].wrapped.BoundBox.Center)
            elif len(self.Solids()) > 1:
                return self.CombinedCenterOfBoundBox(self.Solids())
        elif isinstance(self.wrapped, FreeCADPart.Solid):
            return Vector(self.wrapped.BoundBox.Center)
        else:
            raise ValueError("Cannot find the center(BoundBox's) of %s object type" % str(type(self.Solids()[0].wrapped))) 
Example #25
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def transformShape(self, tMatrix):
        """
            tMatrix is a matrix object.
            returns a copy of the object, transformed by the provided matrix,
            with all objects keeping their type
        """
        tmp = self.wrapped.copy()
        tmp.transformShape(tMatrix)
        r = Shape.cast(tmp)
        r.forConstruction = self.forConstruction
        return r 
Example #26
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def mirror(self, mirrorPlane="XY", basePointVector=(0, 0, 0)):
        if mirrorPlane == "XY" or mirrorPlane== "YX":
            mirrorPlaneNormalVector = FreeCAD.Base.Vector(0, 0, 1)
        elif mirrorPlane == "XZ" or mirrorPlane == "ZX":
            mirrorPlaneNormalVector = FreeCAD.Base.Vector(0, 1, 0)
        elif mirrorPlane == "YZ" or mirrorPlane == "ZY":
            mirrorPlaneNormalVector = FreeCAD.Base.Vector(1, 0, 0)

        if type(basePointVector) == tuple:
            basePointVector = Vector(basePointVector)

        return Shape.cast(self.wrapped.mirror(basePointVector.wrapped, mirrorPlaneNormalVector)) 
Example #27
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def chamfer(self, length, length2, edgeList):
        """
        Chamfers the specified edges of this solid.
        :param length: length > 0, the length (length) of the chamfer
        :param length2: length2 > 0, optional parameter for asymmetrical chamfer. Should be `None` if not required.
        :param edgeList:  a list of Edge objects, which must belong to this solid
        :return: Chamfered solid
        """
        nativeEdges = [e.wrapped for e in edgeList]
        # note: we prefer 'length' word to 'radius' as opposed to FreeCAD's API
        if length2:
            return Shape.cast(self.wrapped.makeChamfer(length, length2, nativeEdges))
        else:
            return Shape.cast(self.wrapped.makeChamfer(length, nativeEdges)) 
Example #28
Source File: kicad.py    From fcad_pcb with MIT License 5 votes vote down vote up
def _makeWires(self,obj,name,offset=0,fill=False,label=None,
            fit_arcs=False,workplane=False):

        if self.add_feature:
            if self.make_sketch:
                obj = self._makeSketch(obj,name,label)
            elif isinstance(obj,Part.Shape):
                obj = self._makeObject('Part::Feature', '{}_wire'.format(name),
                        label,'Shape',obj)
            elif isinstance(obj,(list,tuple)):
                objs = []
                comp = []
                for o in obj:
                    if isinstance(o,Part.Shape):
                        comp.append(o)
                    else:
                        objs.append(o)
                if comp:
                    comp = Part.makeCompound(comp)
                    objs.append(self._makeObject('Part::Feature',
                            '{}_wire'.format(name),label,'Shape',comp))
                obj = objs

        if fill or offset:
            return self._makeArea(obj,name,offset=offset,fill=fill,
                    fit_arcs=fit_arcs,label=label,workplane=workplane)
        else:
            return self._makeCompound(obj,name,label=label) 
Example #29
Source File: kicad.py    From fcad_pcb with MIT License 5 votes vote down vote up
def loadModel(filename):
    mtime = None
    try:
        mtime = os.path.getmtime(filename)
        obj = _model_cache[filename]
        if obj[2] == mtime:
            logger.info('model cache hit');
            return obj
        else:
            logger.info('model reload due to time stamp change');
    except KeyError:
        pass
    except OSError:
        return

    import ImportGui
    doc = getActiveDoc()
    if not os.path.isfile(filename):
        return
    count = len(doc.Objects)
    dobjs = []
    try:
        ImportGui.insert(filename,doc.Name)
        dobjs = doc.Objects[count:]
        obj = doc.addObject('Part::Compound','tmp')
        obj.Links = dobjs
        recomputeObj(obj)
        dobjs = [obj]+dobjs
        obj = (obj.Shape.copy(),obj.ViewObject.DiffuseColor,mtime)
        _model_cache[filename] = obj
        return obj
    except Exception as ex:
        logger.error('failed to load model: {}'.format(ex))
    finally:
        for o in dobjs:
            doc.removeObject(o.Name) 
Example #30
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def shell(self, faceList, thickness, tolerance=0.0001):
        """
            make a shelled solid of given  by removing the list of faces

        :param faceList: list of face objects, which must be part of the solid.
        :param thickness: floating point thickness. positive shells outwards, negative shells inwards
        :param tolerance: modelling tolerance of the method, default=0.0001
        :return: a shelled solid

            **WARNING**  The underlying FreeCAD implementation can very frequently have problems
            with shelling complex geometries!
        """
        nativeFaces = [f.wrapped for f in faceList]
        return Shape.cast(self.wrapped.makeThickness(nativeFaces, thickness, tolerance))