Example #1
0
def mergeSolids(list_of_solids_compsolids,
                flag_single=False,
                split_connections=[],
                bool_compsolid=False):
    """mergeSolids(list_of_solids, flag_single = False): merges touching solids that share
    faces. If flag_single is True, it is assumed that all solids touch, and output is a
    single solid. If flag_single is False, the output is a compound containing all
    resulting solids.

    Note. CompSolids are treated as lists of solids - i.e., merged into solids."""

    solids = []
    for sh in list_of_solids_compsolids:
        solids.extend(sh.Solids)
    if flag_single:
        cs = Part.CompSolid(solids)
        return cs if bool_compsolid else Part.makeSolid(cs)
    else:
        if len(solids) == 0:
            return Part.Compound([])
        groups = splitIntoGroupsBySharing(solids, lambda sh: sh.Faces,
                                          split_connections)
        if bool_compsolid:
            merged_solids = [Part.CompSolid(group) for group in groups]
        else:
            merged_solids = [
                Part.makeSolid(Part.CompSolid(group)) for group in groups
            ]
        return Part.makeCompound(merged_solids)
Example #2
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 #3
0
def svmesh_to_solid(verts,
                    faces,
                    precision=1e-6,
                    remove_splitter=True,
                    method=FCMESH):
    """
    input:
        verts: list of 3element iterables, [vector, vector...]
        faces: list of lists of face indices
        precision: a conversion factor defined in makeShapeFromMesh (FreeCAD)
        remove_splitter: default True, removes duplicate geometry (edges)
    output:
        a FreeCAD solid

    """
    if method == FCMESH:
        tri_faces = ensure_triangles(verts, faces, True)
        faces_t = [[verts[c] for c in f] for f in tri_faces]
        mesh = Mesh.Mesh(faces_t)
        shape = Part.Shape()
        shape.makeShapeFromMesh(mesh.Topology, precision)

        if remove_splitter:
            # may slow it down, or be totally necessary
            shape = shape.removeSplitter()

        return Part.makeSolid(shape)
    elif method == BMESH:
        fc_faces = []
        for face in faces:
            face_i = list(face) + [face[0]]
            face_verts = [Base.Vector(verts[i]) for i in face_i]
            wire = Part.makePolygon(face_verts)
            wire.fixTolerance(precision)
            try:
                fc_face = Part.Face(wire)
                #fc_face = Part.makeFilledFace(wire.Edges)
            except Exception as e:
                print(f"Face idxs: {face_i}, verts: {face_verts}")
                raise Exception("Maybe face is not planar?") from e
            fc_faces.append(fc_face)
        shell = Part.makeShell(fc_faces)
        solid = Part.makeSolid(shell)
        if remove_splitter:
            solid = solid.removeSplitter()
        return solid
    else:
        raise Exception("Unsupported method")
