Example #1
0
def getShapeFromMesh(mesh):
    import Part, MeshPart
    if mesh.isSolid() and (mesh.countComponents() == 1):
        # use the best method
        faces = []
        for f in mesh.Facets:
            p=f.Points+[f.Points[0]]
            pts = []
            for pp in p:
                pts.append(FreeCAD.Vector(pp[0],pp[1],pp[2]))
            faces.append(Part.Face(Part.makePolygon(pts)))
        shell = Part.makeShell(faces)
        solid = Part.Solid(shell)
        solid = solid.removeSplitter()
        return solid

    faces = []  
    segments = mesh.getPlanarSegments(0.001) # use rather strict tolerance here
    for i in segments:
        if len(i) > 0:
            wires = MeshPart.wireFromSegment(mesh, i)
            if wires:
                faces.append(makeFace(wires))
    try:
        se = Part.makeShell(faces)
    except:
        return None
    else:
        try:
            solid = Part.Solid(se)
        except:
            return se
        else:
            return solid
def getShapeFromMesh(mesh):
    import Part, MeshPart
    if mesh.isSolid() and (mesh.countComponents() == 1):
        # use the best method
        faces = []
        for f in mesh.Facets:
            p = f.Points + [f.Points[0]]
            pts = []
            for pp in p:
                pts.append(FreeCAD.Vector(pp[0], pp[1], pp[2]))
            faces.append(Part.Face(Part.makePolygon(pts)))
        shell = Part.makeShell(faces)
        solid = Part.Solid(shell)
        solid = solid.removeSplitter()
        return solid

    faces = []
    segments = mesh.getPlanarSegments(
        0.001)  # use rather strict tolerance here
    for i in segments:
        if len(i) > 0:
            wires = MeshPart.wireFromSegment(mesh, i)
            if wires:
                faces.append(makeFace(wires))
    try:
        se = Part.makeShell(faces)
    except:
        return None
    else:
        try:
            solid = Part.Solid(se)
        except:
            return se
        else:
            return solid
Example #3
0
def getShapeFromMesh(mesh,fast=True,tolerance=0.001,flat=False,cut=True):
    import Part, MeshPart, DraftGeomUtils
    if mesh.isSolid() and (mesh.countComponents() == 1) and fast:
        # use the best method
        faces = []
        for f in mesh.Facets:
            p=f.Points+[f.Points[0]]
            pts = []
            for pp in p:
                pts.append(FreeCAD.Vector(pp[0],pp[1],pp[2]))
            try:
                f = Part.Face(Part.makePolygon(pts))
            except:
                pass
            else:
                faces.append(f)
        shell = Part.makeShell(faces)
        solid = Part.Solid(shell)
        solid = solid.removeSplitter()
        return solid

    faces = []
    segments = mesh.getPlanarSegments(tolerance)
    #print len(segments)
    for i in segments:
        if len(i) > 0:
            wires = MeshPart.wireFromSegment(mesh, i)
            if wires:
                if flat:
                    nwires = []
                    for w in wires:
                        nwires.append(DraftGeomUtils.flattenWire(w))
                    wires = nwires
                try:
                    faces.append(makeFace(wires,method=int(cut)+1))
                except:
                    return None
    try:
        se = Part.makeShell(faces)
        se = se.removeSplitter()
        if flat:
            return se
    except Part.OCCError:
        try:
            cp = Part.makeCompound(faces)
        except Part.OCCError:
            return None
        else:
            return cp
    else:
        try:
            solid = Part.Solid(se)
        except Part.OCCError:
            return se
        else:
            return solid
Example #4
0
def createOrUpdateSimpleAssemblyShape(doc):
    visibleImportObjects = [
        obj for obj in doc.Objects if 'importPart' in obj.Content
        and hasattr(obj, 'ViewObject') and obj.ViewObject.isVisible()
        and hasattr(obj, 'Shape') and len(obj.Shape.Faces) > 0
    ]

    if len(visibleImportObjects) == 0:
        QtGui.QMessageBox.critical(
            QtGui.QApplication.activeWindow(),
            translate("A2plus_MuxAssembly",
                      "Cannot create SimpleAssemblyShape"),
            translate("A2plus_MuxAssembly", "No visible ImportParts found"))
        return

    sas = doc.getObject('SimpleAssemblyShape')
    if sas is None:
        sas = doc.addObject("Part::FeaturePython", "SimpleAssemblyShape")
        SimpleAssemblyShape(sas)
        #sas.ViewObject.Proxy = 0
        ViewProviderSimpleAssemblyShape(sas.ViewObject)
    faces = []
    shape_list = []
    for obj in visibleImportObjects:
        faces = faces + obj.Shape.Faces
        shape_list.append(obj.Shape)
    if len(faces) == 1:
        shell = Part.makeShell([faces])
    else:
        shell = Part.makeShell(faces)
    try:
        if a2plib.getUseSolidUnion():
            if len(shape_list) > 1:
                shape_base = shape_list[0]
                shapes = shape_list[1:]
                solid = shape_base.fuse(shapes)
            else:
                solid = Part.Solid(shape_list[0])
        else:
            solid = Part.Solid(
                shell
            )  # This does not work if shell includes spherical faces. FC-Bug ??
            # Fall back to shell if faces are misiing
            if len(shell.Faces) != len(solid.Faces):
                solid = shell
    except:
        # keeping a shell if solid is failing
        FreeCAD.Console.PrintWarning('Union of Shapes FAILED\n')
        solid = shell
    sas.Shape = solid  #shell
    sas.ViewObject.Visibility = False
Example #5
0
	def __init__(self, ship, trim, drafts):
		""" Constructor. performs plot and show it (Using pyxplot).
		@param ship Selected ship instance
		@param trim Trim in degrees.
		@param drafts List of drafts to be performed.
		"""
		# Compute data
		# Get external faces
		faces = self.externalFaces(ship.Shape)
		if len(faces) == 0:
			msg = QtGui.QApplication.translate("ship_console", "Can't detect external faces from ship object",
                                       None,QtGui.QApplication.UnicodeUTF8)
			FreeCAD.Console.PrintError(msg + '\n')
			return
		else:
			faces = Part.makeShell(faces)
		# Print data
		msg = QtGui.QApplication.translate("ship_console", "Computing hydrostatics",
                                   None,QtGui.QApplication.UnicodeUTF8)
		FreeCAD.Console.PrintMessage(msg + '...\n')
		self.points = []
		for i in range(0,len(drafts)):
			FreeCAD.Console.PrintMessage("\t%d / %d\n" % (i+1, len(drafts)))
			draft = drafts[i]
			point = Tools.Point(ship,faces,draft,trim)
			self.points.append(point)
		# Try to plot
		self.plotVolume()
		self.plotStability()
		self.plotCoeffs()
		# Save data
		if self.createDirectory():
			return
		if self.saveData(ship, trim, drafts):
			return
Example #6
0
def getShape(obj):
    "gets a shape from an IfcOpenShell object"
    import StringIO, Part
    sh = Part.Shape()
    sh.importBrep(StringIO.StringIO(obj.mesh.brep_data))
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ", obj.id
        else:
            if DEBUG: print "object ", obj.id, " doesn't contain any face"
    m = obj.matrix
    mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2],
                         m[5], m[8], m[11], 0, 0, 0, 1)
    sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj
    return sh
 def Activated(self):
     #first check if assembly mux part already existings
     checkResult = [
         obj for obj in FreeCAD.ActiveDocument.Objects
         if hasattr(obj, 'type') and obj.type == 'muxedAssembly'
     ]
     if len(checkResult) == 0:
         partName = 'muxedAssembly'
         debugPrint(2, 'creating assembly mux "%s"' % (partName))
         muxedObj = FreeCAD.ActiveDocument.addObject(
             "Part::FeaturePython", partName)
         muxedObj.Proxy = Proxy_muxAssemblyObj()
         muxedObj.ViewObject.Proxy = 0
         muxedObj.addProperty("App::PropertyString", "type")
         muxedObj.type = 'muxedAssembly'
     else:
         muxedObj = checkResult[0]
         debugPrint(2, 'updating assembly mux "%s"' % (muxedObj.Name))
     #m.Shape =Part.makeShell( App.ActiveDocument.rod_12mm_import01.Shape.Faces + App.ActiveDocument.rod_12mm_import02.Shape.Faces + App.ActiveDocument.table_import01.Shape.Faces)
     faces = []
     for obj in FreeCAD.ActiveDocument.Objects:
         if 'importPart' in obj.Content:
             debugPrint(3, '  - parsing "%s"' % (obj.Name))
             faces = faces + obj.Shape.Faces
     muxedObj.Shape = Part.makeSolid(Part.makeShell(faces))
     FreeCADGui.ActiveDocument.getObject(muxedObj.Name).Visibility = False
     FreeCAD.ActiveDocument.recompute()
Example #8
0
def closeHole(shape):
    """closeHole(shape): closes a hole in an open shape"""
    import DraftGeomUtils, Part

    # creating an edges lookup table
    lut = {}
    for face in shape.Faces:
        for edge in face.Edges:
            hc = edge.hashCode()
            if lut.has_key(hc):
                lut[hc] = lut[hc] + 1
            else:
                lut[hc] = 1
    # filter out the edges shared by more than one face
    bound = []
    for e in shape.Edges:
        if lut[e.hashCode()] == 1:
            bound.append(e)
    bound = DraftGeomUtils.sortEdges(bound)
    try:
        nface = Part.Face(Part.Wire(bound))
        shell = Part.makeShell(shape.Faces + [nface])
        solid = Part.Solid(shell)
    except:
        raise
    else:
        return solid
