예제 #1
0
def write_stl_file(a_shape,
                   filename,
                   mode="ascii",
                   linear_deflection=0.9,
                   angular_deflection=0.5):
    """ export the shape to a STL file
    Be careful, the shape first need to be explicitely meshed using BRepMesh_IncrementalMesh
    a_shape: the topods_shape to export
    filename: the filename
    mode: optional, "ascii" by default. Can either be "binary"
    linear_deflection: optional, default to 0.001. Lower, more occurate mesh
    angular_deflection: optional, default to 0.5. Lower, more accurate_mesh
    """
    assert not a_shape.IsNull()
    assert mode in ["ascii", "binary"]
    if os.path.isfile(filename):
        print("Warning: %s file already exists and will be replaced" %
              filename)
    # first mesh the shape
    mesh = BRepMesh_IncrementalMesh(a_shape, linear_deflection, False,
                                    angular_deflection, True)
    #mesh.SetDeflection(0.05)
    mesh.Perform()
    assert mesh.IsDone()

    stl_exporter = StlAPI_Writer()
    if mode == "ascii":
        stl_exporter.SetASCIIMode(True)
    else:  # binary, just set the ASCII flag to False
        stl_exporter.SetASCIIMode(False)
    stl_exporter.Write(a_shape, filename)

    assert os.path.isfile(filename)
예제 #2
0
def export_stl_file(shape, filename, tolerance=1e-4):
    """Exports a shape to a STL mesh file.  The mesh is automatically
    computed prior to export and the resolution/tolerance of the mesh
    can optionally be changed from the default of 1e-4"""
    mesh = BRepMesh_IncrementalMesh(shape.val().wrapped, tolerance, True)
    mesh.Perform()
    writer = StlAPI_Writer()
    writer.Write(shape.val().wrapped, filename)
예제 #3
0
def _to_stl(shp, path, delta):
    path = os.path.expanduser(path)

    mesh = BRepMesh_IncrementalMesh(shp.Shape(), delta)

    if mesh.IsDone() is False:
        return False

    stl_writer = StlAPI_Writer()
    stl_writer.Write(shp.Shape(), path)
    return True
예제 #4
0
def getStl(g, step=0.6):
    global geom_counter
    geom_counter = geom_counter + 1
    name_base = "./tmp_g_" + str(fem_counter)
    stl_file = name_base + ".stl"
    mesh = BRepMesh_IncrementalMesh(g, step)
    mesh.Perform()
    stl_exporter = StlAPI_Writer()
    stl_exporter.SetASCIIMode(
        True)  # change to False if you need binary export
    stl_exporter.Write(g, stl_file)
    return stl_file
예제 #5
0
def save_to_stl(shapes, dirpath=Path.home()):
    assert isinstance(shapes, list)

    try:
        os.makedirs(Path(dirpath))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(True)
    for index, shape in enumerate(shapes):
        filepath = Path(dirpath, "combined_shape_" + str(index + 1) + ".stl")
        stl_writer.Write(shape, str(filepath))
예제 #6
0
    def Write(self, filename, single_export=True):
        print("write-Part")
        path, ext = os.path.splitext(filename)

        # Default to a step writer if no extension type was provided:
        if not ext:
            ext = '.stp'

        status = []
        if ext == '.stl':
            stl_ascii_format = False
            if single_export:
                stl_writer = StlAPI_Writer()
                for name, component in self.items():
                    shape = component
                    status.append(
                        stl_writer.Write(shape, filename, stl_ascii_format))
            else:
                for name, component in self.items():
                    stl_writer = StlAPI_Writer()
                    f = path + '_' + name + ext
                    shape = component
                    status.append(stl_writer.Write(shape, f, stl_ascii_format))

        elif ext in ['.stp', '.step']:
            if single_export:
                status.append(
                    export_STEPFile_name(list(self.values()), filename))
            else:
                for name, component in self.items():
                    f = path + '_' + name + ext
                    status.append(export_STEPFile_name([component], f))
        else:
            raise ValueError('Unexpected file extension {}'.format(ext))

        return status
예제 #7
0
    def Write(self, filename, single_export=True):
        print("write-Product")
        path, ext = os.path.splitext(filename)

        status = []

        if ext == '.stl':
            stl_ascii_format = False

            if single_export:
                stl_writer = StlAPI_Writer()
                for partname, part in self.items():
                    for name, component in part.items():
                        status.append(
                            stl_writer.Write(component, filename,
                                             stl_ascii_format))
            else:
                for partname, part in self.items():
                    f = path + '_' + name + ext
                    status.append(path.Write(f, single_export=True))

        elif ext in ['.stp', '.step']:
            if single_export:
                shapes = []
                for partname, part in self.items():
                    print(part)
                    shapes.append(part)
                status.append(export_STEPFile_name(shapes, filename))
            else:
                for name, part in self.items():
                    f = path + '_' + name + ext
                    # Writes one file per part
                    p = Part()
                    p.AddComponent(part, name)
                    status.append(p.Write(f, single_export=True))
        """
        Aim Output STEP file (single_export==True)
        Product1 -- Part1 -- Comp1
                  |        - Comp2
                  - Part2 -- Comp1
                  |        - Comp2
                  - Comp1
        """

        return status