def process_nonchanging_domains(nonchanging_file_name, output_file_name, refinement_level):
	if len(nonchanging_file_name) != 0:
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")
		
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
Example #5
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 #6
0
def design_plate(span_length, base_length, base_width, wall_t, base_thickness,
                 folder_path):
    bolt_d = file("./bolts/hole_params.csv", "r")
    bolt_data = csv.reader(bolt_d)
    for row in bolt_data:
        bolt_diam = float(row[0])
        bolt_spacing = float(row[4])
        bolt_fixture = float(row[5])
    x = (span_length / 2) + (base_length / 2)
    y = (0.5 * wall_t) + (4.8 * wall_t)
    x2 = 0.6 * bolt_spacing
    z = base_thickness
    points = []
    points.append(Base.Vector(x - x2, y, z))
    points.append(Base.Vector(x + x2, y, z))
    points.append(Base.Vector(x + x2, -y, z))
    points.append(Base.Vector(x - x2, -y, z))
    edges = []
    for i in range(0, 3):
        edges.append(Part.makeLine(points[i], points[i + 1]))
    edges.append(Part.makeLine(points[3], points[0]))
    w = Part.Wire(edges)
    f = Part.Face(w)
    P = f.extrude(Base.Vector(0, 0, bolt_fixture))
    plate = Part.makeSolid(P)
    cylinders = bolt_holes(wall_t, span_length, base_length, base_width,
                           base_thickness + bolt_fixture)
    for i in cylinders:
        plate = plate.cut(i)
    plate1 = plate.mirror(Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
    cpd = Part.makeCompound([plate1, plate])
    cpd.exportStep(folder_path + "/flange.stp")
    return bolt_fixture
 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()
def read_in_stl_files_and_resave_as_single_step(read_folder, write_folder):
    try:
        os.mkdir(write_folder)
    except:
        pass
    list_of_solid_parts = []
    for file in os.listdir(read_folder):
        if file.endswith(".stl"):
            #print('reading in ' ,os.path.join(read_folder, file))

            # only for stp model =Part.Shape()
            # model.read(os.path.join("stl_files", file))

            #obj = Mesh.open(os.path.join(read_folder, file))
            obj = Mesh.Mesh(os.path.join(read_folder, file))
            #print('opening ' ,os.path.join(read_folder, file))
            #Mesh.export(obj,os.path.join(write_folder,file))

            shape = Part.Shape()
            shape.makeShapeFromMesh(obj.Topology, 0.05)
            solid = Part.makeSolid(shape)
            list_of_solid_parts.append(solid)

    compound_obj = Part.makeCompound(list_of_solid_parts)
    compound_obj.exportStep(os.path.join(write_folder, file))
Example #9
0
        def process(self):
            if not any(socket.is_linked for socket in self.outputs):
                return

            solids_in = self.inputs[0].sv_get(deepcopy=False)
            offsets = self.inputs[1].sv_get(deepcopy=False)[0]

            solids = []
            for solid_base, offset in zip(*mlr([solids_in, offsets])):

                shape = solid_base.makeOffsetShape(offset,
                                                   self.tolerance,
                                                   inter=self.intersection,
                                                   join=self['join_type'])
                if self.refine_solid:
                    shape = shape.removeSplitter()
                try:
                    valid = shape.isValid()
                    solid = Part.makeSolid(shape)
                except Exception as e:
                    self.warning("Shape is not valid: %s: %s", shape, e)
                    continue

                solids.append(solid)

            self.outputs['Solid'].sv_set(solids)
Example #10
0
        def process(self):
            if not any(socket.is_linked for socket in self.outputs):
                return

            verts_s = self.inputs[0].sv_get(deepcopy=False)
            faces_s = self.inputs[1].sv_get(deepcopy=False)
            solids = []
            faces = []
            for verts, faces in zip(*mlr([verts_s, faces_s])):
                tri_faces = ensure_triangles(verts, faces, True)
                faces_t = []
                for f in tri_faces:
                    faces_t.append([verts[c] for c in f])

                mesh = Mesh.Mesh(faces_t)
                shape = Part.Shape()
                shape.makeShapeFromMesh(mesh.Topology, self.precision)
                if self.refine_solid:
                    shape = shape.removeSplitter()
                solid = Part.makeSolid(shape)

                solids.append(solid)


            self.outputs['Solid'].sv_set(solids)
Example #11
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 #12
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 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
def process_nonchanging_domains(nonchanging_file_name, output_file_name):
    if len(nonchanging_file_name) != 0:

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()
        len_original = len(__objs_original__)
        print "Loading non-changing component..."
        Import.insert(nonchanging_file_name, "tmp")

        # get objects
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create fusion object
        FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

        # add objs to FusionTool
        FreeCAD.getDocument(
            "tmp").FusionTool.Shapes = __objs__[0:len(__objs__)]

        # compute
        FreeCAD.getDocument("tmp").recompute()

        # make one solid
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove all except the last
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        print "Exporting BOOLEANED file..."
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.export(__objs__, output_file_name + "_BOOLEANED.step")
        print "Output file " + output_file_name + "_BOOLEANED.step" + " exported."
Example #15
0
def des_cyl(bolt_diam, bolt_depth, pos, cylinders):
    cylinda = Part.makeCylinder(bolt_diam / 2, bolt_depth, pos,
                                Base.Vector(0, 0, 1), 360)
    cylinda = Part.makeSolid(cylinda)
    cylinders.append(cylinda)
    cylinda = cylinda.mirror(Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
    cylinders.append(cylinda)
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 #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
Example #18
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 #19
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 #20
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 process_nonchanging_domains(nonchanging_file_name, output_file_name):
	if len(nonchanging_file_name) != 0:

		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()
		len_original =len(__objs_original__)
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
Example #22
0
def fragment(key_list, port_dict, fused_object, port_number, outer_casing_prefix, q) :
	"""Fragments a port into parts: outside fused_object, in common with the fused_object and inside the fused_object. 
	Discards the inside part (ie the part that would intersect with plasma)
	Puts the new port structures in a queue for removal by its caller"""

	for port in key_list :
		#PROBLEM: NBPort1 is in NBPort10,11,12 ... 
		if ("NBPort" + port_number) in port and not port.startswith(outer_casing_prefix) : 


			####### UNTESTED PART BEGINS ###########
			#REMOVE FALSE POSITIVES ie NBPort1 is IN NBPort12, NBPort16 etc..
			port_digits = 0
			for c in port :
				if c.isdigit() :
					port_digits += 1
			port_number_digits = len(port_number)
						
			if port_number_digits != port_digits :
				#eg iw_NBPort12 and iw_NBPort1
				#eg iw_NBPort10 and iw_NBPort106
				continue
			#else: we have found a correct match

			######### UNTESTED PART ENDS ###########

			#print "found", port, "for cutting"
			pieces = SplitAPI.booleanFragments([fused_object, port_dict[port]], "Standard")
			downgraded_pieces = pieces.Solids
			
			for solid in downgraded_pieces :
				if solid.common(port_dict[port]).Volume == 0 :
					downgraded_pieces.remove(solid)
			
			#find the order of the remaining 3
			positions = {magnitude(downgraded_pieces[0].CenterOfMass) : downgraded_pieces[0], \
						magnitude(downgraded_pieces[1].CenterOfMass) : downgraded_pieces[1], \
						magnitude(downgraded_pieces[2].CenterOfMass) : downgraded_pieces[2] }
			
			mini = magnitude(downgraded_pieces[0].CenterOfMass)
			for val in positions :
				if val < mini :
					mini = val
			del positions[mini]

			remaining_list = []
			for val in positions :
				remaining_list.append(positions[val])

			if len(remaining_list) != 2 :
				print "********** WARNING in" + port + " ************"
				print "Expected 2 items remaining after removing minimum fragment"
				print "Recieved", len(remaining_list)

			new_port = Part.makeSolid(remaining_list[0].fuse(remaining_list[1]))
			print port, "completed"
			
			q.put( (port, new_port) )
    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 #24
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 #25
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 #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 process_allowed_domains(allowed_domains_file_name, output_file_name, refinement_level):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# get bounding box of the allowed domains
		# NOTE: ASSUMING ALLOWED DOMAINS ARE ALL FUSED IN ONE OBJECT.
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		print __objs__

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
    def execute(self, slopedPlanes):
        '''execute(self, slopedPlanes)
        Builds the shape of the slopedPlanes object.'''

        # print('execute')

        sketch = slopedPlanes.Base
        shape = sketch.Shape.copy()
        shape.Placement = P()

        self.declareSlopedPlanes(slopedPlanes)

        # print(self.OnChanged, self.slopeList)

        if self.OnChanged and self.slopeList:
            # print('A ', self.OnChanged)

            faceList = self.reProcessFaces(slopedPlanes)
            pyFaceListNew = self.Pyth

        else:
            # print('B ', self.OnChanged)

            face = Part.makeFace(shape.Wires, slopedPlanes.FaceMaker)
            fList = face.Faces
            faceList, pyFaceListNew = self.processFaces(slopedPlanes, fList)
            self.Pyth = pyFaceListNew

        # print('pyFaceListNew ', pyFaceListNew)

        self.OnChanged = False

        endShape =\
            self.makeShells(slopedPlanes, pyFaceListNew)

        if slopedPlanes.Group:
            # print('Group')
            endShape = self.groupping(slopedPlanes, endShape)

        if slopedPlanes.Thickness:
            # print('Thickness')
            endShape = self.fattening(slopedPlanes, faceList, endShape)

        if not slopedPlanes.Complement:
            endShape.complement()

        endShape.removeInternalWires(True)

        if slopedPlanes.Solid:
            endShape = Part.makeSolid(endShape)

        # print(endShape.Placement)

        slopedPlanes.Shape = endShape
Example #29
0
def process_allowed_domains(allowed_domains_file_name, output_file_name):
    if len(allowed_domains_file_name) != 0:
        print "Checking allowed domains..."
        # take the intersection of allowed domains
        # read in step file for allowed domains

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()

        Import.insert(allowed_domains_file_name, "tmp")
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create mega BB object
        create_mega_bounding_box_object()

        # cut out allowed domains from mega BB object
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
        FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument(
            "tmp").Objects[-3]
        FreeCAD.getDocument("tmp").recompute()
        #Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # cut out not-allowed parts
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
        FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument(
            "tmp").Objects[0]
        FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").recompute()
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove everything except the last cut-object
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        if len(__objs__) > 1:
            # create a fuse object and union all "Common"s
            FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
            FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1:len(__objs__)]
            print FreeCAD.getDocument("tmp").Fuse.Shapes
            FreeCAD.getDocument("tmp").recompute()

            # remove "Commons"s
            for i in range(0, len(__objs__)):
                FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
Example #30
0
 def SetupOperation(self, itool):
     self.operation = self.activeOps[itool]
     self.tool = self.operation.ToolController.Tool
     toolProf = self.CreateToolProfile(self.tool, Vector(0,1,0), Vector(0,0,0), self.tool.Diameter / 2.0)
     self.cutTool.Shape = Part.makeSolid(toolProf.revolve(Vector(0,0,0), Vector(0,0,1)))
     self.cutTool.ViewObject.show()
     self.voxSim.SetCurrentTool(self.tool)
     self.icmd = 0
     self.curpos = FreeCAD.Placement(self.initialPos, self.stdrot)
     #self.cutTool.Placement = FreeCAD.Placement(self.curpos, self.stdrot)
     self.cutTool.Placement = self.curpos
Example #31
0
def make_solid(geofile_list, directory, total, q):
	"""Takes a file to read in, the directory in which it is found, and the dictionary into which to put it"""
	global count
	for geofile in geofile_list :
		print "*** Creating solid from file: " + geofile + " (" + str(count + 1) + "/" + str(total) + ") ***"
		count += 1
		obj = Mesh.Mesh(os.path.join(directory, geofile))
		shape = Part.Shape()
		shape.makeShapeFromMesh(obj.Topology, 0.05)
		solid = Part.makeSolid(shape)

		q.put( (("").join(geofile.split(".")[:-1]) , solid) )
Example #32
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 #33
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 #34
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 #35
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 mergeSolids(list_of_solids_compsolids, flag_single = False, split_connections = [], bool_compsolid = False):
    """mergeSolids(list_of_solids, flag_single = False): merges touching solids that share
    faces. If flag_single is True, it is assumed that all solids touch, and output is a
    single solid. If flag_single is False, the output is a compound containing all
    resulting solids.

    Note. CompSolids are treated as lists of solids - i.e., merged into solids."""

    solids = []
    for sh in list_of_solids_compsolids:
        solids.extend(sh.Solids)
    if flag_single:
        cs = Part.CompSolid(solids)
        return cs if bool_compsolid else Part.makeSolid(cs)
    else:
        if len(solids)==0:
            return Part.Compound([])
        groups = splitIntoGroupsBySharing(solids, lambda(sh): sh.Faces, split_connections)
        if bool_compsolid:
            merged_solids = [Part.CompSolid(group) for group in groups]
        else:
            merged_solids = [Part.makeSolid(Part.CompSolid(group)) for group in groups]
        return Part.makeCompound(merged_solids)
def process_allowed_domains(allowed_domains_file_name, output_file_name):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		
		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()

		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
Example #38
0
        def process(self):
            if not any(socket.is_linked for socket in self.outputs):
                return

            files = self.inputs[0].sv_get()[0]

            solids = []
            for f in files:
                shape = Part.Shape()
                shape.importBrep(f)
                solid = Part.makeSolid(shape)
                solids.append(solid)

            self.outputs['Solid'].sv_set(solids)
Example #39
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 #40
0
    def svmesh_to_solid(verts, faces, precision):
        """
        input: verts / faces / precision
        output a Solid (FreeCad type)

        this utility function is included in the node, to keep this code in the same place
        """
        
        tri_faces = ensure_triangles(verts, faces, True)
        faces_t = [[verts[c] for c in f] for f in tri_faces]
        mesh = Mesh.Mesh(faces_t)
        shape = Part.Shape()
        shape.makeShapeFromMesh(mesh.Topology, precision)
        shape = shape.removeSplitter()  # may slow it down, or be totally necessary
        return Part.makeSolid(shape)
Example #41
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 #42
0
 def make_solid(self, surfaces):
     faces = [face.face for face in surfaces]
     shell = Part.makeShell(faces)
     shape = Part.makeSolid(shell)
     ok = shape.isValid()
     if not ok:
         self.debug("Constructed solid is not valid, will try to fix it")
         if self.validate:
             ok = shape.fix(self.tolerance, self.tolerance, self.tolerance)
             if not ok:
                 raise Exception(
                     "Constructed Solid object is not valid and can't be fixed automatically"
                 )
     if self.check_closed:
         if not shape.isClosed():
             raise Exception("Constructed Solid object is not closed")
     return shape
Example #43
0
    def SetupOperation(self, itool):
        self.operation = self.activeOps[itool]
        try:
            self.tool = PathDressup.toolController(self.operation).Tool
        except:
            self.tool = None

        # if hasattr(self.operation, "ToolController"):
        #     self.tool = self.operation.ToolController.Tool
        if (self.tool is not None):
            toolProf = self.CreateToolProfile(self.tool, Vector(0, 1, 0), Vector(0, 0, 0), self.tool.Diameter / 2.0)
            self.cutTool.Shape = Part.makeSolid(toolProf.revolve(Vector(0, 0, 0), Vector(0, 0, 1)))
            self.cutTool.ViewObject.show()
            self.voxSim.SetCurrentTool(self.tool)
        self.icmd = 0
        self.curpos = FreeCAD.Placement(self.initialPos, self.stdrot)
        # self.cutTool.Placement = FreeCAD.Placement(self.curpos, self.stdrot)
        self.cutTool.Placement = self.curpos
Example #44
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 #46
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."
 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 #48
0
 def fromFaces(name,faces):
     shell = Part.makeShell(faces)
     shape = Part.makeSolid(shell)
     return Piece(name,shape)