Example #9
0
    def execute(self, fp):
        '''Do something when doing a recomputation, this method is mandatory'''
        import math
        # Need to add code to check values make a valid Tube
        # Define six vetices for the shape
        x1 = fp.rmax * math.sin(fp.startphi)
        y1 = fp.rmax * math.cos(fp.startphi)
        x2 = fp.rmax * math.sin(fp.startphi + fp.deltaphi)
        y2 = fp.rmax * math.cos(fp.startphi + fp.deltaphi)
        v1 = FreeCAD.Vector(0, 0, 0)
        v2 = FreeCAD.Vector(x1, y1, 0)
        v3 = FreeCAD.Vector(x2, y2, 0)
        v4 = FreeCAD.Vector(0, 0, fp.z)
        v5 = FreeCAD.Vector(x1, y1, fp.z)
        v6 = FreeCAD.Vector(x2, y2, fp.z)

        # Make the wires/faces
        f1 = self.make_face3(v1, v2, v3)
        f2 = self.make_face4(v1, v3, v6, v4)
        f3 = self.make_face3(v4, v6, v5)
        f4 = self.make_face4(v5, v2, v1, v4)
        shell = Part.makeShell([f1, f2, f3, f4])
        solid = Part.makeSolid(shell)

        cyl1 = Part.makeCylinder(fp.rmax, fp.z)
        cyl2 = Part.makeCylinder(fp.rmin, fp.z)
        cyl3 = cyl1.cut(cyl2)

        tube = cyl3.cut(solid)
        fp.Shape = tube
        FreeCAD.Console.PrintMessage("Recompute GDML Tube Object \n")
Example #10
0
def muxObjectsWithKeys(objsIn, withColor=False):
    '''
    combines all the objects in objsIn into one shape,
    is able to import colors
    '''
    faces = []
    faceColors = []
    muxInfo = []  # List of keys, not used at moment...

    for obj in objsIn:
        # Save Computing time, store this before the for..enumerate loop later...
        colorFlag = (len(obj.ViewObject.DiffuseColor) < len(obj.Shape.Faces))
        shapeCol = obj.ViewObject.ShapeColor
        diffuseCol = obj.ViewObject.DiffuseColor
        tempShape = makePlacedShape(obj)

        # now start the loop with use of the stored values..(much faster)
        for i, face in enumerate(tempShape.Faces):
            faces.append(face)
            DebugMsg(A2P_DEBUG_3, "a2p MUX: i(Faces)={}\n{}\n".format(i, face))

            if withColor:
                if colorFlag:
                    faceColors.append(shapeCol)
                else:
                    faceColors.append(diffuseCol[i])

    shell = Part.makeShell(faces)
    Msg("A2P MUX: result: {}\n".format(shell))
    DebugMsg(A2P_DEBUG_3, "a2p MUX: faceColors:\n{}\n".format(
        faceColors))  # has result all faces' color values?
    if withColor:
        return muxInfo, shell, faceColors
    else:
        return muxInfo, shell
Example #11
0
def createOrUpdateSimpleAssemblyShape(doc):
    visibleImportObjects = [
        obj for obj in doc.Objects if 'importPart' in obj.Content
        and hasattr(obj, 'ViewObject') and obj.ViewObject.isVisible()
        and hasattr(obj, 'Shape') and len(obj.Shape.Faces) > 0
    ]

    if len(visibleImportObjects) == 0:
        QtGui.QMessageBox.critical(QtGui.QApplication.activeWindow(),
                                   "Cannot create SimpleAssemblyShape",
                                   "No visible ImportParts found")
        return

    sas = doc.getObject('SimpleAssemblyShape')
    if sas == None:
        sas = doc.addObject("Part::FeaturePython", "SimpleAssemblyShape")
        SimpleAssemblyShape(sas)
        #sas.ViewObject.Proxy = 0
        ViewProviderSimpleAssemblyShape(sas.ViewObject)
    faces = []

    for obj in visibleImportObjects:
        faces = faces + obj.Shape.Faces
    shell = Part.makeShell(faces)
    sas.Shape = shell
    sas.ViewObject.Visibility = False
Example #12
0
def p_polyhedron_action(p) :
    '''polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA faces EQ OSQUARE path_set ESQUARE COMMA keywordargument_list RPAREN SEMICOL
                      | polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL'''
    if printverbose: print("Polyhedron Points")
    v = []
    for i in p[6] :
        if printverbose: print(i)
        v.append(FreeCAD.Vector(float(i[0]),float(i[1]),float(i[2])))
    if printverbose:
        print(v)
        print ("Polyhedron "+p[9])
        print (p[12])
    faces_list = []
    mypolyhed = doc.addObject('Part::Feature',p[1])
    for i in p[12] :
        if printverbose: print(i)
        v2 = FreeCAD.Vector
        pp =[v2(v[k]) for k in i]
        # Add first point to end of list to close polygon
        pp.append(pp[0])
        w = Part.makePolygon(pp)
        try:
           f = Part.Face(w)
        except Exception:
            secWireList = w.Edges[:]
            f = Part.makeFilledFace(Part.__sortEdges__(secWireList))
        #f = make_face(v[int(i[0])],v[int(i[1])],v[int(i[2])])
        faces_list.append(f)
    shell=Part.makeShell(faces_list)
    solid=Part.Solid(shell).removeSplitter()
    if solid.Volume < 0:
        solid.reverse()
    mypolyhed.Shape=solid
    p[0] = [mypolyhed]
Example #13
0
    def execute(self, obj):

        radius = float(obj.Radius)
        if (radius != self.radiusvalue):
            obj.Side = radius * 4 / math.sqrt(6)
            self.radiusvalue = radius
        else:
            self.radiusvalue = float(obj.Side * math.sqrt(6) / 4)
            obj.Radius = self.radiusvalue
            radius = self.radiusvalue

        faces = []
        vertexes_bottom = horizontal_regular_polygon_vertexes(
            3, 4 * radius / 3 / math.sqrt(2), -radius / 3)
        vertexes_top = horizontal_regular_polygon_vertexes(1, 0, radius)

        for i in range(3):
            vertexes_side = [
                vertexes_bottom[i], vertexes_bottom[i + 1], vertexes_top[0],
                vertexes_bottom[i]
            ]
            polygon_side = Part.makePolygon(vertexes_side)
            faces.append(Part.Face(polygon_side))

        polygon_bottom = Part.makePolygon(vertexes_bottom)

        faces.append(Part.Face(polygon_bottom))
        shell = Part.makeShell(faces)
        solid = Part.makeSolid(shell)
        obj.Shape = solid
Example #14
0
def muxObjectsWithKeys(doc, withColor=False):
    '''
    combines all the imported shape object in doc into one shape,
    ist able to import colors
    '''
    faces = []
    faceColors = []
    muxInfo = []  # List of keys, not used at moment...

    visibleObjects = [
        obj for obj in doc.Objects if hasattr(obj, 'ViewObject')
        and obj.ViewObject.isVisible() and hasattr(obj, 'Shape')
        and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name
    ]

    for obj in visibleObjects:
        # Save Computing time, store this before the for..enumerate loop later...
        colorFlag = (len(obj.ViewObject.DiffuseColor) < len(obj.Shape.Faces))
        shapeCol = obj.ViewObject.ShapeColor
        diffuseCol = obj.ViewObject.DiffuseColor

        # now start the loop with use of the stored values..(much faster)
        for i, face in enumerate(obj.Shape.Faces):
            faces.append(face)
            if withColor:
                if colorFlag:
                    faceColors.append(shapeCol)
                else:
                    faceColors.append(diffuseCol[i])

    shell = Part.makeShell(faces)
    if withColor:
        return muxInfo, shell, faceColors
    else:
        return muxInfo, shell
def torus(segments, rings, width, height):
    """
    Function to make the faces of a torus, where every section is shifted 1/rings degrees
    :param segments: Number of segment of the torus
    :param rings: number of ring of each segment
    :param width: width in mmm of center of the torus
    :param height: height of the torus
    :return: solid of the torus
    """
    App.Console.PrintMessage("\n Draw torus based on " + str(segments) + " Segments, "
                             + str(segments * rings) + " Faces \n")
    x_base = FreeCAD.Vector(width / 2, 0, 0)
    z_base = FreeCAD.Vector(height / 2, 0, 0)

    total_faces = rings*segments
    vertex = []
    for vertex_cnt in range(total_faces):

        r_angle = vertex_cnt * (2 * math.pi * (rings-1) / (rings * segments))
        s_angle = vertex_cnt * (2 * math.pi / segments)
        rz_base = DraftVecUtils.rotate(z_base, r_angle, FreeCAD.Vector(0, 1, 0))
        vertex.append(DraftVecUtils.rotate(x_base+rz_base, s_angle))
    faces = []
    for face_cnt in range(total_faces):
        vertex_1 = vertex[face_cnt]
        vertex_2 = vertex[(face_cnt+1) % total_faces]
        vertex_3 = vertex[(face_cnt + segments) % total_faces]
        vertex_4 = vertex[(face_cnt + segments+1) % total_faces]
        faces.append(make_face(vertex_1, vertex_2, vertex_3))
        faces.append(make_face(vertex_2, vertex_3, vertex_4))

    shell = Part.makeShell(faces)
    solid: object = Part.makeSolid(shell)
    return solid
