Exemplo n.º 1
0
def upload_model():

    if request.method == "POST":

        if request.files:

            model = request.files["model"]
            modelfile = os.path.join(app.config["MODEL_UPLOADS"],
                                     model.filename)
            model.save(modelfile)
            filename, file_extension = os.path.splitext(model.filename)
            #big_shp = read_step_file(modelfile)
            step_reader = STEPControl_Reader()
            status = step_reader.ReadFile(modelfile)
            if status == IFSelect_RetDone:
                ok = step_reader.TransferRoots()
                _nbs = step_reader.NbShapes()
                big_shp = step_reader.Shape()
                tess = ShapeTesselator(big_shp)
                tess.Compute(compute_edges=False, mesh_quality=0.5)
                jsonfile = filename + ".json"
                with open(os.path.join(app.config["MODEL_UPLOADS"], jsonfile),
                          "w") as text_file:
                    json_shape = tess.ExportShapeToThreejsJSONString(filename)
                    json_shape = json_shape.replace("data\\", "data/")
                    json_shape = json_shape.replace("\\step_postprocessed\\",
                                                    "/step_postprocessed/")
                    text_file.write(json_shape)
            else:
                raise Exception("error could not read step file")
            return redirect(url_for('modelview', modelname=jsonfile))

    return render_template("public/upload.html")
Exemplo n.º 2
0
    def load_shape_from_file(self, filename):
        """
        This method loads a shape from the file `filename`.

        :param string filename: name of the input file.
            It should have proper extension (.step or .stp)

        :return: shape: loaded shape
        :rtype: TopoDS_Shape
        """
        self._check_filename_type(filename)
        self._check_extension(filename)
        reader = STEPControl_Reader()
        return_reader = reader.ReadFile(filename)
        # check status
        if return_reader == IFSelect_RetDone:
            return_transfer = reader.TransferRoots()
            if return_transfer:
                # load all shapes in one
                shape = reader.OneShape()
                return shape
            else:
                raise RuntimeError("Shapes not loaded.")
        else:
            raise RuntimeError("Cannot read the file.")
Exemplo n.º 3
0
    def read_step_file(filename, verbosity=True):
        """ read the STEP file and returns a compound (based on OCC.Extend.DataExchange)
        filename: the file path
        return_as_shapes: optional, False by default. If True returns a list of shapes,
                          else returns a single compound
        verbosity: optional, False by default.
        """
        if not os.path.isfile(filename):
            raise FileNotFoundError("%s not found." % filename)

        step_reader = STEPControl_Reader()
        status = step_reader.ReadFile(filename)

        if status != IFSelect_RetDone:  # check status
            raise AssertionError("Error: can't read file.")

        if verbosity:
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

        _nbr = step_reader.TransferRoots()
        _nbs = step_reader.NbShapes()

        shape_to_return = step_reader.OneShape()  # a compound
        if shape_to_return is None:
            raise AssertionError("Shape is None.")
        elif shape_to_return.IsNull():
            raise AssertionError("Shape is Null.")

        return shape_to_return
Exemplo n.º 4
0
class StepRead(object):
    """
    Read a STEP file.

    :param str fn: The file to read.
    """
    def __init__(self, fn):
        self._reader = STEPControl_Reader()
        self._tr = self._reader.WS().TransferReader()

        # Read file
        status = self._reader.ReadFile(fn)
        if status != IFSelect_RetDone:
            raise RuntimeError("Error reading STEP file.")

        # Convert to desired units
        Interface_Static.SetCVal("xstep.cascade.unit", Settings.units)

        # Transfer
        nroots = self._reader.TransferRoots()
        if nroots > 0:
            self._shape = Shape.wrap(self._reader.OneShape())

    @property
    def object(self):
        """
        :return: The STEP reader object.
        :rtype: OCC.Core.STEPControl.STEPControl_Reader
        """
        return self._reader

    @property
    def shape(self):
        """
        :return: The main shape.
        :rtype: afem.topology.entities.Shape
        """
        return self._shape

    def name_from_shape(self, shape):
        """
        Attempt to extract the name for the STEP entity that corresponds to the
        shape.

        :param afem.topology.entities.Shape shape: The shape.

        :return: The name or None if not found.
        :rtype: str or None
        """
        item = self._tr.EntityFromShapeResult(shape.object, 1)
        if not item:
            return None
        return item.Name().ToCString()
