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)
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) 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
def convert(source, dest): step_reader = STEPControl_Reader() status = step_reader.ReadFile(source) if status == IFSelect_RetDone: i = 1 ok = False number_of_roots = step_reader.NbRootsForTransfer() while i <= number_of_roots and not ok: ok = step_reader.TransferRoot(i) i += 1 if (not ok): return { 'error': 'Failed to find a suitable root for the STEP file' } shape = step_reader.Shape(1) output = os.path.abspath(dest) stl_ascii = False stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(stl_ascii) stl_writer.Write(shape, output) print "STL FILE: %s" % output else: print "Error, can't read file: %s" % './demo.stp'
def write_2_stl(occtopology, stl_filepath, linear_deflection = 0.8, angle_deflection = 0.5): """ This function writes a 3D model into STL format. Parameters ---------- occtopology : OCCtopology Geometries to be written into STL. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex stl_filepath : str The file path of the STL file. mesh_incremental_float : float, optional Default = 0.8. Returns ------- None : None The geometries are written to a STL file. """ from OCC.StlAPI import StlAPI_Writer from OCC.BRepMesh import BRepMesh_IncrementalMesh from OCC.TopoDS import TopoDS_Shape # Export to STL stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) occtopology = TopoDS_Shape(occtopology) mesh = BRepMesh_IncrementalMesh(occtopology, linear_deflection, True, angle_deflection, True) assert mesh.IsDone() stl_writer.Write(occtopology,stl_filepath)
def export(self, event): """ Export the current model to stl """ from OCC.StlAPI import StlAPI_Writer from OCC.BRepMesh import BRepMesh_IncrementalMesh #: TODO: All parts options = event.parameters.get('options') if not isinstance(options, ExportOptions): return False exporter = StlAPI_Writer() exporter.SetASCIIMode(not options.binary) #: Make a compound of compounds (if needed) compound = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(compound) for part in self.parts: #: Must mesh the shape first if isinstance(part, Part): builder.Add(compound, part.proxy.shape) else: builder.Add(compound, part.proxy.shape.Shape()) #: Build the mesh mesh = BRepMesh_IncrementalMesh(compound, options.linear_deflection, options.relative, options.angular_deflection) mesh.Perform() if not mesh.IsDone(): raise ExportError("Failed to create the mesh") exporter.Write(compound, options.path)
def write_stl(self, filename): # The active component or only component has no special suffix. The # inactive component, if it exists, has a '.inactive' component. stl_writer = Stl() stl_writer.SetASCIIMode(True) stl_writer.Write(self.shapes[0], filename + '.stl') if len(self.shapes) > 1: stl_writer = Stl() stl_writer.SetASCIIMode(True) stl_writer.Write(self.shapes[1], filename + '.inactive.stl') # All shapes (even if more than 2, in principle) are also output with a # suffix of their position in the STEP file for i, shape in enumerate(self.shapes): stl_writer = Stl() stl_writer.SetASCIIMode(True) stl_writer.Write(shape, filename + ('.%d.stl' % i))
def save_model(self): from OCC.StlAPI import StlAPI_Writer stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) for part in self.current_table.values(): try: for loft in part: stl_writer.Write(loft, model_filepath) except: stl_writer.Write(part, model_filepath)
def convert(source, dest): output = os.path.abspath(dest) shape = get_shape_from_file(source) if not shape: raise ConversionError("Could not create {}".format(output)) stl_ascii = False stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(stl_ascii) stl_writer.Write(shape, str(output)) return output
def stl_file(name, shape): stl_filename = "./" + name + "_low_resolution.stl" stl_exporter = StlAPI_Writer() stl_exporter.SetASCIIMode( True) # change to False if you need binary export stl_exporter.Write(shape, stl_filename) # then we change the mesh resolution #mesh.SetDeflection(0.05) stl_reader = StlAPI_Reader() fan_shp = TopoDS_Shape() stl_reader.Read(fan_shp, stl_filename) exproted = DisplayShapeFunc(fan_shp) display(exproted) return stl_filename
def export(self): """ Export a DeclaraCAD model from an enaml file to an STL based on the given options. Parameters ---------- options: declaracad.occ.plugin.ExportOptions """ from OCC.BRep import BRep_Builder from OCC.BRepMesh import BRepMesh_IncrementalMesh from OCC.StlAPI import StlAPI_Writer from OCC.TopoDS import TopoDS_Compound # Make a compound of compounds (if needed) compound = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(compound) # Load the enaml model file parts = load_model(self.filename) for part in parts: # Render the part from the declaration shape = part.render() # Must mesh the shape firsts if hasattr(shape, 'Shape'): builder.Add(compound, shape.Shape()) else: builder.Add(compound, shape) #: Build the mesh exporter = StlAPI_Writer() exporter.SetASCIIMode(not self.binary) mesh = BRepMesh_IncrementalMesh( compound, self.linear_deflection, self.relative, self.angular_deflection ) mesh.Perform() if not mesh.IsDone(): raise RuntimeError("Failed to create the mesh") exporter.Write(compound, self.path) if not os.path.exists(self.path): raise RuntimeError("Failed to write shape")
def export_files_for_simulation(self, control_surface={}, body={}): from OCC.StlAPI import StlAPI_Writer stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) for part, loft in body.items(): try: for l in loft: stl_writer.Write(l, "airplane.stl") os.system(f"meshio-convert airplane.stl airplane.obj") clean_after_body("airplane") except: stl_writer.Write(loft, part + ".stl") os.system(f"meshio-convert {part}.stl {part}.obj") clean_after_moveables(part)
def writestl(filepath, mesh): """ Write stl of IncrementalMesh Note: this is for IncrementalMesh files only. SMESH files have their own built in `.ExportStl()` method for this purpose """ writer = StlAPI_Writer() writer.SetASCIIMode(True) try: writer.Write(mesh.Shape(), filepath.as_posix()) except: print('Write failed') else: if args.v >= 1: print(f'\nstl file was successfully saved to:\n {filepath}')
def step_reader(step_string): from OCC.StlAPI import StlAPI_Writer from OCC.STEPControl import STEPControl_Reader from OCC.BRep import BRep_Builder from OCC.TopoDS import TopoDS_Compound from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity builder = BRep_Builder() comp = TopoDS_Compound() builder.MakeCompound(comp) stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) with io.tmpfile(contents=io.shapes()[shape_name][:][0]) as tmpfile: step_reader = STEPControl_Reader() status = step_reader.ReadFile(tmpfile[1]) if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = step_reader.TransferRoot(1) nbs = step_reader.NbShapes() l = [] for i in range(1, nbs + 1): shape = step_reader.Shape(i) builder.Add(comp, shape) with io.tmpfile(suffix='.stl') as tmpf: stl_writer.Write(comp, tmpf[1]) tmpf[0].flush() reader = vtk.vtkSTLReader() reader.SetFileName(tmpf[1]) reader.Update() return reader
def write_stl(shape, filename, df=0.1): from OCC.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.BRepMesh import BRepMesh_IncrementalMesh mesh = BRepMesh_IncrementalMesh(shape, df) mesh.Perform() assert mesh.IsDone() stl_writer.Write(shape, stl_file) assert os.path.isfile(stl_file)
def topods_shape_reader(shape, deflection=0.001): from OCC.StlAPI import StlAPI_Writer from OCC.BRepMesh import BRepMesh_IncrementalMesh import vtk stl_writer = StlAPI_Writer() with tmpfile(suffix='.stl') as tmpf: mesh = BRepMesh_IncrementalMesh(shape, deflection) mesh.Perform() assert mesh.IsDone() stl_writer.SetASCIIMode(False) stl_writer.Write(shape, tmpf[1]) tmpf[0].flush() reader = vtk.vtkSTLReader() reader.SetFileName(tmpf[1]) reader.Update() return reader
update=True, transparency=shape.transparency) start_display() # Export geometry to STEP or STL if requested lastArg = sys.argv[-1].split('=') cmd = lastArg[0] if cmd == 'stepfile' or cmd == 'stlfile': if len(lastArg) == 1: print('ERROR: no name was given for the requested output file.') exit(1) filename = lastArg[1] if cmd == 'stepfile': step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") for shape in tw_shape: if shape.Name() in sys.argv: step_writer.Transfer(shape.occ_shape, STEPControl_AsIs) status = step_writer.Write(filename + '.step') assert (status == IFSelect_RetDone) exit(0) if cmd == 'stlfile': stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) for shape in tw_shape: if shape.Name() in sys.argv: status = stl_writer.Write(shape.occ_shape, filename + '.stl') exit(0) print('ERROR: failed to write requested ouptut file.') print('Did you list a valid region on the command line?')
##pythonOCC is free software: you can redistribute it and/or modify ##it under the terms of the GNU Lesser General Public License as published by ##the Free Software Foundation, either version 3 of the License, or ##(at your option) any later version. ## ##pythonOCC is distributed in the hope that it will be useful, ##but WITHOUT ANY WARRANTY; without even the implied warranty of ##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##GNU Lesser General Public License for more details. ## ##You should have received a copy of the GNU Lesser General Public License ##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>. import os from OCC.StlAPI import StlAPI_Writer from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox my_box = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() # set the directory where to output the directory = os.path.split(__name__)[0] stl_output_dir = os.path.abspath(os.path.join(directory, "models")) # make sure the path exists otherwise OCE get confused assert os.path.isdir(stl_output_dir) stl_output_file = os.path.join(stl_output_dir, "box.stl") stl_exporter = StlAPI_Writer() stl_exporter.SetASCIIMode(True) # change to False if you need binary export stl_exporter.Write(my_box, stl_output_file)