Example #16
0
def getShape(obj):
    "gets a shape from an IfcOpenShell object"
    #print "retrieving shape from obj ",obj.id
    import Part
    sh = Part.Shape()
    try:
        sh.importBrepFromString(obj.mesh.brep_data)
        #sh = Part.makeBox(2,2,2)
    except:
        print "Error: malformed shape"
        return None
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ", obj.id
        else:
            if DEBUG: print "object ", obj.id, " doesn't contain any face"
    m = obj.matrix
    mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2],
                         m[5], m[8], m[11], 0, 0, 0, 1)
    sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj
    #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull()
    #for v in sh.Vertexes: print v.Point
    return sh
Example #17
0
    def execute(self, obj):

        obj.DividedBy = int(round(obj.DividedBy))
        if obj.DividedBy <= 0:
            obj.DividedBy = 1
        if obj.DividedBy > 10:
            obj.DividedBy = 10

        radius = float(obj.Radius)
        if radius != self.radiusvalue or obj.DividedBy != self.divided_by:
            self.divided_by = obj.DividedBy
            obj.Side = geodesic_radius2side(radius, self.divided_by)
            self.radiusvalue = radius
        else:
            self.radiusvalue = geodesic_side2radius(obj.Side, self.divided_by)
            obj.Radius = self.radiusvalue
            radius = self.radiusvalue

        self.divided_by = obj.DividedBy

        z = 4 * radius / math.sqrt(10 + 2 * math.sqrt(5))
        anglefaces = 138.189685104
        r = z / 12 * math.sqrt(3) * (3 + math.sqrt(5))

        #radius of a pentagram with the same side
        radius2 = z / math.sin(36 * math.pi / 180) / 2

        #height of radius2 in the sphere
        angle = math.acos(radius2 / radius)
        height = radius * math.sin(angle)

        faces = []

        vertex_bottom = (0, 0, -radius)
        vertexes_low = horizontal_regular_polygon_vertexes(5, radius2, -height)
        vertexes_high = horizontal_regular_polygon_vertexes(
            5, radius2, height, math.pi / 5)
        vertex_top = (0, 0, radius)

        for i in range(5):
            faces = self.geodesic_divide_triangles(vertex_bottom,
                                                   vertexes_low[i + 1],
                                                   vertexes_low[i], faces)

        for i in range(5):
            faces = self.geodesic_divide_triangles(vertexes_high[i],
                                                   vertexes_low[i + 1],
                                                   vertexes_low[i], faces)
            faces = self.geodesic_divide_triangles(vertexes_low[i + 1],
                                                   vertexes_high[i + 1],
                                                   vertexes_high[i], faces)

        for i in range(5):
            faces = self.geodesic_divide_triangles(vertex_top,
                                                   vertexes_high[i],
                                                   vertexes_high[i + 1], faces)

        shell = Part.makeShell(faces)
        solid = Part.makeSolid(shell)
        obj.Shape = solid
def getShape(obj):
    "gets a shape from an IfcOpenShell object"
    #print "retrieving shape from obj ",obj.id
    import Part
    sh=Part.Shape()
    try:
        sh.importBrepFromString(obj.mesh.brep_data)
        #sh = Part.makeBox(2,2,2)
    except:
        print "Error: malformed shape"
        return None
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ",obj.id
        else:
            if DEBUG: print "object ", obj.id, " doesn't contain any face"
    m = obj.matrix
    mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9],
                         m[1], m[4], m[7], m[10],
                         m[2], m[5], m[8], m[11],
                         0, 0, 0, 1)
    sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj 
    #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull()
    #for v in sh.Vertexes: print v.Point
    return sh
Example #19
0
    def execute(self, obj):

        radius = float(obj.Radius)
        if (radius != self.radiusvalue):
            obj.Side = radius * math.sqrt(2)
            self.radiusvalue = radius
        else:
            self.radiusvalue = float(obj.Side / math.sqrt(2))
            obj.Radius = self.radiusvalue
            radius = self.radiusvalue

        faces = []
        vertexes_middle = horizontal_regular_polygon_vertexes(4, radius, 0)
        vertexes_bottom = horizontal_regular_polygon_vertexes(1, 0, -radius)
        vertexes_top = horizontal_regular_polygon_vertexes(1, 0, radius)

        for i in range(4):
            vertexes_side = [
                vertexes_middle[i], vertexes_middle[i + 1], vertexes_top[0],
                vertexes_middle[i]
            ]
            polygon_side = Part.makePolygon(vertexes_side)
            faces.append(Part.Face(polygon_side))

        for i in range(4):
            vertexes_side = [
                vertexes_middle[i], vertexes_middle[i + 1], vertexes_bottom[0],
                vertexes_middle[i]
            ]
            polygon_side = Part.makePolygon(vertexes_side)
            faces.append(Part.Face(polygon_side))

        shell = Part.makeShell(faces)
        solid = Part.makeSolid(shell)
        obj.Shape = solid
Example #20
0
def p_polyhedron_action(p) :
    '''polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA faces EQ OSQUARE path_set ESQUARE COMMA keywordargument_list RPAREN SEMICOL
                      | polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL'''
    if printverbose: print("Polyhedron Points")
    v = []
    for i in p[6] :
        if printverbose: print(i)
        v.append(FreeCAD.Vector(float(i[0]),float(i[1]),float(i[2])))
    if printverbose:
        print(v)
        print ("Polyhedron "+p[9])
        print (p[12])
    faces_list = []    
    mypolyhed = doc.addObject('Part::Feature',p[1])
    for i in p[12] :
        if printverbose: print(i)
        v2 = FreeCAD.Vector
        pp =[v2(v[k]) for k in i]
        # Add first point to end of list to close polygon
        pp.append(pp[0])
        print(pp)
        w = Part.makePolygon(pp)
        f = Part.Face(w)
        #f = make_face(v[int(i[0])],v[int(i[1])],v[int(i[2])])
        faces_list.append(f)
    shell=Part.makeShell(faces_list)
    solid=Part.Solid(shell).removeSplitter()
    if solid.Volume < 0:
        solid.reverse()
    mypolyhed.Shape=solid
    p[0] = [mypolyhed]
Example #21
0
def getShape(obj):
    "gets a shape from an IfcOpenShell object"
    import StringIO,Part
    sh=Part.Shape()
    sh.importBrep(StringIO.StringIO(obj.mesh.brep_data))
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ",obj.id
        else:
            if DEBUG: print "object ", obj.id, " doesn't contain any face"
    m = obj.matrix
    mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9],
                         m[1], m[4], m[7], m[10],
                         m[2], m[5], m[8], m[11],
                         0, 0, 0, 1)
    sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj 
    return sh
Example #22
0
def closeHole(shape):
    '''closeHole(shape): closes a hole in an open shape'''
    import DraftGeomUtils, Part
    # creating an edges lookup table
    lut = {}
    for face in shape.Faces:
        for edge in face.Edges:
            hc = edge.hashCode()
            if lut.has_key(hc):
                lut[hc] = lut[hc] + 1
            else:
                lut[hc] = 1
    # filter out the edges shared by more than one face
    bound = []
    for e in shape.Edges:
        if lut[e.hashCode()] == 1:
            bound.append(e)
    bound = DraftGeomUtils.sortEdges(bound)
    try:
        nface = Part.Face(Part.Wire(bound))
        shell = Part.makeShell(shape.Faces + [nface])
        solid = Part.Solid(shell)
    except:
        raise
    else:
        return solid
Example #23
0
def muxObjects(doc):
    'combines all the imported shape object in doc into one shape'
    faces = []
    for obj in doc.Objects:
        if 'importPart' in obj.Content:
            debugPrint(3, '  - parsing "%s"' % (obj.Name))
            faces = faces + obj.Shape.Faces
    return Part.makeShell(faces)