Exemplo n.º 5
0
def read_step_file(filename, as_compound=True, verbosity=True):
    """ read the STEP file and returns a compound
    filename: the file path
    verbosity: optional, False by default.
    as_compound: True by default. If there are more than one shape at root,
    gather all shapes into one compound. Otherwise returns a list of shapes.
    """
    if not os.path.isfile(filename):
        raise FileNotFoundError("%s not found." % filename)

    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        if verbosity:
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        transfer_result = step_reader.TransferRoots()
        if not transfer_result:
            raise AssertionError("Transfer failed.")
        _nbs = step_reader.NbShapes()
        if _nbs == 0:
            raise AssertionError("No shape to transfer.")
        elif _nbs == 1:  # most cases
            return step_reader.Shape(1)
        elif _nbs > 1:
            print("Number of shapes:", _nbs)
            shps = []
            # loop over root shapes
            for k in range(1, _nbs + 1):
                new_shp = step_reader.Shape(k)
                if not new_shp.IsNull():
                    shps.append(new_shp)
            if as_compound:
                compound, result = list_of_shapes_to_compound(shps)
                if not result:
                    print("Warning: all shapes were not added to the compound")
                return compound
            else:
                print("Warning, returns a list of shapes.")
                return shps
    else:
        raise AssertionError("Error: can't read file.")
    return None
Exemplo n.º 6
0
import numpy as np
from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.TopAbs import TopAbs_FACE
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Core.StepRepr import StepRepr_RepresentationItem
from OCC.Core.BRepAdaptor import BRepAdaptor_Surface
from OCC.Core.GeomAbs import GeomAbs_Cylinder
from OCC.Core.TopoDS import topods

# Read the file and get the shape
reader = STEPControl_Reader()
tr = reader.WS().TransferReader()
reader.ReadFile('geometry_names.stp')
reader.TransferRoots()
shape = reader.OneShape()

# Explore the faces of the shape (these are known to be named)
exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
    s = exp.Current()
    exp.Next()

    # Converting TopoDS_Shape to TopoDS_Face
    face = topods.Face(s)

    # Working on the geometry
    face_adaptor = BRepAdaptor_Surface(face)
    face_type = face_adaptor.GetType()
    if face_type == GeomAbs_Cylinder:
        cylinder = face_adaptor.Cylinder()
        entity = {}
Exemplo n.º 7
0
def read_step_file_withnames(
    filename,
    breadface=False,
    breadedge=False
):  #Read a step file with names attached to solid, faces (can be extended to edges)
    """""[Read a step file with names attached to solid, faces (can be extended to edges)]
    
    Arguments:
        filename {[type]} -- [path to the .stp file]
    
    Keyword Arguments:
        breadface {bool} -- [read the faces' names] (default: {False})
        breadedge {bool} -- [read the edges' names] (default: {False})

    Returns:
        (dSolids, dFaces, dEdges) -- [two dicts with name (int) as key and aShape as value]
    """ ""

    reader = STEPControl_Reader()
    #tr = reader.WS().GetObject().TransferReader().GetObject()
    tr = reader.WS().GetObject().TransferReader()
    reader.ReadFile(filename)
    reader.TransferRoots()
    shape = reader.OneShape()

    dSolids = dict(
    )  #solids initial as a dict with name (int) as key and aShape as value
    dFaces = dict(
    )  #faces initial as a dict with name (int) as key and aShape as value
    dEdges = dict(
    )  #edges initial as a dict with name (int) as key and aShape as value

    #read the solid names
    exp = TopExp_Explorer(shape, TopAbs_SOLID)
    while exp.More():
        s = exp.Current()
        exp.Next()
        #Converting TopoDS_Shape to TopoDS_Face
        solid = topods.Solid(s)
        #Working on the name
        item = tr.EntityFromShapeResult(s, 1)
        if item == None:
            continue
        #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject()
        item = StepRepr_RepresentationItem.DownCast(item)
        name = item.Name().ToCString()
        if name:
            print('Found entity named: {}: {}.'.format(name, s))
            nameid = int(name.split('_')[-1])
            dSolids[nameid] = solid

    # read the face names
    if breadface:
        exp = TopExp_Explorer(shape, TopAbs_FACE)
        while exp.More():
            s = exp.Current()
            exp.Next()
            #Converting TopoDS_Shape to TopoDS_Face
            face = topods.Face(s)
            #Working on the name
            item = tr.EntityFromShapeResult(s, 1)
            if item.IsNull():
                continue
            #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject()
            item = StepRepr_RepresentationItem.DownCast(item)
            name = item.Name().GetObject().ToCString()
            if name:
                #            print('Found entity named: {}: {}.'.format(name, s))
                nameid = int(name.split('_')[-1])
                dFaces[nameid] = face

    # read the edge names
    if breadedge:
        exp = TopExp_Explorer(shape, TopAbs_EDGE)
        while exp.More():
            s = exp.Current()
            exp.Next()
            #Converting TopoDS_Shape to TopoDS_Face
            edge = topods.Edge(s)
            #Working on the name
            item = tr.EntityFromShapeResult(s, 1)
            if item.IsNull():
                continue
            #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject()
            item = StepRepr_RepresentationItem.DownCast(item)
            name = item.Name().GetObject().ToCString()
            if name:
                #            print('Found entity named: {}: {}.'.format(name, s))
                nameid = int(name.split('_')[-1])
                dEdges[nameid] = edge

    ret = (dSolids, dFaces, dEdges)
    return ret