def write_step_file(a_shape, filename, application_protocol="AP203"): """ exports a shape to a STEP file a_shape: the topods_shape to export (a compound, a solid etc.) filename: the filename application protocol: "AP203" or "AP214" """ # a few checks if a_shape.IsNull(): raise AssertionError("Shape %s is null." % a_shape) if application_protocol not in ["AP203", "AP214IS"]: raise AssertionError( "application_protocol must be either AP203 or AP214IS. You passed %s." % application_protocol) if os.path.isfile(filename): print("Warning: %s file already exists and will be replaced" % filename) # creates and initialise the step exporter step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", application_protocol) # transfer shapes and write file step_writer.Transfer(a_shape, STEPControl_AsIs) status = step_writer.Write(filename) if not status == IFSelect_RetDone: raise AssertionError("Error while writing shape to STEP file.") if not os.path.isfile(filename): raise AssertionError("File %s was not saved to filesystem." % filename)
def write_step_file(shape, filename, step_ver="AP214"): step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", step_ver) step_writer.Transfer(shape, STEPControl_AsIs) status = step_writer.Write(filename) assert(status == IFSelect_RetDone)
class Model (plotocc): def __init__(self): super().__init__() self.builder = BRep_Builder() self.compound = TopoDS_Compound() self.builder.MakeCompound(self.compound) schema = 'AP203' assembly_mode = 1 self.writer = STEPControl_Writer() self.fp = self.writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal('write.step.schema', schema) Interface_Static_SetCVal('write.step.unit', 'M') Interface_Static_SetCVal('write.step.assembly', str(assembly_mode)) def AddShape(self, shp, name="shape"): Interface_Static_SetCVal('write.step.product.name', name) status = self.writer.Transfer(shp, STEPControl_AsIs) if int(status) > int(IFSelect_RetError): raise Exception('Some Error occurred') # This portion is not working as I hoped item = stepconstruct_FindEntity(self.fp, shp) if not item: raise Exception('Item not found') def export_stp_with_name(self): status = self.writer.Write(self.tempname + ".stp") if int(status) > int(IFSelect_RetError): raise Exception('Something bad happened')
def binvox_to_step(binvox_file, voxel_length, voxel_width, voxel_height, application_protocol="AP203"): """function used to change binvox file to step file binvox_file: the binvox file ('chair.binvox' etc.) voxel_length: the length of one voxel voxel_width: the width of one voxel voxel_height: the height of one voxel application protocol: "AP203" or "AP214IS" or "AP242DIS" """ with open(binvox_file, 'rb') as f: model = binvox_rw.read_as_3d_array(f) voxel = voxel_to_TopoDS(model, voxel_length, voxel_width, voxel_height) # initialize the STEP exporter step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", application_protocol) # transfer shapes and write file step_writer.Transfer(voxel, STEPControl_AsIs) status = step_writer.Write(binvox_file[:-6] + "stp") if status != IFSelect_RetDone: raise AssertionError("load failed")
def to_step(self, filepath: str, schema: str = "AP203", unit: str = "MM") -> None: """Write the BRep shape to a STEP file. Parameters ---------- filepath : str Location of the file. schema : str, optional STEP file format schema. unit : str, optional Base units for the geometry in the file. Returns ------- None """ step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", schema) Interface_Static_SetCVal("write.step.unit", unit) step_writer.Transfer(self.shape, STEPControl_AsIs) status = step_writer.Write(filepath) assert status == IFSelect_RetDone, "STEP writing failed."
def write_step(filename, shape): """ STEP writer """ step_writer = STEPControl_Writer() # Changes write schema to STEP standard AP203 # It is considered the most secure standard for STEP. # *According to PythonOCC documentation (http://www.pythonocc.org/) Interface_Static_SetCVal("write.step.schema", "AP203") Interface_Static_SetCVal('write.surfacecurve.mode','0') step_writer.Transfer(shape, STEPControl_AsIs) step_writer.Write(filename)
def export(self): """ Export shape object to STEP file """ writer = STEPControl_Writer() pcurves = 1 if self.write_pcurves else 0 Interface_Static_SetIVal("write.surfacecurve.mode", pcurves) Interface_Static_SetIVal("write.precision.mode", self.precision_mode) with suppress_stdout_stderr(): writer.Transfer(self.shape.val().wrapped, STEPControl_AsIs) writer.Write(self.filename) if self.add_meta_data: self._final_export()
class SCLSTEPWriter: def __init__(self): self.writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") def Write(self, path): status = self.writer.Write(path) if status != IFSelect_RetDone: raise AssertionError("Write failed") def Transfer(self, shape): self.writer.Transfer(shape, STEPControl_AsIs)
def save_assembly(self, shape): from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs from OCC.Core.Interface import Interface_Static_SetCVal from OCC.Core.IFSelect import IFSelect_RetDone step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") # transfer shapes and write file step_writer.Transfer(shape, STEPControl_AsIs) status = step_writer.Write("assembly5.stp") if status != IFSelect_RetDone: raise AssertionError("load failed")
def export_to_step(filename, parts): """ Export all the parts' shapes to a STEP file :param filename: The output STEP file :param parts: a list of Part instances :return: None """ compound = make_compound(parts) step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") step_writer.Transfer(compound, STEPControl_AsIs) status = step_writer.Write(filename) if status != IFSelect_RetDone: raise AssertionError("load failed")
def write_shape_to_file(self, shape, filename): """ This method saves the `shape` to the file `filename`. :param: TopoDS_Shape shape: loaded shape :param string filename: name of the input file. It should have proper extension (.step or .stp) """ self._check_filename_type(filename) self._check_extension(filename) step_writer = STEPControl_Writer() # Changes write schema to STEP standard AP203 # It is considered the most secure standard for STEP. # *According to PythonOCC documentation (http://www.pythonocc.org/) Interface_Static_SetCVal("write.step.schema", "AP203") step_writer.Transfer(shape, STEPControl_AsIs) step_writer.Write(filename)
def saveStepActPrt(self): prompt = 'Choose filename for step file.' fnametuple = QFileDialog.getSaveFileName( None, prompt, './', "STEP files (*.stp *.STP *.step)") fname, _ = fnametuple if not fname: print("Save step cancelled.") return # initialize the STEP exporter step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") # transfer shapes and write file step_writer.Transfer(self.activePart, STEPControl_AsIs) status = step_writer.Write(fname) assert status == IFSelect_RetDone
class ExportMethod (object): def __init__(self, tol=1.0E-6): self.obj = STEPControl_Writer() self.obj.SetTolerance(tol) Interface_Static_SetCVal("write.step.schema", "AP214") """ self.obj.PrintStatsTransfer: what 0 gives general statistics (number of translated roots, number of warnings, number of fail messages), 1 gives root results, 2 gives statistics for all checked entities, 3 gives the list of translated entities, 4 gives warning and fail messages, 5 gives fail messages only. The use of mode depends on the value of what. If what is 0, mode is ignored. If what is 1, 2 or 3, mode defines the following: 0 lists the numbers of IGES or STEP entities in the respective model 1 gives the number, identifier, type and result type for each IGES or STEP entity and/or its status (fail, warning, etc.) 2 gives maximum information for each IGES or STEP entity (i.e. checks) 3 gives the number of entities per type of IGES or STEP entity 4 gives the number of IGES or STEP entities per result type and/or status 5 gives the number of pairs (IGES or STEP or result type and status) 6 gives the number of pairs (IGES or STEP or result type and status) AND the list of entity numbers in the IGES or STEP model. If what is 4 or 5, mode defines the warning and fail messages as follows: if mode is 0 all warnings and checks per entity are returned if mode is 2 the list of entities per warning is returned. If mode is not set, only the list of all entities per warning is given. """ def add_shpe(self, shape): """ STEPControl_AsIs translates an Open CASCADE shape to its highest possible STEP representation. STEPControl_ManifoldSolidBrep translates an Open CASCADE shape to a STEP manifold_solid_brep or brep_with_voids entity. STEPControl_FacetedBrep translates an Open CASCADE shape into a STEP faceted_brep entity. STEPControl_ShellBasedSurfaceModel translates an Open CASCADE shape into a STEP shell_based_surface_model entity. STEPControl_GeometricCurveSet translates an Open CASCADE shape into a STEP geometric_curve_set entity. """ self.obj.Transfer(shape, STEPControl_AsIs) def fileout(self, filename): status = self.obj.Write(filename) assert(status == IFSelect_RetDone)
def write_step_file(a_shape, filename, application_protocol="AP203"): """ exports a shape to a STEP file a_shape: the topods_shape to export (a compound, a solid etc.) filename: the filename application protocol: "AP203" or "AP214" """ # a few checks assert not a_shape.IsNull() assert application_protocol in ["AP203", "AP214IS"] if os.path.isfile(filename): print("Warning: %s file already exists and will be replaced" % filename) # creates and initialise the step exporter step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") # transfer shapes and write file step_writer.Transfer(a_shape, STEPControl_AsIs) status = step_writer.Write(filename) assert status == IFSelect_RetDone assert os.path.isfile(filename)
class ExportCAFMethod(object): def __init__(self, name="name", tol=1.0E-10): self.name = name self.schema = 'AP214' self.assembly_mode = 1 self.stp = STEPControl_Writer() self.stp.SetTolerance(tol) self.app = self.stp.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal('write.step.schema', self.schema) Interface_Static_SetCVal('write.step.unit', 'MM') Interface_Static_SetCVal('write.step.assembly', str(self.assembly_mode)) # Interface_Static_SetCVal ("write.step.schema","AP203") # Interface_Static_SetIVal ("write.step.schema", 3) # Interface_Static_SetRVal def Add(self, shape, name="name"): """ STEPControl_AsIs translates an Open CASCADE shape to its highest possible STEP representation. STEPControl_ManifoldSolidBrep translates an Open CASCADE shape to a STEP manifold_solid_brep or brep_with_voids entity. STEPControl_FacetedBrep translates an Open CASCADE shape into a STEP faceted_brep entity. STEPControl_ShellBasedSurfaceModel translates an Open CASCADE shape into a STEP shell_based_surface_model entity. STEPControl_GeometricCurveSet translates an Open CASCADE shape into a STEP geometric_curve_set entity. """ Interface_Static_SetCVal('write.step.product.name', name) self.stp.Transfer(shape, STEPControl_AsIs) item = stepconstruct_FindEntity(self.app, shape) item.SetName(TCollection_HAsciiString(name)) def Write(self, filename=None): if not filename: filename = self.name path, ext = os.path.splitext(filename) if not ext: ext = ".stp" status = self.stp.Write(path + ext) assert (status == IFSelect_RetDone)
class ExportCAFMethod(object): def __init__(self, name="name", tol=1.0E-10): self.name = name self.writer = STEPControl_Writer() self.fp = self.writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal("write.step.schema", "AP214") Interface_Static_SetCVal('write.step.unit', 'mm') Interface_Static_SetCVal('write.step.assembly', str(1)) def Add(self, shape, name="name"): """ STEPControl_AsIs translates an Open CASCADE shape to its highest possible STEP representation. STEPControl_ManifoldSolidBrep translates an Open CASCADE shape to a STEP manifold_solid_brep or brep_with_voids entity. STEPControl_FacetedBrep translates an Open CASCADE shape into a STEP faceted_brep entity. STEPControl_ShellBasedSurfaceModel translates an Open CASCADE shape into a STEP shell_based_surface_model entity. STEPControl_GeometricCurveSet translates an Open CASCADE shape into a STEP geometric_curve_set entity. """ Interface_Static_SetCVal('write.step.product.name', name) status = self.writer.Transfer(shape, STEPControl_AsIs) if int(status) > int(IFSelect_RetError): raise Exception('Some Error occurred') # This portion is not working as I hoped item = stepconstruct_FindEntity(self.fp, shape) if not item: raise Exception('Item not found') item.SetName(TCollection_HAsciiString(name)) def Write(self, filename=None): if not filename: filename = self.name path, ext = os.path.splitext(filename) if not ext: ext = ".stp" status = self.writer.Write(path + ext) assert (status == IFSelect_RetDone)
def to_step(self, filepath, schema="AP203"): """Write the surface geometry to a STP file. Parameters ---------- filepath : str schema : str, optional Returns ------- None """ from OCC.Core.STEPControl import STEPControl_Writer from OCC.Core.STEPControl import STEPControl_AsIs from OCC.Core.Interface import Interface_Static_SetCVal from OCC.Core.IFSelect import IFSelect_RetDone step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", schema) step_writer.Transfer(self.occ_face, STEPControl_AsIs) status = step_writer.Write(filepath) if status != IFSelect_RetDone: raise AssertionError("Operation failed.")
def write_step(shape, file_name): step_writer = STEPControl_Writer() step_writer.Transfer(shape, STEPControl_AsIs) step_writer.Write(file_name)
class StepExporter(object): r"""STEP file exporter Parameters ---------- filename : str the file to save to eg. myshape.step verbose : bool verbosity of the STEP exporter schema : ["AP203", "AP214CD"] which STEP schema to use, either AP214CD or AP203 tolerance : float """ def __init__(self, filename, verbose=False, schema="AP214CD", tolerance=1e-4): logger.info("StepExporter instantiated with filename : %s" % filename) logger.info("StepExporter schema : %s" % schema) logger.info("StepExporter tolerance : %s" % str(tolerance)) if schema not in ["AP203", "AP214CD"]: msg = "Unsupported STEP schema" logger.error(msg) raise StepUnknownSchemaException(msg) check_exporter_filename(filename, step_extensions) check_overwrite(filename) self._filename = filename self._shapes = list() self.verbose = verbose self._stepcontrol_writer = STEPControl_Writer() self._stepcontrol_writer.SetTolerance(tolerance) Interface_Static_SetCVal("write.step.schema", schema) def add_shape(self, a_shape): r"""Add a shape to export Parameters ---------- a_shape : TopoDS_Shape or subclass """ check_shape(a_shape) # raises an exception if the shape is not valid self._shapes.append(a_shape) def write_file(self): r"""Write STEP file""" for shp in self._shapes: transfer_status = self._stepcontrol_writer.Transfer( shp, STEPControl_AsIs) if transfer_status != IFSelect_RetDone: msg = "An error occurred while transferring a " \ "shape to the STEP writer" logger.error(msg) raise StepShapeTransferException(msg) write_status = self._stepcontrol_writer.Write(self._filename) if self.verbose: self._stepcontrol_writer.PrintStatsTransfer() if write_status == IFSelect_RetDone: logger.info("STEP file write successful.") else: msg = "An error occurred while writing the STEP file" logger.error(msg) raise StepFileWriteException(msg)
## ##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/>. from __future__ import print_function from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs from OCC.Core.Interface import Interface_Static_SetCVal from OCC.Core.IFSelect import IFSelect_RetDone # creates a basic shape box_s = BRepPrimAPI_MakeBox(10, 20, 30).Shape() # initialize the STEP exporter step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") # transfer shapes and write file step_writer.Transfer(box_s, STEPControl_AsIs) status = step_writer.Write("box.stp") if status != IFSelect_RetDone: raise AssertionError("load failed")
def to_stp(self, destination_file, geom_repr="solid", schema="AP242"): """ Write current assembly to STEP file OpenCascade reference: https://www.opencascade.com/doc/occt-7.4.0/overview/html/occt_user_guides__step.html#occt_step_3 :param destination_file: :param geom_repr: :param schema: STEP Schemas. """ from OCC.Core.IFSelect import IFSelect_RetError from OCC.Core.Interface import Interface_Static_SetCVal from OCC.Core.STEPConstruct import stepconstruct_FindEntity from OCC.Core.STEPControl import STEPControl_AsIs, STEPControl_Writer from OCC.Core.TCollection import TCollection_HAsciiString from ada.core.utils import Counter if geom_repr not in ["shell", "solid"]: raise ValueError( 'Geometry representation can only accept either "solid" or "shell" as input' ) destination_file = pathlib.Path(destination_file).with_suffix(".stp") assembly_mode = 1 shp_names = Counter(1, "shp") writer = STEPControl_Writer() fp = writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal("write.step.schema", schema) # Interface_Static_SetCVal('write.precision.val', '1e-5') Interface_Static_SetCVal("write.precision.mode", "1") Interface_Static_SetCVal("write.step.assembly", str(assembly_mode)) from ada import Assembly, Beam, Part, Pipe, Plate, Shape, Wall def add_geom(geo, o): name = o.name if o.name is not None else next(shp_names) Interface_Static_SetCVal("write.step.product.name", name) stat = writer.Transfer(geo, STEPControl_AsIs) if int(stat) > int(IFSelect_RetError): raise Exception("Some Error occurred") item = stepconstruct_FindEntity(fp, geo) if not item: logging.debug("STEP item not found for FindEntity") else: item.SetName(TCollection_HAsciiString(name)) if type(self) is Shape: assert isinstance(self, Shape) add_geom(self.geom, self) elif type(self) in (Beam, Plate, Wall): assert isinstance(self, (Beam, Plate, Wall)) if geom_repr == "shell": add_geom(self.shell, self) else: add_geom(self.solid, self) elif type(self) is Pipe: assert isinstance(self, Pipe) for geom in self.geometries: add_geom(geom, self) elif type(self) in (Part, Assembly): assert isinstance(self, Part) for p in self.get_all_subparts() + [self]: for obj in list(p.plates) + list(p.beams) + list( p.shapes) + list(p.pipes) + list(p.walls): if type(obj) in (Plate, Beam, Wall): try: if geom_repr == "shell": add_geom(obj.shell, self) else: add_geom(obj.solid, self) except BaseException as e: logging.info(f'passing pl "{obj.name}" due to {e}') continue elif type(obj) in (Pipe, ): assert isinstance(obj, Pipe) for geom in obj.geometries: add_geom(geom, self) elif type(obj) is Shape: add_geom(obj.geom, self) else: raise ValueError("Unkown Geometry type") os.makedirs(destination_file.parent, exist_ok=True) status = writer.Write(str(destination_file)) if int(status) > int(IFSelect_RetError): raise Exception("Error during write operation") print(f'step file created at "{destination_file}"')
cut = cutFactory.MakeCirclePatern( 90., 30, ) cut = transform.TransformShape(0., 0., 30., 0., -90., 0., cut) tube = BRepAlgoAPI_Cut(tube, cut).Shape() cut = cutFactory.MakePentagonPattern(90., 30., 2.) cut = transform.TransformShape(0., 0., 80., 0., -90., 0., cut) tube = BRepAlgoAPI_Cut(tube, cut).Shape() aisCut = AIS_Shape(cut) context.Display(aisCut, True) aisTube = AIS_Shape(tube) context.Display(aisTube, True) stepWriter = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203") stepWriter.Transfer(aisTube.Shape(), STEPControl_AsIs) status = stepWriter.Write("Test3.stp") # menu_name = 'Tube Maker' # add_menu( menu_name ) # add_function_to_menu( menu_name, TestFunction ) display.FitAll() start_display()
#display.DisplayShape(wire_extrados.Shape(), update=True) #display.DisplayShape(wire_intrados.Shape(), update=True) display.DisplayShape(wire.Shape(), update=True) generator_extrados.AddWire(wire_extrados.Wire()) generator_intrados.AddWire(wire_intrados.Wire()) generator_trailing_edge.AddWire(wire_trailing_edge.Wire()) generator.AddWire(wire.Wire()) #start_display() generator_extrados.Build() extrados_shape = generator_extrados.Shape() generator_intrados.Build() intrados_shape = generator_intrados.Shape() generator_trailing_edge.Build() trailing_edge_shape = generator_trailing_edge.Shape() intrados_trailing_edge = generator_trailing_edge.Shape() display.DisplayShape(extrados_shape) display.DisplayShape(intrados_shape) display.DisplayShape(trailing_edge_shape) generator.Build() #display.DisplayShape(generator.Shape()) step_writer.Transfer(extrados_shape, STEPControl_AsIs) step_writer.Transfer(intrados_shape, STEPControl_AsIs) #step_writer.Transfer(generator.Shape(), STEPControl_AsIs) status = step_writer.Write("surface.stp") start_display() write_geo('foil', geom)
print type(bb) #display.DisplayShape(all_s) domain = general_split_algorithm([bb], surfaces) from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Section #display.DisplayShape(domain) from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs step_writer = STEPControl_Writer() step_writer.Transfer(domain, STEPControl_AsIs) stpfile = "foil.stp" step_writer.Write(stpfile) topo = Topo(domain) faces = topo.faces iface = 0 print dir(faces) N = float(topo.number_of_faces()) surfaces = [None for i in range(topo.number_of_faces())] maxima = [-1 for i in range(topo.number_of_faces())] for f in topo.faces(): print str(100. * float(iface) / N) + ' % done' for f2 in d_faces: shp = BRepAlgoAPI_Section(f, d_faces[f2]).Shape() tp = Topo(shp) nedge = tp.number_of_edges()
shp = read_step_file( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'step_examples', '21_141_sponka.stp')) get_boundingbox(shp) print('box dx, dy, dz:', get_dx_dy_dz(shp)) cones, holes, newshp = detect_through_holes(shp, True) # CUT from parallelepiped cutFromParallelepiped = cut_from_parallelepiped(shp, 0.001) step_writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP242") # transfer shapes and write file step_writer.Transfer(cutFromParallelepiped, STEPControl_StepModelType(STEPControl_AsIs)) status = step_writer.Write( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'result', 'objects.stp')) print('volume:', count_volume_from_shape(cutFromParallelepiped)) print('box dx, dy, dz:', get_dx_dy_dz(cutFromParallelepiped)) print('cones', cones) print('holes', holes) display.DisplayShape(cutFromParallelepiped, transparency=0.5, color="blue") display.DisplayShape(shp, color="yellow") # shp1 = read_step_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'result', 'objects.stp')) start_display()
writer = STEPControl_Writer() fp = writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal('write.step.schema', schema) Interface_Static_SetCVal('write.step.unit', 'M') Interface_Static_SetCVal('write.step.assembly', str(assembly_mode)) my_box1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() my_box2 = BRepPrimAPI_MakeBox(20., 1., 30.).Shape() components = [my_box1, my_box2] comp_names = ['PartA', 'PartB'] for i, comp in enumerate(components): Interface_Static_SetCVal('write.step.product.name', comp_names[i]) status = writer.Transfer(comp, STEPControl_AsIs) if int(status) > int(IFSelect_RetError): raise Exception('Some Error occurred') # This portion is not working as I hoped item = stepconstruct_FindEntity(fp, comp) if not item: raise Exception('Item not found') item.SetName(TCollection_HAsciiString(comp_names[i])) status = writer.Write('step_export_with_name.stp') if int(status) > int(IFSelect_RetError): raise Exception('Something bad happened') read_step_file_with_names_colors('step_export_with_name.stp')
class StepExporter: def __init__(self, schema="AP242", assembly_mode=1): self.writer = STEPControl_Writer() fp = self.writer.WS().TransferWriter().FinderProcess() self.fp = fp Interface_Static_SetCVal("write.step.schema", schema) # Interface_Static_SetCVal('write.precision.val', '1e-5') Interface_Static_SetCVal("write.precision.mode", "1") Interface_Static_SetCVal("write.step.assembly", str(assembly_mode)) def add_to_step_writer(self, obj: valid_types, geom_repr=ElemType.SOLID, fuse_piping=False): """Write current assembly to STEP file""" from ada.concepts.connections import JointBase if geom_repr not in ElemType.all: raise ValueError( f'Invalid geom_repr: "{geom_repr}". Must be in "{ElemType.all}"' ) if issubclass(type(obj), Shape): self.add_geom(obj.geom, obj, geom_repr=geom_repr) elif type(obj) in (Beam, Plate, Wall): self.export_structural(obj, geom_repr) elif type(obj) is Pipe: self.export_piping(obj, geom_repr, fuse_piping) elif type(obj) in (Part, Assembly) or issubclass(type(obj), JointBase): for sub_obj in obj.get_all_physical_objects( sub_elements_only=False): if type(sub_obj) in (Plate, Beam, Wall): self.export_structural(sub_obj, geom_repr) elif type(sub_obj) in (Pipe, ): self.export_piping(sub_obj, geom_repr, fuse_piping) elif issubclass(type(sub_obj), Shape): self.add_geom(sub_obj.geom, sub_obj, geom_repr=geom_repr) else: raise ValueError("Unknown Geometry type") else: raise ValueError("Unknown Geometry type") def add_geom(self, geom, obj, geom_repr=None): from ada.concepts.transforms import Placement from ada.core.vector_utils import vector_length from .utils import transform_shape name = obj.name if obj.name is not None else next(shp_names) Interface_Static_SetCVal("write.step.product.name", name) # Transform geometry res = obj.placement.absolute_placement() if vector_length(res - Placement().origin) > 0: geom = transform_shape(geom, transform=tuple(res)) try: if geom_repr == ElemType.SHELL: stat = self.writer.Transfer( geom, STEPControl_ShellBasedSurfaceModel) else: stat = self.writer.Transfer(geom, STEPControl_AsIs) except BaseException as e: logging.info(f"Passing {obj} due to {e}") return None if int(stat) > int(IFSelect_RetError): raise Exception("Some Error occurred") item = stepconstruct_FindEntity(self.fp, geom) if not item: logging.debug("STEP item not found for FindEntity") else: item.SetName(TCollection_HAsciiString(name)) def export_structural(self, stru_obj: Union[Plate, Beam, Wall], geom_repr): if geom_repr == ElemType.SHELL: self.add_geom(stru_obj.shell, stru_obj) elif geom_repr == ElemType.LINE: self.add_geom(stru_obj.line, stru_obj) else: self.add_geom(stru_obj.solid, stru_obj) def export_piping(self, pipe: Pipe, geom_repr, fuse_shapes=False): result = None for pipe_seg in pipe.segments: if geom_repr == ElemType.LINE: geom = pipe_seg.line elif geom_repr == ElemType.SHELL: geom = pipe_seg.shell else: geom = pipe_seg.solid if fuse_shapes is True: if result is None: result = geom else: result = BRepAlgoAPI_Fuse(result, geom).Shape() else: self.add_geom(geom, pipe) if fuse_shapes is True: self.add_geom(result, pipe) def write_to_file(self, destination_file, silent, return_file_obj=False) -> Union[None, StringIO]: if return_file_obj: logging.warning( "returning file objects for STEP is not yet supported. But will be from OCCT v7.7.0." ) destination_file = pathlib.Path(destination_file).with_suffix(".stp") os.makedirs(destination_file.parent, exist_ok=True) status = self.writer.Write(str(destination_file)) if int(status) > int(IFSelect_RetError): raise Exception("Error during write operation") if silent is False: print(f'step file created at "{destination_file}"')
class StepWrite(object): """ Write shape to a STEP file. :param str schema: Schema for STEP file ('AP203', or 'AP214'). :param units: Units to convert STEP file to. :type units: str or None :param product_name: The name of the STEP product entry. If more than one product is generated during translation, then OpenCASCADE will automatically append a unique integer. :type product_name: str or None :param assembly_mode: Mode for writing assemblies (0, 1, or 2). :type assembly_mode: int or None .. note:: The assembly modes are as follows: * 0 (off, default): Writes STEP files without assemblies. * 1(on): Writes all shapes in the form of STEP assemblies. * 2(auto): Writes shapes having a structure of (possibly nested) compounds in the form of STEP assemblies, single shapes are written without assembly structures. """ def __init__(self, schema='AP203', units=None, product_name=None, assembly_mode=None): self._writer = STEPControl_Writer() self._fp = self._writer.WS().TransferWriter().FinderProcess() Interface_Static.SetCVal('write.step.schema', schema) try: units = units_dict[units] except KeyError: units = Settings.units Interface_Static.SetCVal('write.step.unit', units) if product_name is not None: Interface_Static.SetCVal('write.step.product.name', product_name) if assembly_mode is not None: Interface_Static.SetIVal_('write.step.assembly', assembly_mode) @property def object(self): """ :return: The STEP writer object. :rtype: OCC.Core.STEPControl.STEPControl_Writer """ return self._writer def transfer(self, *shapes): """ Transfer and add the shapes to the exported entities. :param afem.topology.entities.Shape shapes: The shape(s). :return: *True* if shape was transferred, *False* if not. :rtype: bool """ added_shape = False for shape in shapes: shape = Shape.to_shape(shape) if not shape: continue status = self._writer.Transfer(shape.object, STEPControl_AsIs) if int(status) < int(IFSelect_RetError): added_shape = True return added_shape def set_name(self, shape, name): """ Set the name of the STEP entity for the given shape. The shape(s) should be transferred before naming them. :param afem.topology.entities.Shape shape: The shape (or sub-shape). :param str name: The name. :return: *True* if name is set, *False* otherwise. :rtype: bool """ item = stepconstruct.FindEntity(self._fp, shape.object) if not item: return False item.SetName(TCollection_HAsciiString(name)) return True def write(self, fn='afem.stp'): """ Write the STEP file. :param str fn: The filename. :return: *True* if written, *False* if not. :rtype: bool """ status = self._writer.Write(fn) return int(status) < int(IFSelect_RetError)