Example #24
0
def muxObjects( doc ):
    'combines all the imported shape object in doc into one shape'
    faces = []
    for obj in doc.Objects:
        if 'importPart' in obj.Content:
            debugPrint(3, '  - parsing "%s"' % (obj.Name))
            faces = faces + obj.Shape.Faces
    return Part.makeShell(faces)
    def makeRibs(self, fp):
        interpolate = False
        if len(fp.Shape1.Shape.Edges) != len(fp.Shape2.Shape.Edges):
            interpolate = True
        else:
            for e in range(0, len(fp.Shape1.Shape.Edges)):
                edge1 = fp.Shape1.Shape.Edges[e]
                edge2 = fp.Shape2.Shape.Edges[e]
                curve1 = edge1.Curve.toBSpline()
                curve2 = edge2.Curve.toBSpline()
                poles1 = curve1.getPoles()
                poles2 = curve2.getPoles()
                if len(poles1) != len(poles2):
                    interpolate = True
                    break

        if interpolate:
            ribs = CurvedSegment.makeRibsInterpolate(fp, 1, True, False)
        else:
            ribs = CurvedSegment.makeRibsSameShape(fp, 1, True, False)

        if (fp.makeSurface or fp.makeSolid) and len(ribs) == 1:
            rib1 = [fp.Shape1.Shape, ribs[0]]
            shape1 = CurvedShapes.makeSurfaceSolid(rib1, False)
            rib2 = [ribs[0], fp.Shape2.Shape]
            shape2 = CurvedShapes.makeSurfaceSolid(rib2, False)

            shape = Part.makeCompound([shape1, shape2])

            if fp.makeSolid:
                surfaces = shape1.Faces + shape2.Faces

                face1 = CurvedShapes.makeFace(fp.Shape1.Shape)
                if face1:
                    surfaces.append(face1)
                face2 = CurvedShapes.makeFace(fp.Shape2.Shape)
                if face2:
                    surfaces.append(face2)

                try:
                    shell = Part.makeShell(surfaces)
                    if face1 and face2:
                        try:
                            shape = Part.makeSolid(shell)
                        except Exception as ex:
                            FreeCAD.Console.PrintError(
                                "Creating solid failed ! " + ex + "\n")

                except Exception as ex:
                    FreeCAD.Console.PrintError("Creating shell failed ! " +
                                               ex + "\n")

        else:
            shape = Part.makeCompound(ribs)

        if shape:
            fp.Shape = shape
Example #26
0
    def extrudeLinearWithRotation(cls, outerWire, innerWires, vecCenter,
                                  vecNormal, angleDegrees):
        """
            Creates a 'twisted prism' by extruding, while simultaneously rotating around the extrusion vector.

            Though the signature may appear to be similar enough to extrudeLinear to merit combining them, the
            construction methods used here are different enough that they should be separate.

            At a high level, the steps followed are:
            (1) accept a set of wires
            (2) create another set of wires like this one, but which are transformed and rotated
            (3) create a ruledSurface between the sets of wires
            (4) create a shell and compute the resulting object

            :param outerWire: the outermost wire, a cad.Wire
            :param innerWires: a list of inner wires, a list of cad.Wire
            :param vecCenter: the center point about which to rotate.  the axis of rotation is defined by
                   vecNormal, located at vecCenter. ( a cad.Vector )
            :param vecNormal: a vector along which to extrude the wires ( a cad.Vector )
            :param angleDegrees: the angle to rotate through while extruding
            :return: a cad.Solid object
        """

        # from this point down we are dealing with FreeCAD wires not cad.wires
        startWires = [outerWire.wrapped] + [i.wrapped for i in innerWires]
        endWires = []
        p1 = vecCenter.wrapped
        p2 = vecCenter.add(vecNormal).wrapped

        # make translated and rotated copy of each wire
        for w in startWires:
            w2 = w.copy()
            w2.translate(vecNormal.wrapped)
            w2.rotate(p1, p2, angleDegrees)
            endWires.append(w2)

        # make a ruled surface for each set of wires
        sides = []
        for w1, w2 in zip(startWires, endWires):
            rs = FreeCADPart.makeRuledSurface(w1, w2)
            sides.append(rs)

        #make faces for the top and bottom
        startFace = FreeCADPart.Face(startWires)
        endFace = FreeCADPart.Face(endWires)
        startFace.validate()
        endFace.validate()

        #collect all the faces from the sides
        faceList = [startFace]
        for s in sides:
            faceList.extend(s.Faces)
        faceList.append(endFace)

        shell = FreeCADPart.makeShell(faceList)
        solid = FreeCADPart.makeSolid(shell)
        return Shape.cast(solid)
def mergeShells(list_of_faces_shells, flag_single = False, split_connections = []):
    faces = []
    for sh in list_of_faces_shells:
        faces.extend(sh.Faces)
    if flag_single:
        return Part.makeShell(faces)
    else:
        groups = splitIntoGroupsBySharing(faces, lambda(sh): sh.Edges, split_connections)
        return Part.makeCompound([Part.Shell(group) for group in groups])
Example #28
0
def mergeShells(list_of_faces_shells, flag_single = False, split_connections = []):
    faces = []
    for sh in list_of_faces_shells:
        faces.extend(sh.Faces)
    if flag_single:
        return Part.makeShell(faces)
    else:
        groups = splitIntoGroupsBySharing(faces, lambda sh: sh.Edges, split_connections)
        return Part.makeCompound([Part.Shell(group) for group in groups])
Example #29
0
def STLWrite(faces, filename, thickness=0):
  import triangle

  shape = None
  shells = []
  triangles = []
  for f in faces:
    r = f[0]
    A = f[1]

    facets = []
    B = triangle.triangulate(A, opts='p')
    if not 'triangles' in B:
      print "No triangles in " + B
      continue

    if thickness:
      for t in [np.transpose(np.array([list(B['vertices'][x]) + [0,1] for x in (face[0], face[1], face[2])])) for face in B['triangles']]:
        facets.extend([np.dot(r, x) for x in inflate(t, thickness=thickness)])
      for t in [np.transpose(np.array([list(A['vertices'][x]) + [0,1] for x in (edge[0], edge[1])])) for edge in A['segments']]:
        facets.extend([np.dot(r, x) for x in inflate(t, thickness=thickness, edges=True)])
    else:
      for t in [np.transpose(np.array([list(B['vertices'][x]) + [0,1] for x in (face[0], face[1], face[2])])) for face in B['triangles']]:
        facets.append(np.dot(r, t))

    triangles.extend(facets)

    if thickness:
      FREECADPATH = '/usr/lib64/freecad/lib'
      import sys
      sys.path.append(FREECADPATH)
      import FreeCAD
      import Part
      meshes = []
      for f in (np.transpose(t[0:3,:]) for t in facets):
        try:
          meshes.append(Part.Face(Part.Wire([Part.makeLine(tuple(f[x]), tuple(f[x-1])) for x in range(3)])))
        except RuntimeError:
          print "Skipping face: " + repr(f)
      shell = Part.makeShell(meshes)
      shells.append(shell)
      if shape is None:
        shape = shell
      else:
        shape = shape.fuse(shell)

  if shape:
    with open("freecad" + filename, 'wb') as fp:
      shape.exportStl("freecad" + filename)

  from stlwriter import Binary_STL_Writer
  faces = triangles

  with open(filename, 'wb') as fp:
    writer = Binary_STL_Writer(fp)
    writer.add_faces(faces)
    writer.close()
Example #30
0
def createOrUpdateSimpleAssemblyShape(doc):
    visibleImportObjects = [
        obj for obj in doc.Objects if 'importPart' in obj.Content
        and hasattr(obj, 'ViewObject') and obj.ViewObject.isVisible()
        and hasattr(obj, 'Shape') and len(obj.Shape.Faces) > 0
    ]

    if len(visibleImportObjects) == 0:
        QtGui.QMessageBox.critical(QtGui.QApplication.activeWindow(),
                                   "Cannot create SimpleAssemblyShape",
                                   "No visible ImportParts found")
        return

    sas = doc.getObject('SimpleAssemblyShape')
    if sas == None:
        sas = doc.addObject("Part::FeaturePython", "SimpleAssemblyShape")
        SimpleAssemblyShape(sas)
        #sas.ViewObject.Proxy = 0
        ViewProviderSimpleAssemblyShape(sas.ViewObject)
    faces = []
    shape_list = []
    for obj in visibleImportObjects:
        faces = faces + obj.Shape.Faces
        shape_list.append(obj.Shape)
    shell = Part.makeShell(faces)
    try:
        # solid = Part.Solid(shell)
        # solid = Part.makeCompound (shape_list)
        if a2plib.getUseSolidUnion():
            if len(shape_list) > 1:
                shape_base = shape_list[0]
                shapes = shape_list[1:]
                solid = shape_base.fuse(shapes)
            else:  #one shape only
                numShellFaces = len(shell.Faces)
                solid = Part.Solid(
                    shell
                )  # This does not work if shell includes spherical faces. FC-Bug ??
                numSolidFaces = len(solid.Faces)
                # Check, whether all faces where processed...
                if numShellFaces != numSolidFaces:
                    solid = shell  # Some faces are missing, take shell as result as workaround..
        else:
            numShellFaces = len(shell.Faces)
            solid = Part.Solid(
                shell
            )  # This does not work if shell includes spherical faces. FC-Bug ??
            numSolidFaces = len(solid.Faces)
            # Check, whether all faces where processed...
            if numShellFaces != numSolidFaces:
                solid = shell  # Some faces are missing, take shell as result as workaround..
    except:
        # keeping a shell if solid is failing
        solid = shell
    sas.Shape = solid  #shell
    sas.ViewObject.Visibility = False
