Beispiel #1
0
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 "AP214IS" or "AP242DIS"
    """
    # a few checks
    if a_shape.IsNull():
        raise AssertionError("Shape %s is null." % a_shape)
    if application_protocol not in ["AP203", "AP214IS", "AP242DIS"]:
        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 IOError("Error while writing shape to STEP file.")
    if not os.path.isfile(filename):
        raise IOError("File %s was not saved to filesystem." % filename)
Beispiel #2
0
    def add_occ_shape(self, name, occ_shape):
        """
        Add an OpenCascade TopoDS_Shape.
        """

        if name not in self._ref:

            from OCC.STEPControl import STEPControl_Writer, STEPControl_AsIs

            # step format is used for the storage.
            step_writer = STEPControl_Writer()

            step_writer.Transfer(occ_shape, STEPControl_AsIs)

            shape_data = None

            with tmpfile() as tmpf:

                step_writer.Write(tmpf[1])

                tmpf[0].flush()
                shape_data = str_of_file(tmpf[1])

                shape = self._ref.create_dataset(name, (1, ),
                                                 dtype=h5py.new_vlen(str))
                shape[:] = shape_data
                shape.attrs['id'] = self._number_of_shapes
                shape.attrs['type'] = 'step'
                self._number_of_shapes += 1
Beispiel #3
0
    def write_step(stshape):
        # initialize the STEP exporter
        step_writer = STEPControl_Writer()

        # missing person => load failure
        #Interface_Static_SetCVal("write.step.schema", "AP203")

        step_str, shape = stshape

        step_writer.Transfer(shape, STEPControl_AsIs)
        status = step_writer.Write(
            'siconos-mechanisms-{0}.stp'.format(step_str))
 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 writeSTEP(filepath, shape):
    """ Write STEP file of the shape"""

    # STEPControl_AsIs says to make the STEP model the same geometry type as the
    # shape (ie. a solid Shape should be a STEP Solid)
    writer = STEPControl_Writer()
    writer.Transfer(diffuser.Shape(), STEPControl_AsIs)

    # Write the STEP file to the given filepath
    try:
        writer.Write(filepath.as_posix())
    except:
        print('Write failed')
    else:
        if args.v >= 1:
            print(f'\nSTEP file was successfully saved to:\n {filepath}')
Beispiel #6
0
    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.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")
Beispiel #7
0
    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.STEPControl import STEPControl_Writer, STEPControl_AsIs
        from OCC.Interface import Interface_Static_SetCVal as SetCVal
        from OCC.Interface import Interface_Static_SetIVal as SetIVal
        from OCC.Interface import Interface_Static_SetRVal as SetRVal
        from OCC.IFSelect import IFSelect_RetDone
        
        # Set all params
        exporter = STEPControl_Writer()
        SetIVal("write.precision.mode", PRECISION_MODES[self.precision_mode])
        if self.precision_mode == 'greatest':
            SetRVal("write.precision.val", self.precision_val)
        SetIVal("write.step.assembly", ASSEMBLY_MODES[self.assembly_mode])
        SetCVal("write.step.schema", self.schema)
        if self.product_name:
            SetCVal("write.step.product.name", self.product_name)
        SetIVal("write.surfacecurve.mode", 
                SURFACECURVE_MODES[self.surfacecurve_mode])
        SetCVal("write.step.unit", self.units.upper())
        SetIVal("write.step.vertex.mode", VERTEX_MODES[self.vertex_mode])

        # Load the enaml model file
        parts = load_model(self.filename)
        
        for part in parts:
            # Render the part from the declaration
            shape = part.render()
            
            # Transfer all shapes
            if hasattr(shape, 'Shape'):
                exporter.Transfer(shape.Shape(), STEPControl_AsIs)
            else:
                exporter.Transfer(shape, STEPControl_AsIs)

        # Send it
        status = exporter.Write(self.path)
        if status != IFSelect_RetDone or not os.path.exists(self.path):
            raise RuntimeError("Failed to write shape")
Beispiel #8
0
def build(input, output):
    #sample xml for testing
    xml = "<eagle version=\"7\"><drawing><board><plain><wire x1=\"0\" y1=\"0\" x2=\"0\" y2=\"2\" width=\"0.254\" layer=\"20\"/><wire x1=\"0\" y1=\"2\" x2=\"1.5\" y2=\"2\" width=\"0.254\" layer=\"20\"/><wire x1=\"1.5\" y1=\"2\" x2=\"1\" y2=\"0\" width=\"0.254\" layer=\"20\"/><wire x1=\"1\" y1=\"0\" x2=\"0\" y2=\"0\" width=\"0.254\" layer=\"20\"/></plain></board></drawing></eagle>"

    #xmldoc = minidom.parseString( xml )

    xmldoc = minidom.parse(input)

    wires = xmldoc.getElementsByTagName('wire')

    makeWire = BRepBuilderAPI_MakeWire()

    for wire in wires:

        if wire.attributes['layer'].value == '20':
            x1 = float(wire.attributes['x1'].value)
            y1 = float(wire.attributes['y1'].value)

            x2 = float(wire.attributes['x2'].value)
            y2 = float(wire.attributes['y2'].value)

            #print('Building edge from  {}, {} to {}, {}'.format( x1,y1,x2,y2))

            edge = BRepBuilderAPI_MakeEdge( gp_Pnt( x1, y1, 0.0 ), \
                                            gp_Pnt( x2, y2, 0.0 ) \
                                                      )

            makeWire.Add(edge.Edge())

    face = BRepBuilderAPI_MakeFace(makeWire.Wire())

    #vector & height
    vector = gp_Vec(0, 0, .1)

    body = BRepPrimAPI_MakePrism(face.Face(), vector)

    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", "AP203")

    # transfer shapes and write file
    step_writer.Transfer(body.Shape(), STEPControl_AsIs)
    status = step_writer.Write(output)

    if status != IFSelect_RetDone:
        raise AssertionError("load failed")
Beispiel #9
0
def write_step_file(shape, filename, application_protocol='AP203'):
    """ Exports a shape to a STEP file.

    Parameters
    ----------
    shape : TopoDS_Shape
        Shape to be exported, an object of the `TopoDS_Shape` class or one of its subclasses. See
        https://www.opencascade.com/doc/occt-7.4.0/refman/html/class_topo_d_s___shape.html
    filename : str
        Name of the file the shape is saved into.
    application_protocol : {'AP203', 'AP214IS', 'AP242DIS'}, optional
        Version of schema used for the output STEP file. The default is 'AP203'.

    Notes
    -----
    For details on how to read and write STEP files, see the documentation on
    https://dev.opencascade.org/doc/overview/html/occt_user_guides__step.html.

    """
    if shape.IsNull():
        raise AssertionError('Shape is null.')
    if application_protocol not in ['AP203', 'AP214IS', 'AP242DIS']:
        raise ValueError(
            'Application protocol must be one of {"AP203", "AP214IS", "AP242DIS"}.'
        )
    if os.path.isfile(filename):
        warnings.warn('File already exists and will be replaced.',
                      RuntimeWarning)

    # Create and initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", application_protocol)

    # Transfer shape and write file
    step_writer.Transfer(shape, STEPControl_AsIs)
    status = step_writer.Write(filename)

    if status != IFSelect_RetDone:
        raise IOError('Error while writing shape to STEP file.')
    if not os.path.isfile(filename):
        raise IOError('File was not saved.')
def export_STEPFile(shapes, filename):
    """Exports a .stp file containing the input shapes
    Parameters
    ----------
    shapes : list of TopoDS_Shape
        Shapes to write to file
    filename : string
        The output filename
    """
    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    #    Interface_Static_SetCVal("write.step.schema", "AP214") # Use default?

    # transfer shapes
    for shape in shapes:
        step_writer.Transfer(shape, STEPControl_AsIs)

    status = step_writer.Write(filename)

    assert (status == IFSelect_RetDone)
    return status
Beispiel #11
0
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)
Beispiel #12
0
def build_test(path):
    #points
    pt1 = gp_Pnt(0, 0, 0)
    pt2 = gp_Pnt(0, 2, 0)
    pt3 = gp_Pnt(1.5, 2, 0)
    pt4 = gp_Pnt(1, 0, 0)

    edge1 = BRepBuilderAPI_MakeEdge(pt1, pt2)
    edge2 = BRepBuilderAPI_MakeEdge(pt2, pt3)
    edge3 = BRepBuilderAPI_MakeEdge(pt3, pt4)
    edge4 = BRepBuilderAPI_MakeEdge(pt4, pt1)

    #make wire with 4 edges
    wire = BRepBuilderAPI_MakeWire(edge1.Edge(), edge2.Edge(), edge3.Edge(),
                                   edge4.Edge())

    #alternate wire. create and then add in
    #makeWire = BRepBuilderAPI_MakeWire()
    #makeWire.add( wire )
    #wireProfile = makeWire.Wire()

    face = BRepBuilderAPI_MakeFace(wire.Wire())

    #vector & height
    vector = gp_Vec(0, 0, .1)

    body = BRepPrimAPI_MakePrism(face.Face(), vector)

    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", "AP203")

    # transfer shapes and write file
    step_writer.Transfer(body.Shape(), STEPControl_AsIs)
    status = step_writer.Write(path)

    if status != IFSelect_RetDone:
        raise AssertionError("load failed")
##(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/>.

from __future__ import print_function

from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

from OCC.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCC.Interface import Interface_Static_SetCVal
from OCC.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")

assert (status == IFSelect_RetDone)
Beispiel #14
0
def export_STEPFile_name(shapes, filename):
    print(filename)
    step_writer = STEPControl_Writer()
    ws = step_writer.WS().GetObject()
    print(ws.ModeWriteShape())
Beispiel #15
0
def write_step(shape, file_name):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(shape, STEPControl_AsIs)
    step_writer.Write(file_name)
Beispiel #16
0
 def __init__(self, tol=1.0E-6):
     self.obj = STEPControl_Writer()
     self.obj.SetTolerance(tol)
     Interface_Static_SetCVal("write.step.schema", "AP214")
     """
Beispiel #17
0
    def exportStep(self, fileName):

        writer = STEPControl_Writer()
        writer.Transfer(self.wrapped, STEPControl_AsIs)

        return writer.Write(fileName)
Beispiel #18
0
def _write_step(table):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(table, STEPControl_AsIs)
    status = step_writer.Write("table.stp")