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 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 __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 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 __init__(self, name="name", tol=1.0E-10): self.name = name self.step = STEPCAFControl_Writer() self.step.SetNameMode(True) self.doc = TDocStd_Document(TCollection_ExtendedString("")) self.x_app = XCAFApp_Application.GetApplication() self.x_app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), self.doc) self.shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) Interface_Static_SetCVal("write.step.schema", "AP214") Interface_Static_SetCVal('write.step.unit', 'mm')
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))
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 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 __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 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 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_STEPFile_single(shape, filename, tol=1.0E-6): """ Exports a .stp file containing the input shapes Parameters ---------- shape : TopoDS_Shape filename : string The output filename """ step = STEPCAFControl_Writer() step.SetNameMode(True) step.SetPropsMode(True) h_doc = TDocStd_Document() x_app = XCAFApp_Application.GetApplication().GetObject() x_app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) shape_tool = h_shape_tool.GetObject() Interface_Static_SetCVal("write.step.schema", "AP214") # transfer shapes print(filename) shape_tool.AddShape(shape) step.Transfer(h_doc, STEPControl_AsIs) status = step.Write(filename) assert(status == IFSelect_RetDone)
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)
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 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. """ label = self.shape_tool.AddShape(shape) Interface_Static_SetCVal('write.step.product.name', name) self.step.Transfer(self.doc, STEPControl_AsIs)
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 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))
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 test_static_method(self): ''' Test wrapper for static methods. ... snippet from the SWIG documentation ... Static class members present a special problem for Python. Prior to Python-2.2, Python classes had no support for static methods and no version of Python supports static member variables in a manner that SWIG can utilize. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this: class Spam { public: static void foo(); static int bar; }; In Python, the static member can be access in three different ways: >>> example.Spam_foo() # Spam::foo() >>> s = example.Spam() >>> s.foo() # Spam::foo() via an instance >>> example.Spam.foo() # Spam::foo(). Python-2.2 only ... end snippet ... In order that SWIG properly wraps static methods, the keyword 'static' must be included in the interface file. For instance, in the Interface.i file, the following line: static Standard_Boolean SetCVal(const char * name, const char * val); makes possible to use the method as: >>> from OCC.Core.Interface import * >>> Interface_Static_SetCVal("write.step.schema","AP203") ''' # needs to be inited otherwise the following does not work STEPControl_Writer() # Note : static methods are wrapped with lowercase convention # so SetCVal can be accessed with setcval r = Interface_Static_SetCVal("write.step.schema", "AP203") self.assertEqual(r, 1) l = Interface_Static_CVal("write.step.schema") self.assertEqual(l, "AP203")
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 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
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 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_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)
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 __init__(self): self.writer = STEPControl_Writer() Interface_Static_SetCVal("write.step.schema", "AP203")
def __init__(self, tol=1.0E-6): self.obj = STEPControl_Writer() self.obj.SetTolerance(tol) Interface_Static_SetCVal("write.step.schema", "AP214") """
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 OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox from OCC.Extend.DataExchange import read_step_file_with_names_colors schema = 'AP203' assembly_mode = 1 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:
display.SetSelectionModeFace() display.register_select_callback(recognize_clicked) p = os.path.dirname(os.path.abspath(__file__)) # open 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")
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}"')