Example #31
0
def getShape(obj,objid):
    "gets a shape from an IfcOpenShell object"
    #print "retrieving shape from obj ",objid
    import Part
    sh=Part.Shape()
    brep_data = None
    if IFCOPENSHELL5:
        try:
            brep_data = IfcImport.create_shape(obj)
        except:
            print "Unable to retrieve shape data"
    else:
        brep_data = obj.mesh.brep_data
    if brep_data:
        try:
            if MAKETEMPFILES:
                import tempfile
                tf = tempfile.mkstemp(suffix=".brp")[1]
                of = pyopen(tf,"wb")
                of.write(brep_data)
                of.close()
                sh = Part.read(tf)
                os.remove(tf)
            else:
                sh.importBrepFromString(brep_data)
        except:
            print "Error: malformed shape"
            return None
        else:
            if IFCOPENSHELL5 and ADDPLACEMENT:
                sh.Placement = getPlacement(getAttr(obj,"ObjectPlacement"))
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ",objid
        else:
            if DEBUG: print "object ", objid, " doesn't contain any geometry"
    if not IFCOPENSHELL5:
        m = obj.matrix
        mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9],
                             m[1], m[4], m[7], m[10],
                             m[2], m[5], m[8], m[11],
                             0, 0, 0, 1)
        sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj 
    #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull()
    #for v in sh.Vertexes: print v.Point
    return sh
Example #32
0
    def extrudeLinearWithRotation(cls, outerWire, innerWires, vecCenter, vecNormal, angleDegrees):
        """
            Creates a 'twisted prism' by extruding, while simultaneously rotating around the extrusion vector.

            Though the signature may appear to be similar enough to extrudeLinear to merit combining them, the
            construction methods used here are different enough that they should be separate.

            At a high level, the steps followed are:
            (1) accept a set of wires
            (2) create another set of wires like this one, but which are transformed and rotated
            (3) create a ruledSurface between the sets of wires
            (4) create a shell and compute the resulting object

            :param outerWire: the outermost wire, a cad.Wire
            :param innerWires: a list of inner wires, a list of cad.Wire
            :param vecCenter: the center point about which to rotate.  the axis of rotation is defined by
                   vecNormal, located at vecCenter. ( a cad.Vector )
            :param vecNormal: a vector along which to extrude the wires ( a cad.Vector )
            :param angleDegrees: the angle to rotate through while extruding
            :return: a cad.Solid object
        """

        # from this point down we are dealing with FreeCAD wires not cad.wires
        startWires = [outerWire.wrapped] + [i.wrapped for i in innerWires]
        endWires = []
        p1 = vecCenter.wrapped
        p2 = vecCenter.add(vecNormal).wrapped

        # make translated and rotated copy of each wire
        for w in startWires:
            w2 = w.copy()
            w2.translate(vecNormal.wrapped)
            w2.rotate(p1, p2, angleDegrees)
            endWires.append(w2)

        # make a ruled surface for each set of wires
        sides = []
        for w1, w2 in zip(startWires, endWires):
            rs = FreeCADPart.makeRuledSurface(w1, w2)
            sides.append(rs)

        #make faces for the top and bottom
        startFace = FreeCADPart.Face(startWires)
        endFace = FreeCADPart.Face(endWires)
        startFace.validate()
        endFace.validate()

        #collect all the faces from the sides
        faceList = [startFace]
        for s in sides:
            faceList.extend(s.Faces)
        faceList.append(endFace)

        shell = FreeCADPart.makeShell(faceList)
        solid = FreeCADPart.makeSolid(shell)
        return Shape.cast(solid)
Example #33
0
    def createGeometry(self, fp):
        Airfoils = sortAirfoils(fp.Airfoils)

        Wires = []

        for Airfoil in Airfoils:
            Wires.append(Airfoil.Shape.Wires[0])

        Faces = []

        if (not fp.Segmented):
            FreeCAD.Console.PrintMessage("Create Normal Wing-Geometry\n")
            Loft = Part.makeLoft(Wires)

            Faces = Loft.Faces
            for Face in Faces:
                Face.reverse()

            RevertedShape = Airfoils[0].Shape.copy()
            RevertedShape.reverse()
            Faces.append(RevertedShape.Faces[0])
            Faces.append(Airfoils[-1].Shape.Faces[0])

        else:
            FreeCAD.Console.PrintMessage("Create Segmented Wing-Geometry\n")
            last = None

            for Wire in Wires:

                if (last is None):
                    last = Wire
                    continue

                WingSegment = Part.makeLoft([last, Wire])

                for Face in WingSegment.Faces:
                    Face.reverse()

                Faces.extend(WingSegment.Faces)

                last = Wire

            RevertedShape = Airfoils[-1].Shape.copy()
            RevertedShape.reverse()
            Faces.append(RevertedShape.Faces[0])
            Faces.append(Airfoils[0].Shape.Faces[0])

        Shell = Part.makeShell(Faces)
        TempSolid = Part.makeSolid(Shell)
        fp.Shape = Part.makeSolid(Shell)

        if (fp.Shape.Volume < 0):
            TempShape = fp.Shape.copy()
            TempShape.reverse()
            fp.Shape = TempShape
Example #34
0
 def saveData(self, ship, trim, drafts):
     """ Write data file.
     @param ship Selected ship instance
     @param trim Trim in degrees.
     @param drafts List of drafts to be performed.
     @return True if error happens.
     """
     # Open the file
     filename = self.path + 'hydrostatics.dat'
     try:
         Output = open(filename, "w")
     except IOError:
         msg = Translator.translate("Can't write '" + filename + "' file.\n")
         FreeCAD.Console.PrintError(msg)
         return True
     # Print header
     Output.write(header)
     Output.write(" #\n")
     Output.write(" # File automatically exported by FreeCAD-Ship\n")
     Output.write(" # This file contains transversal areas data, filled with following columns:\n")
     Output.write(" #  1: Ship displacement [ton]\n")
     Output.write(" #  2: Draft [m]\n")
     Output.write(" #  3: Wetted surface [m2]\n")
     Output.write(" #  4: 1cm triming ship moment [ton m]\n")
     Output.write(" #  5: Bouyance center x coordinate\n")
     Output.write(" #  6: Floating area\n")
     Output.write(" #  7: KBt\n")
     Output.write(" #  8: BMt\n")
     Output.write(" #  9: Cb (block coefficient)\n")
     Output.write(" # 10: Cf (Floating coefficient)\n")
     Output.write(" # 11: Cm (Main frame coefficient)\n")
     Output.write(" #\n")
     Output.write(" #################################################################\n")
     # Get external faces
     faces = self.externalFaces(ship.Shape)
     if len(faces) == 0:
         msg = Translator.translate("Can't detect external faces from ship object.\n")
         FreeCAD.Console.PrintError(msg)
     else:
         faces = Part.makeShell(faces)
     # Print data
     FreeCAD.Console.PrintMessage("Computing hydrostatics...\n")
     for i in range(0,len(drafts)):
         FreeCAD.Console.PrintMessage("\t%d / %d\n" % (i+1, len(drafts)))
         draft = drafts[i]
         point = Tools.Point(ship,faces,draft,trim)
         string = "%f %f %f %f %f %f %f %f %f %f %f\n" % (point.disp, point.draft, point.wet, point.mom, point.xcb, point.farea, point.KBt, point.BMt, point.Cb, point.Cf, point.Cm)
         Output.write(string)
     # Close file
     Output.close()
     self.dataFile = filename
     msg = Translator.translate("Data saved at '" + self.dataFile + "'.\n")
     FreeCAD.Console.PrintMessage(msg)
     return False
Example #35
0
 def saveData(self, ship, trim, drafts):
     """ Write data file.
     @param ship Selected ship instance
     @param trim Trim in degrees.
     @param drafts List of drafts to be performed.
     @return True if error happens.
     """
     # Open the file
     filename = self.path + 'hydrostatics.dat'
     try:
         Output = open(filename, "w")
     except IOError:
         msg = Translator.translate("Can't write '" + filename + "' file.\n")
         FreeCAD.Console.PrintError(msg)
         return True
     # Print header
     Output.write(header)
     Output.write(" #\n")
     Output.write(" # File automatically exported by FreeCAD-Ship\n")
     Output.write(" # This file contains transversal areas data, filled with following columns:\n")
     Output.write(" #  1: Ship displacement [ton]\n")
     Output.write(" #  2: Draft [m]\n")
     Output.write(" #  3: Wetted surface [m2]\n")
     Output.write(" #  4: 1cm triming ship moment [ton m]\n")
     Output.write(" #  5: Bouyance center x coordinate\n")
     Output.write(" #  6: Floating area\n")
     Output.write(" #  7: KBt\n")
     Output.write(" #  8: BMt\n")
     Output.write(" #  9: Cb (block coefficient)\n")
     Output.write(" # 10: Cf (Floating coefficient)\n")
     Output.write(" # 11: Cm (Main frame coefficient)\n")
     Output.write(" #\n")
     Output.write(" #################################################################\n")
     # Get external faces
     faces = self.externalFaces(ship.Shape)
     if len(faces) == 0:
         msg = Translator.translate("Can't detect external faces from ship object.\n")
         FreeCAD.Console.PrintError(msg)
     else:
         faces = Part.makeShell(faces)
     # Print data
     FreeCAD.Console.PrintMessage("Computing hydrostatics...\n")
     for i in range(0,len(drafts)):
         FreeCAD.Console.PrintMessage("\t%d / %d\n" % (i+1, len(drafts)))
         draft = drafts[i]
         point = Tools.Point(ship,faces,draft,trim)
         string = "%f %f %f %f %f %f %f %f %f %f %f\n" % (point.disp, point.draft, point.wet, point.mom, point.xcb, point.farea, point.KBt, point.BMt, point.Cb, point.Cf, point.Cm)
         Output.write(string)
     # Close file
     Output.close()
     self.dataFile = filename
     msg = Translator.translate("Data saved at '" + self.dataFile + "'.\n")
     FreeCAD.Console.PrintMessage(msg)
     return False