예제 #8
0
def write_stl(shape, filename, definition=0.1):
    from OCC.Core.StlAPI import StlAPI_Writer
    import os

    directory = os.path.split(__name__)[0]
    stl_output_dir = os.path.abspath(directory)
    assert os.path.isdir(stl_output_dir)

    stl_file = os.path.join(stl_output_dir, filename)

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(False)

    from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
    mesh = BRepMesh_IncrementalMesh(shape, definition)
    mesh.Perform()
    assert mesh.IsDone()

    stl_writer.Write(shape, stl_file)
    assert os.path.isfile(stl_file)
    return stl_file
예제 #9
0
def stp2stl(filename, fileIODir, linDeflection=0.1, angDeflection=0.1, solidOnly=True):
    # make sure the path exists otherwise OCE get confused
    assert os.path.isdir(fileIODir)

    nameBase = filename.split('.')[0]

    stpName = os.path.abspath(os.path.join(fileIODir, nameBase + '.stp'))
    modelShp = read_step_file(stpName)
    if solidOnly:
        solids = list(Topo(modelShp).solids())
        modelShp = solids[0]
    mesh = BRepMesh_IncrementalMesh(modelShp, linDeflection)
    mesh.Perform()
    assert mesh.IsDone()

    # set the directory where to output the
    stlName = os.path.abspath(os.path.join(fileIODir, nameBase + '.stl'))

    stl_exporter = StlAPI_Writer()
    stl_exporter.SetASCIIMode(True)  # change to False if you need binary export
    stl_exporter.Write(modelShp, stlName)
    # make sure the program was created
    assert os.path.isfile(stlName)
예제 #10
0
def write_stl_file(a_shape,
                   filename,
                   mode="ascii",
                   linear_deflection=0.9,
                   angular_deflection=0.5):
    """export the shape to a STL file
    Be careful, the shape first need to be explicitly meshed using BRepMesh_IncrementalMesh
    a_shape: the topods_shape to export
    filename: the filename
    mode: optional, "ascii" by default. Can either be "binary"
    linear_deflection: optional, default to 0.001. Lower, more occurate mesh
    angular_deflection: optional, default to 0.5. Lower, more accurate_mesh
    """
    if a_shape.IsNull():
        raise AssertionError("Shape is null.")
    if mode not in ["ascii", "binary"]:
        raise AssertionError("mode should be either ascii or binary")
    if os.path.isfile(filename):
        print(f"Warning: {filename} already exists and will be replaced")
    # first mesh the shape
    mesh = BRepMesh_IncrementalMesh(a_shape, linear_deflection, False,
                                    angular_deflection, True)
    # mesh.SetDeflection(0.05)
    mesh.Perform()
    if not mesh.IsDone():
        raise AssertionError("Mesh is not done.")

    stl_exporter = StlAPI_Writer()
    if mode == "ascii":
        stl_exporter.SetASCIIMode(True)
    else:  # binary, just set the ASCII flag to False
        stl_exporter.SetASCIIMode(False)
    stl_exporter.Write(a_shape, filename)

    if not os.path.isfile(filename):
        raise IOError("File not written to disk.")
예제 #11
0
    def plot(self, plot_file=None, save_fig=False):
        """
        Method to plot a file. If `plot_file` is not given it plots
        `self.shape`.

        :param string plot_file: the filename you want to plot.
        :param bool save_fig: a flag to save the figure in png or not.
            If True the plot is not shown.

        :return: figure: matlplotlib structure for the figure of the
            chosen geometry
        :rtype: matplotlib.pyplot.figure
        """
        if plot_file is None:
            shape = self.shape
            plot_file = self.infile
        else:
            shape = self.load_shape_from_file(plot_file)

        stl_writer = StlAPI_Writer()
        # Do not switch SetASCIIMode() from False to True.
        stl_writer.SetASCIIMode(False)

        # Necessary to write to STL [to check]
        stl_mesh = BRepMesh_IncrementalMesh(shape, 0.01)
        stl_mesh.Perform()

        f = stl_writer.Write(shape, 'aux_figure.stl')

        # Create a new plot
        figure = pyplot.figure()
        axes = mplot3d.Axes3D(figure)

        # Load the STL files and add the vectors to the plot
        stl_mesh = mesh.Mesh.from_file('aux_figure.stl')
        os.remove('aux_figure.stl')
        axes.add_collection3d(
            mplot3d.art3d.Poly3DCollection(stl_mesh.vectors / 1000))

        # Get the limits of the axis and center the geometry
        max_dim = np.array([\
            np.max(stl_mesh.vectors[:, :, 0]) / 1000,\
            np.max(stl_mesh.vectors[:, :, 1]) / 1000,\
            np.max(stl_mesh.vectors[:, :, 2]) / 1000])
        min_dim = np.array([\
            np.min(stl_mesh.vectors[:, :, 0]) / 1000,\
            np.min(stl_mesh.vectors[:, :, 1]) / 1000,\
            np.min(stl_mesh.vectors[:, :, 2]) / 1000])

        max_lenght = np.max(max_dim - min_dim)
        axes.set_xlim(\
            -.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2,\
            .6 * max_lenght + (max_dim[0] + min_dim[0]) / 2)
        axes.set_ylim(\
            -.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2,\
            .6 * max_lenght + (max_dim[1] + min_dim[1]) / 2)
        axes.set_zlim(\
            -.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2,\
            .6 * max_lenght + (max_dim[2] + min_dim[2]) / 2)

        # Show the plot to the screen
        if not save_fig:
            pyplot.show()
        else:
            figure.savefig(plot_file.split('.')[0] + '.png')

        return figure
예제 #12
0
def write_stl(shape, filepath):
    assert isinstance(filepath, Path)

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(True)
    stl_writer.Write(copy.deepcopy(shape), str(filepath))