Example #36
0
def updateThickenedSection(obj, theSketch, thickness, sides):
    """Create a cross section surface from a sketch"""
    #get the normal to the sketch
    logging.debug('-->updateThickenedSection()')
    mx = theSketch.Placement.toMatrix()
    normal = FreeCAD.Vector(mx.A31, mx.A32, mx.A33)
    normal.normalize()

    #construct faces and put them in a list
    faces = []

    sideIdx = 0
    lastSide = 0

    #loop through the wires
    logging.debug('number of wires = ' + str(len(theSketch.Shape.Wires)))
    for wx in theSketch.Shape.Wires:
        logging.debug('wire ' + str(sideIdx) + " length = " + str(wx.Length) +
                      " closed = " + str(wx.isClosed()))
        #determine symmetry and offset distance from arguments
        sym = False
        dist = thickness

        #determine the side by reading the argument in the list of side specifications
        #if there is a list supplied use it wire by wire. If we run out of values, keep using the last one
        if sideIdx >= len(sides):
            side = sides[lastSide]
        else:
            side = sides[sideIdx]
            lastSide = side

        sideIdx += 1

        if side < 0:
            dist = -dist
        elif side == 0:
            sym = True


#if  treat open and closed same
        resultFace = None
        base = None
        offset = None
        if wx.isClosed():
            resultFace = offsetClosedWire(wx, dist, sym)
        else:
            resultFace = offsetOpenWire(wx, dist, sym, normal)

        logging.debug('appending face  area = ' + str(resultFace.Area))
        faces.append(resultFace)

    sx = Part.makeShell(faces)
    obj.Shape = sx
Example #37
0
def getShape(obj,objid):
    "gets a shape from an IfcOpenShell object"
    #print "retrieving shape from obj ",objid
    import Part
    sh=Part.Shape()
    brep_data = None
    if IOC_ADVANCED:
        try:
            brep_data = IfcImport.create_shape(obj)
        except:
            print "Unable to retrieve shape data"
    else:
        brep_data = obj.mesh.brep_data
    if brep_data:
        try:
            if MAKETEMPFILES:
                import tempfile
                tf = tempfile.mkstemp(suffix=".brp")[1]
                of = pyopen(tf,"wb")
                of.write(brep_data)
                of.close()
                sh = Part.read(tf)
                os.remove(tf)
            else:
                sh.importBrepFromString(brep_data)
        except:
            print "Error: malformed shape"
            return None
    if not sh.Solids:
        # try to extract a solid shape
        if sh.Faces:
            try:
                if DEBUG: print "Malformed solid. Attempting to fix..."
                shell = Part.makeShell(sh.Faces)
                if shell:
                    solid = Part.makeSolid(shell)
                    if solid:
                        sh = solid
            except:
                if DEBUG: print "failed to retrieve solid from object ",objid
        else:
            if DEBUG: print "object ", objid, " doesn't contain any geometry"
    if not IOC_ADVANCED:
        m = obj.matrix
        mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9],
                             m[1], m[4], m[7], m[10],
                             m[2], m[5], m[8], m[11],
                             0, 0, 0, 1)
        sh.Placement = FreeCAD.Placement(mat)
    # if DEBUG: print "getting Shape from ",obj 
    #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull()
    #for v in sh.Vertexes: print v.Point
    return sh
Example #38
0
def gen_haus0(le, wi, hiall, hi, midx, wx, midy, wy):

    he = hiall
    he3 = hi

    inle = 8
    inwi = 2
    if wx == 0: wx = 0.0001
    if wy == 0: wy = 0.0001

    if midx < 0.5:
        bix = le * midx
    else:
        bix = le * (1 - midx)

    if midy < 0.5:
        biy = wi * midy
    else:
        biy = wi * (1 - midy)

    list1 = viereck(le, wi, 0)
    list2 = viereck(le, wi, he)
    list3 = viereck(
        le,
        wi,
        he3,
        le * midx - bix * wx,
        le - (le * midx + bix * wx),
        wi * midy - biy * wy,
        wi - (wi * midy + biy * wy),
    )

    poly1 = Part.makePolygon(list1)
    poly3 = Part.makePolygon(list3)
    face1 = Part.Face(poly1)
    face3 = Part.Face(poly3)
    faceListe = [face1, face3]

    for i in range(len(list1) - 1):
        liste3 = [list1[i], list1[i + 1], list2[i + 1], list2[i], list1[i]]
        poly = Part.makePolygon(liste3)
        face = Part.Face(poly)
        faceListe.append(face)

    for i in range(len(list2) - 1):
        liste3 = [list2[i], list2[i + 1], list3[i + 1], list3[i], list2[i]]
        poly = Part.makePolygon(liste3)
        face = Part.Face(poly)
        faceListe.append(face)

    myShell = Part.makeShell(faceListe)
    mySolid = Part.makeSolid(myShell)
    return mySolid
Example #39
0
def muxObjects(doc, mode=0):
    'combines all the imported shape object in doc into one shape'
    faces = []
    if mode == 1:
        objects = doc.getSelection()
    else:
        objects = doc.Objects

    for obj in objects:
        if 'importPart' in obj.Content:
            faces = faces + obj.Shape.Faces
    shell = Part.makeShell(faces)
    return shell
Example #40
0
def gen_haus0(le,wi,hiall,hi,midx,wx,midy,wy):

#	le=30
#	wi=20
	he=hiall
	he3=hi
	
	inle=8
	inwi=2
	if wx==0: wx=0.0001
	if wy==0: wy=0.0001
	
	if midx<0.5:
		bix=le*midx
	else:
		bix=le*(1-midx)

	if midy<0.5:
		biy=wi*midy
	else:
		biy=wi*(1-midy)

	list1=viereck(le,wi,0)
	list2=viereck(le,wi,he)
	# list3=viereck(le,wi,he3,inle,inwi)
	list3=viereck(le,wi,he3,
		le*midx-bix*wx,le-(le*midx+bix*wx),
		wi*midy-biy*wy,wi-(wi*midy+biy*wy),
	)
	
	poly1 = Part.makePolygon( list1)
	poly3 = Part.makePolygon( list3)
	face1 = Part.Face(poly1)
	face3 = Part.Face(poly3)
	faceListe=[face1,face3]

	for i in range(len(list1)-1):
		liste3=[list1[i],list1[i+1],list2[i+1],list2[i],list1[i]]
		poly=Part.makePolygon(liste3)
		face = Part.Face(poly)
		faceListe.append(face)

	for i in range(len(list2)-1):
		liste3=[list2[i],list2[i+1],list3[i+1],list3[i],list2[i]]
		poly=Part.makePolygon(liste3)
		face = Part.Face(poly)
		faceListe.append(face)

	myShell = Part.makeShell(faceListe)   
	mySolid = Part.makeSolid(myShell)
	return mySolid
Example #41
0
def muxObjects(doc, mode=0):
    'combines all the imported shape object in doc into one shape'
    faces = []

    if mode == 1:
        objects = doc.getSelection()
    else:
        objects = doc.Objects

    for obj in objects:
        if 'importPart' in obj.Content:
            debugPrint(3, '  - parsing "%s"' % (obj.Name))
            faces = faces + obj.Shape.Faces
    return Part.makeShell(faces)
Example #42
0
def muxObjects(doc, mode=0):
    'combine tout l objet de forme importe dans doc en une forme'
    faces = []

    if mode == 1:
        objects = doc.getSelection()
    else:
        objects = doc.Objects

    for obj in objects:
        if 'importPart' in obj.Content:
            debugPrint(3, '  - parsing "%s"' % (obj.Name))
            faces = faces + obj.Shape.Faces
    return Part.makeShell(faces)
Example #43
0
def muxObjects(doc, mode=0):
    'combines all the imported shape object in doc into one shape'
    faces = []

    if mode == 1:
        objects = doc.getSelection()
    else:
        objects = doc.Objects

    for obj in objects:
        if 'importPart' in obj.Content:
            debugPrint(3, '  - parsing "%s"' % (obj.Name))
            faces = faces + obj.Shape.Faces
    return Part.makeShell(faces)
Example #44
0
    def GetPathSolid(self, tool, cmd, pos):
        toolPath = PathGeom.edgeForCmd(cmd, pos)
        # curpos = e1.valueAt(e1.LastParameter)
        startDir = toolPath.tangentAt(0)
        startDir[2] = 0.0
        endPos = toolPath.valueAt(toolPath.LastParameter)
        endDir = toolPath.tangentAt(toolPath.LastParameter)
        try:
            startDir.normalize()
            endDir.normalize()
        except:
            return (None, endPos)
        # height = self.height

        # hack to overcome occ bugs
        rad = tool.Diameter / 2.0 - 0.001 * pos[2]
        # rad = rad + 0.001 * self.icmd
        if type(toolPath.Curve
                ) is Part.Circle and toolPath.Curve.Radius <= rad:
            rad = toolPath.Curve.Radius - 0.01 * (pos[2] + 1)
            return (None, endPos)

        # create the path shell
        toolProf = self.CreateToolProfile(tool, startDir, pos, rad)
        rotmat = Base.Matrix()
        rotmat.move(pos.negative())
        rotmat.rotateZ(math.pi)
        rotmat.move(pos)
        mirroredProf = toolProf.transformGeometry(rotmat)
        fullProf = Part.Wire([toolProf, mirroredProf])
        pathWire = Part.Wire(toolPath)
        try:
            pathShell = pathWire.makePipeShell([fullProf], False, True)
        except:
            if self.debug:
                Part.show(pathWire)
                Part.show(fullProf)
            return (None, endPos)

        # create the start cup
        startCup = toolProf.revolve(pos, Vector(0, 0, 1), -180)

        # create the end cup
        endProf = self.CreateToolProfile(tool, endDir, endPos, rad)
        endCup = endProf.revolve(endPos, Vector(0, 0, 1), 180)

        fullShell = Part.makeShell(startCup.Faces + pathShell.Faces +
                                   endCup.Faces)
        return (Part.makeSolid(fullShell).removeSplitter(), endPos)
Example #45
0
    def GetPathSolid(self, tool, cmd, pos):
        toolPath = PathGeom.edgeForCmd(cmd, pos)
        # curpos = e1.valueAt(e1.LastParameter)
        startDir = toolPath.tangentAt(0)
        startDir[2] = 0.0
        endPos = toolPath.valueAt(toolPath.LastParameter)
        endDir = toolPath.tangentAt(toolPath.LastParameter)
        try:
            startDir.normalize()
            endDir.normalize()
        except:
            return (None, endPos)
        # height = self.height

        # hack to overcome occ bugs
        rad = tool.Diameter / 2.0 - 0.001 * pos[2]
        # rad = rad + 0.001 * self.icmd
        if type(toolPath.Curve) is Part.Circle and toolPath.Curve.Radius <= rad:
            rad = toolPath.Curve.Radius - 0.01 * (pos[2] + 1)
            return (None, endPos)

        # create the path shell
        toolProf = self.CreateToolProfile(tool, startDir, pos, rad)
        rotmat = Base.Matrix()
        rotmat.move(pos.negative())
        rotmat.rotateZ(math.pi)
        rotmat.move(pos)
        mirroredProf = toolProf.transformGeometry(rotmat)
        fullProf = Part.Wire([toolProf, mirroredProf])
        pathWire = Part.Wire(toolPath)
        try:
            pathShell = pathWire.makePipeShell([fullProf], False, True)
        except:
            if self.debug:
                Part.show(pathWire)
                Part.show(fullProf)
            return (None, endPos)

        # create the start cup
        startCup = toolProf.revolve(pos, Vector(0, 0, 1), -180)

        # create the end cup
        endProf = self.CreateToolProfile(tool, endDir, endPos, rad)
        endCup = endProf.revolve(endPos, Vector(0, 0, 1), 180)

        fullShell = Part.makeShell(startCup.Faces + pathShell.Faces + endCup.Faces)
        return (Part.makeSolid(fullShell).removeSplitter(), endPos)
Example #46
0
	def accept(self):
		if not self.ship:
			return False
		if self.running:
			return
		self.save()
		draft  = self.form.minDraft.value()
		drafts = [draft]
		dDraft = (self.form.maxDraft.value() - self.form.minDraft.value())/(self.form.nDraft.value()-1)
		for i in range(1,self.form.nDraft.value()):
			draft = draft + dDraft
			drafts.append(draft)
		# Compute data
		# Get external faces
		self.loop=QtCore.QEventLoop()
		self.timer=QtCore.QTimer()
		self.timer.setSingleShot(True)
		QtCore.QObject.connect(self.timer,QtCore.SIGNAL("timeout()"),self.loop,QtCore.SLOT("quit()"))
		self.running = True
		faces = self.externalFaces(self.ship.Shape)
		if not self.running:
			return False
		if len(faces) == 0:
			msg = QtGui.QApplication.translate("ship_console", "Can't detect external faces from ship object",
                                       None,QtGui.QApplication.UnicodeUTF8)
			App.Console.PrintError(msg + '\n')
			return False
		faces = Part.makeShell(faces)
		# Get hydrostatics
		msg = QtGui.QApplication.translate("ship_console", "Computing hydrostatics",
                                   None,QtGui.QApplication.UnicodeUTF8)
		App.Console.PrintMessage(msg + '...\n')
		points = []
		for i in range(0,len(drafts)):
			App.Console.PrintMessage("\t%d / %d\n" % (i+1, len(drafts)))
			draft = drafts[i]
			point = Tools.Point(self.ship,faces,draft,self.form.trim.value())
			points.append(point)
			self.timer.start(0.0)
			self.loop.exec_()
			if(not self.running):
				break
		PlotAux.Plot(self.ship, self.form.trim.value(), points)
		return True
Example #47
0
def p_polyhedron_action(p) :
    'polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL'
    print "Polyhedron Points"
    v = []
    for i in p[6] :
        print i
        v.append(FreeCAD.Vector(float(i[0]),float(i[1]),float(i[2])))
    print v
    print "Polyhedron triangles"
    print p[12]
    faces_list = []    
    mypolyhed = doc.addObject('Part::Feature',p[1])
    for i in p[12] :
        print i
        f = make_face(v[int(i[0])],v[int(i[1])],v[int(i[2])])
        faces_list.append(f)
    shell=Part.makeShell(faces_list)
    mypolyhed.Shape=Part.Solid(shell) 
    p[0] = [mypolyhed]
Example #48
0
	def execute(self, fp):
		# Define six vetices for the shape
		v1 = FreeCAD.Vector(0,0,0)
		v2 = FreeCAD.Vector(fp.Length,0,0)
		v3 = FreeCAD.Vector(0,fp.Width,0)
		v4 = FreeCAD.Vector(fp.Length,fp.Width,0)
		v5 = FreeCAD.Vector(fp.Length/2,fp.Width/2,fp.Height/2)
		v6 = FreeCAD.Vector(fp.Length/2,fp.Width/2,-fp.Height/2)
		
		# Make the wires/faces
		f1 = self.make_face(v2,v1,v5)
		f2 = self.make_face(v4,v2,v5)
		f3 = self.make_face(v3,v4,v5)
		f4 = self.make_face(v1,v3,v5)
		f5 = self.make_face(v1,v2,v6)
		f6 = self.make_face(v2,v4,v6)
		f7 = self.make_face(v4,v3,v6)
		f8 = self.make_face(v3,v1,v6)
		shell=Part.makeShell([f1,f2,f3,f4,f5,f6,f7,f8])
		solid=Part.makeSolid(shell)
		fp.Shape = solid
def gen_pyramidenstumpf(count=8,size_bottom = 60, size_top=20, height=60):

	list1=vieleck(count,size_bottom,0)
	list2=vieleck(count,size_top,height)
	
	poly1 = Part.makePolygon( list1)
	poly2 = Part.makePolygon( list2)
	face1 = Part.Face(poly1)
	face2 = Part.Face(poly2)
	faceListe=[face1,face2]
	
	for i in range(len(list1)-1):
		liste3=[list1[i],list1[i+1],list2[i+1],list2[i],list1[i]]
		poly=Part.makePolygon(liste3)
		face = Part.Face(poly)
		faceListe.append(face)
	#	say(i);say(poly);say(faceListe)
	
	myShell = Part.makeShell(faceListe)   
	mySolid = Part.makeSolid(myShell)
	return mySolid
Example #50
0
def export_step(nurbs_idx, nurbs_pts, refinement_level, input_file_name, output_file_name, nonchanging_file_name, allowed_domains_file_name):

	# generate and get faces
	faceHolder = get_faces_from_points(nurbs_idx, nurbs_pts)

	# create shell from face list, create solid from shell
	shellHolder = Part.makeShell(faceHolder)
	solidHolder = Part.makeSolid(shellHolder)
	Part.show(solidHolder)

	# here, the part is brought into the right coordinate system 
	# (something somewhere messes it up, but its too late to get into that mess) Laavaa!
	reorient_object(input_file_name, output_file_name, refinement_level)

	# process allowed domains
	process_allowed_domains(allowed_domains_file_name, output_file_name, refinement_level)

	# process non-changing domains
	process_nonchanging_domains(nonchanging_file_name, output_file_name, refinement_level)

	print "Export done."
Example #51
0
def meshToShape(obj,mark=True):
    '''meshToShape(object,[mark]): turns a mesh into a shape, joining coplanar facets. If
    mark is True (default), non-solid objects will be marked in red'''

    name = obj.Name
    import Part,MeshPart
    from draftlibs import fcgeo
    if "Mesh" in obj.PropertiesList:
        faces = []	
        mesh = obj.Mesh
        plac = obj.Placement
        segments = mesh.getPlanes(0.001) # use rather strict tolerance here
        print len(segments)," segments ",segments
        for i in segments:
            print "treating",segments.index(i),i
            if len(i) > 0:
                wires = MeshPart.wireFromSegment(mesh, i)
                print "wire done"
                print wires
                if wires:
                    faces.append(makeFace(wires))
                print "done facing"
            print "faces",faces

        try:
            se = Part.makeShell(faces)
            solid = Part.Solid(se)
        except:
            pass
        else:
            if solid.isClosed():
                FreeCAD.ActiveDocument.removeObject(name)
            newobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
            newobj.Shape = solid
            newobj.Placement = plac
            if not solid.isClosed():
                if mark:
                    newobj.ViewObject.ShapeColor = (1.0,0.0,0.0,1.0)
            return newobj
    return None
Example #52
0
File: Wing.py Project: anso0/fcwing
def makeWing(Airfoils):
	a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Wing")
	
	Airfoils = sortAirfoils(Airfoils)
	
	Wires = []
	
	for Airfoil in Airfoils:
		Wires.append(Airfoil.Shape.Wires[0])


	Loft = Part.makeLoft(Wires)
	
	Faces = Loft.Faces
	for Face in Faces:
		Face.reverse()
	
	RevertedShape = Airfoils[0].Shape.copy()
	RevertedShape.reverse()
	Faces.append(RevertedShape.Faces[0])
	Faces.append(Airfoils[-1].Shape.Faces[0])
	
	Shell = Part.makeShell(Faces)
	TempSolid = Part.makeSolid(Shell)			
	a.Shape = Part.makeSolid(Shell)
	
	Wing(a)
	
	ViewProviderBox(a.ViewObject)
	a.Components = Airfoils
	
	if(a.Shape.Volume < 0):
		TempShape = a.Shape.copy()
		TempShape.reverse()
		a.Shape = TempShape
	
	FreeCAD.ActiveDocument.recompute()
	return a
 def Activated(self):
     #first check if assembly mux part already existings
     checkResult = [ obj  for obj in FreeCAD.ActiveDocument.Objects 
                     if hasattr(obj, 'type') and obj.type == 'muxedAssembly' ]
     if len(checkResult) == 0:
         partName = 'muxedAssembly'
         debugPrint(2, 'creating assembly mux "%s"' % (partName))
         muxedObj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",partName)
         muxedObj.Proxy = Proxy_muxAssemblyObj()
         muxedObj.ViewObject.Proxy = 0
         muxedObj.addProperty("App::PropertyString","type")
         muxedObj.type = 'muxedAssembly'
     else:
         muxedObj = checkResult[0]
         debugPrint(2, 'updating assembly mux "%s"' % (muxedObj.Name))
     #m.Shape =Part.makeShell( App.ActiveDocument.rod_12mm_import01.Shape.Faces + App.ActiveDocument.rod_12mm_import02.Shape.Faces + App.ActiveDocument.table_import01.Shape.Faces)
     faces = []
     for obj in FreeCAD.ActiveDocument.Objects:
         if 'importPart' in obj.Content:
             debugPrint(3, '  - parsing "%s"' % (obj.Name))
             faces = faces + obj.Shape.Faces
     muxedObj.Shape =  Part.makeSolid(Part.makeShell(faces))
     FreeCADGui.ActiveDocument.getObject(muxedObj.Name).Visibility = False
     FreeCAD.ActiveDocument.recompute()
Example #54
0
def p_polyhedron_action(p) :
    '''polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA faces EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL
                      | polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL'''
    if printverbose: print "Polyhedron Points"
    v = []
    for i in p[6] :
        if printverbose: print i
        v.append(FreeCAD.Vector(float(i[0]),float(i[1]),float(i[2])))
    if printverbose:
        print v
        print "Polyhedron triangles"
        print p[12]
    faces_list = []    
    mypolyhed = doc.addObject('Part::Feature',p[1])
    for i in p[12] :
        if printverbose: print i
        f = make_face(v[int(i[0])],v[int(i[1])],v[int(i[2])])
        faces_list.append(f)
    shell=Part.makeShell(faces_list)
    solid=Part.Solid(shell).removeSplitter()
    if solid.Volume < 0:
        solid.reverse()
    mypolyhed.Shape=solid
    p[0] = [mypolyhed]
Example #55
0
    def execute(self, obj):
        import Part  # math #DraftGeomUtils
        output = ""
        toolLoad = PathUtils.getLastToolLoad(obj)
        if toolLoad is None or toolLoad.ToolNumber == 0:
            self.vertFeed = 100
            self.horizFeed = 100
            self.radius = 0.25
            obj.ToolNumber = 0
            obj.ToolDescription = "UNDEFINED"
        else:
            self.vertFeed = toolLoad.VertFeed.Value
            self.horizFeed = toolLoad.HorizFeed.Value
            tool = PathUtils.getTool(obj, toolLoad.ToolNumber)
            if tool.Diameter == 0:
                self.radius = 0.25
            else:
                self.radius = tool.Diameter/2
            obj.ToolNumber = toolLoad.ToolNumber
            obj.ToolDescription = toolLoad.Name

        if obj.UserLabel == "":
            obj.Label = obj.Name + " (" + obj.ToolDescription + ")"
        else:
            obj.Label = obj.UserLabel + " (" + obj.ToolDescription + ")"


        if obj.Base:
            hfaces = []
            vfaces = []
            wires = []

            for b in obj.Base:
                for sub in b[1]:
                    # we only consider the outer wire if this is a Face
                    # Horizontal and vertical faces are handled differently
                    shape = getattr(b[0].Shape, sub)
                    if numpy.isclose(shape.normalAt(0, 0).z, 1):  # horizontal face
                        hfaces.append(shape)

                    elif numpy.isclose(shape.normalAt(0, 0).z, 0):  # vertical face
                        vfaces.append(shape)
                    else:
                        FreeCAD.Console.PrintError(translate("Path", "Face doesn't appear to be parallel or perpendicular to the XY plane. No path will be generated for: \n"))
                        FreeCAD.Console.PrintError(b[0].Name + "." + sub + "\n")
            for h in hfaces:
                wires.append(h.OuterWire)

            tempshell = Part.makeShell(vfaces)
            slices = tempshell.slice(FreeCAD.Base.Vector(0, 0, 1), tempshell.CenterOfMass.z )

            wires = wires + slices

            for wire in wires:
                if obj.Algorithm == "OCC Native":
                    output += self._buildPathOCC(obj, wire)
                else:
                    try:
                        import area
                    except:
                        FreeCAD.Console.PrintError(translate("Path", "libarea needs to be installed for this command to work.\n"))
                        return
                    edgelist = wire.Edges
                    edgelist = Part.__sortEdges__(edgelist)
                    output += self._buildPathLibarea(obj, edgelist)

        if obj.Active:
            path = Path.Path(output)
            obj.Path = path
            obj.ViewObject.Visibility = True

        else:
            path = Path.Path("(inactive operation)")
            obj.Path = path
            obj.ViewObject.Visibility = False
Example #56
0
 def fromFaces(name,faces):
     shell = Part.makeShell(faces)
     shape = Part.makeSolid(shell)
     return Piece(name,shape)
    def accept(self):
        if not self.ship:
            return False
        if self.running:
            return
        self.save()

        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")
        form.minDraft = self.widget(QtGui.QLineEdit, "MinDraft")
        form.maxDraft = self.widget(QtGui.QLineEdit, "MaxDraft")
        form.nDraft = self.widget(QtGui.QSpinBox, "NDraft")

        trim = Units.Quantity(form.trim.text()).getValueAs('deg').Value
        min_draft = Units.Quantity(form.minDraft.text()).getValueAs('m').Value
        max_draft = Units.Quantity(form.maxDraft.text()).getValueAs('m').Value
        n_draft = form.nDraft.value()

        draft = min_draft
        drafts = [draft]
        dDraft = (max_draft - min_draft) / (n_draft - 1)
        for i in range(1, n_draft):
            draft = draft + dDraft
            drafts.append(draft)

        # Compute data
        # Get external faces
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer,
                               QtCore.SIGNAL("timeout()"),
                               self.loop,
                               QtCore.SLOT("quit()"))
        self.running = True
        faces = self.externalFaces(self.ship.Shape)
        if not self.running:
            return False
        if len(faces) == 0:
            msg = QtGui.QApplication.translate(
                "ship_console",
                "Failure detecting external faces from the ship object",
                None,
                QtGui.QApplication.UnicodeUTF8)
            App.Console.PrintError(msg + '\n')
            return False
        faces = Part.makeShell(faces)
        # Get the hydrostatics
        msg = QtGui.QApplication.translate(
            "ship_console",
            "Computing hydrostatics",
            None,
            QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintMessage(msg + '...\n')
        points = []
        for i in range(len(drafts)):
            App.Console.PrintMessage("\t{} / {}\n".format(i + 1, len(drafts)))
            draft = drafts[i]
            point = Tools.Point(self.ship,
                                faces,
                                draft,
                                trim)
            points.append(point)
            self.timer.start(0.0)
            self.loop.exec_()
            if(not self.running):
                break
        PlotAux.Plot(self.ship, trim, points)
        return True
Example #58
0
def cara4ptos(pto1, pto2, pto3, pto4):
    tr1 = Part.Face(Part.makePolygon([pto1, pto2, pto3, pto1]))
    tr2 = Part.Face(Part.makePolygon([pto1, pto3, pto4, pto1]))
    cara = Part.makeShell([tr1, tr2])
    return cara
Example #59
0
 def makeShell(cls, listOfFaces):
     return Shell(FreeCADPart.makeShell([i.obj for i in listOfFaces]))