def topo2topotype(occtopology):
    """
    This function converts the original OCCtopology of the given topology. e.g. an OCCcompound that is originally an OCCface etc.
 
    Parameters
    ----------
    occtopology : OCCtopology 
        The OCCtopology to be converted. 
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
        
    Returns
    -------
    original topology : OCCtopology
        The original OCCtopology of the input.
    """
    shapetype = occtopology.ShapeType()
    if shapetype == TopAbs_COMPOUND:  #compound
        orig_topo = topods_Compound(occtopology)
    if shapetype == TopAbs_COMPSOLID:  #compsolid
        orig_topo = topods_CompSolid(occtopology)
    if shapetype == TopAbs_SOLID:  #solid
        orig_topo = topods_Solid(occtopology)
    if shapetype == TopAbs_SHELL:  #shell
        orig_topo = topods_Shell(occtopology)
    if shapetype == TopAbs_FACE:  #face
        orig_topo = topods_Face(occtopology)
    if shapetype == TopAbs_WIRE:  #wire
        orig_topo = topods_Wire(occtopology)
    if shapetype == TopAbs_EDGE:  #edge
        orig_topo = topods_Edge(occtopology)
    if shapetype == TopAbs_VERTEX:  #vertex
        orig_topo = topods_Vertex(occtopology)
    return orig_topo
Exemplo n.º 2
0
    def triangulate_solid(self):

        mesh = BRepMesh_IncrementalMesh(self.shape, 0.3, False, 0.5, True)
        mesh.Perform()

        b = BRep_Tool()
        ex = TopExp_Explorer(self.shape, TopAbs_FACE)
        faces = []
        verts = []
        while ex.More():
            face = topods_Face(ex.Current())
            location = TopLoc_Location()
            triang_face = (b.Triangulation(face, location))

            if triang_face != None:
                tab = triang_face.Nodes()
                tri = triang_face.Triangles()

                for i in range(1, triang_face.NbTriangles() + 1):
                    try:
                        verts.append(list(tab.Value(i).Coord()))
                    except:
                        continue

                for i in range(1, triang_face.NbTriangles() + 1):
                    try:
                        index1, index2, index3 = tri.Value(i).Get()
                        faces.append([index1 - 1, index2 - 1, index3 - 1])
                    except:
                        continue

            ex.Next()

        return verts, faces
Exemplo n.º 3
0
def occ_triangle_mesh(event=None):
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(aShape, 0.1)
    builder = BRep_Builder()
    Comp = TopoDS_Compound()
    builder.MakeCompound(Comp)

    ex = TopExp_Explorer(aShape, TopAbs_FACE)
    while ex.More():
        F = topods_Face(ex.Current())
        L = TopLoc_Location()
        facing = (BRep_Tool().Triangulation(F, L))
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles() + 1):
            trian = tri.Value(i)
            #print trian
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    M = index1
                    N = index2
                elif j == 2:
                    N = index3
                elif j == 3:
                    M = index2
                ME = BRepBuilderAPI_MakeEdge(tab.Value(M), tab.Value(N))
                if ME.IsDone():
                    builder.Add(Comp, ME.Edge())
        ex.Next()
    display.DisplayShape(Comp, update=True)
Exemplo n.º 4
0
def face_mesh_triangle(comp=TopoDS_Shape(), isR=0.1, thA=0.1):
    # Mesh the shape
    BRepMesh_IncrementalMesh(comp, isR, True, thA, True)
    bild1 = BRep_Builder()
    comp1 = TopoDS_Compound()
    bild1.MakeCompound(comp1)
    bt = BRep_Tool()
    ex = TopExp_Explorer(comp, TopAbs_FACE)
    while ex.More():
        face = topods_Face(ex.Current())
        location = TopLoc_Location()
        facing = bt.Triangulation(face, location)
        tab = facing.Nodes()
        tri = facing.Triangles()
        print(facing.NbTriangles(), facing.NbNodes())
        for i in range(1, facing.NbTriangles() + 1):
            trian = tri.Value(i)
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    m = index1
                    n = index2
                elif j == 2:
                    n = index3
                elif j == 3:
                    m = index2
                me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n))
                if me.IsDone():
                    bild1.Add(comp1, me.Edge())
        ex.Next()
    return comp1
Exemplo n.º 5
0
def shellC(shapeList, *args):  # callback (collector) for shell
    win.lineEdit.setFocus()
    for shape in shapeList:
        face = topods_Face(shape)
        win.faceStack.append(face)
    if (win.faceStack and win.lineEditStack):
        shell()
def recognize_clicked(shp, *kwargs):
    """ This is the function called every time
    a face is clicked in the 3d view
    """
    for shape in shp:  # this should be a TopoDS_Face TODO check it is
        print("Face selected: ", shape)
        recognize_face(topods_Face(shape))
def topo_explorer(occtopo2explore, topotype2find):
    """
    This function explores and fetches the specified topological type from the given OCCtopology.
    e.g. find a list of OCCfaces in an OCCcompound.
 
    Parameters
    ----------
    occtopo2explore : OCCtopology 
        The OCCtopology to be explored.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
        
    topotype2find : str 
        The string describing the topology to find. 
        The strings can be e.g. "compound", "compsolid", "solid", "shell", "face", "wire", "edge", "vertex". 
        
    Returns
    -------
    list of topology : list of OCCtopology
        The list of OCCtopology found in the specified OCCtopology.
    """
    geom_list = []
    if topotype2find == "compound":
        shapetype2find_topABS = TopAbs_COMPOUND
    if topotype2find == "compsolid":
        shapetype2find_topABS = TopAbs_COMPSOLID
    if topotype2find == "solid":
        shapetype2find_topABS = TopAbs_SOLID
    if topotype2find == "shell":
        shapetype2find_topABS = TopAbs_SHELL
    if topotype2find == "face":
        shapetype2find_topABS = TopAbs_FACE
    if topotype2find == "wire":
        shapetype2find_topABS = TopAbs_WIRE
    if topotype2find == "edge":
        shapetype2find_topABS = TopAbs_EDGE
    if topotype2find == "vertex":
        shapetype2find_topABS = TopAbs_VERTEX

    ex = TopExp_Explorer(occtopo2explore, shapetype2find_topABS)
    while ex.More():
        if shapetype2find_topABS == 0:
            geom = topods_Compound(ex.Current())
        if shapetype2find_topABS == 1:
            geom = topods_CompSolid(ex.Current())
        if shapetype2find_topABS == 2:
            geom = topods_Solid(ex.Current())
        if shapetype2find_topABS == 3:
            geom = topods_Shell(ex.Current())
        if shapetype2find_topABS == 4:
            geom = topods_Face(ex.Current())
        if shapetype2find_topABS == 5:
            geom = topods_Wire(ex.Current())
        if shapetype2find_topABS == 6:
            geom = topods_Edge(ex.Current())
        if shapetype2find_topABS == 7:
            geom = topods_Vertex(ex.Current())
        geom_list.append(geom)
        ex.Next()
    return geom_list
Exemplo n.º 8
0
def wpOnFaceC(shapeList, *args):  # callback (collector) for wpOnFace
    if not shapeList:
        shapeList = []
    for shape in shapeList:
        face = topods_Face(shape)
        win.faceStack.append(face)
    if len(win.faceStack) == 1:
        statusText = "Select face for workplane U direction."
        win.statusBar().showMessage(statusText)
    elif len(win.faceStack) == 2:
        wpOnFace()
def draft_angle(event=None):
    S = BRepPrimAPI_MakeBox(200., 300., 150.).Shape()
    adraft = BRepOffsetAPI_DraftAngle(S)
    topExp = TopExp_Explorer()
    topExp.Init(S, TopAbs_FACE)
    while topExp.More():
        face = topods_Face(topExp.Current())
        surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(face)).GetObject()
        dirf = surf.Pln().Axis().Direction()
        ddd = gp_Dir(0, 0, 1)
        if dirf.IsNormal(ddd, precision_Angular()):
            adraft.Add(face, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))
        topExp.Next()
    adraft.Build()
    display.DisplayShape(adraft.Shape(), update=True)
Exemplo n.º 10
0
def get_faces(_shape):
    """ return the faces from `_shape`
    :param _shape: TopoDS_Shape, or a subclass like TopoDS_Solid
    :return: a list of faces found in `_shape`
    """
    topExp = TopExp_Explorer()
    topExp.Init(_shape, TopAbs_FACE)
    _faces = []

    while topExp.More():
        fc = topods_Face(topExp.Current())
        # print(fc)
        _faces.append(fc)
        topExp.Next()

    return _faces
 def _bspline_surface_from_face(self, face):
     """
     Private method that takes a TopoDS_Face and transforms it into a
     Bspline_Surface.
     
 	:param TopoDS_Face face: the TopoDS_Face to be converted
     :rtype: Geom_BSplineSurface
     """
     if not isinstance(face, TopoDS_Face):
         raise TypeError("face must be a TopoDS_Face")
     # TopoDS_Face converted to Nurbs
     nurbs_face = topods_Face(BRepBuilderAPI_NurbsConvert(face).Shape())
     # GeomSurface obtained from Nurbs face
     surface = BRep_Tool.Surface(nurbs_face)
     # surface is now further converted to a bspline surface
     bspline_surface = geomconvert_SurfaceToBSplineSurface(surface)
     return bspline_surface
Exemplo n.º 12
0
def simple_mesh():
    #
    # Create the shape
    #
    theBox = BRepPrimAPI_MakeBox(200, 60, 60).Shape()
    theSphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape()
    shape = BRepAlgoAPI_Fuse(theSphere, theBox).Shape()
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(shape, 0.8)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_FACE)
    while ex.More():
        face = topods_Face(ex.Current())
        location = TopLoc_Location()
        facing = (bt.Triangulation(face, location)).GetObject()
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles() + 1):
            trian = tri.Value(i)
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    m = index1
                    n = index2
                elif j == 2:
                    n = index3
                elif j == 3:
                    m = index2
                me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n))
                if me.IsDone():
                    builder.Add(comp, me.Edge())
        ex.Next()
    display.EraseAll()
    display.DisplayShape(shape)
    display.DisplayShape(comp, update=True)
Exemplo n.º 13
0
    def recognize_clicked(self, shp, *kwargs):
        """ This is the function called every time
        a face is clicked in the 3d view
        """
        '''t = TopologyExplorer(self.frame)
        for shape in t.faces():  # this should be a TopoDS_Face TODO check it is
            print("Face selected: ", shape)
            self.recognize_face(topods_Face(shape))'''

        for shape in shp:  # this should be a TopoDS_Face TODO check it is
            print("Face selected: ", shape)
            bbox = Bnd_Box()
            brepbndlib_Add(shape, bbox)
            xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
            bounds = [
                sorted([xmax - xmin, ymax - ymin, zmax - zmin])[1],
                sorted([xmax - xmin, ymax - ymin, zmax - zmin])[2]
            ]
            print('--> Bounds', xmax - xmin, ymax - ymin, zmax - zmin)
            centre, normal, X_axis = self.recognize_face(topods_Face(shape))
            self.faces.append([centre, normal, X_axis, bounds])
Exemplo n.º 14
0
    def recognize_clicked(self, shp, *kwargs):
        """ This is the function called every time
        a face is clicked in the 3d view
        """

        '''t = TopologyExplorer(self.frame)
        for shape in t.faces():  # this should be a TopoDS_Face TODO check it is
            print("Face selected: ", shape)
            self.recognize_face(topods_Face(shape))'''

        for shape in shp:  # this should be a TopoDS_Face TODO check it is
            print("Face selected: ", shape)
            bbox = Bnd_Box()
            brepbndlib_Add(shape, bbox)
            xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
            bounds = [sorted([xmax - xmin, ymax - ymin, zmax - zmin])[1],
                      sorted([xmax - xmin, ymax - ymin, zmax - zmin])[2]]
            print('--> Bounds', xmax - xmin, ymax - ymin, zmax - zmin)
            centre, normal, X_axis = self.recognize_face(topods_Face(shape))
            if shape in self.faces_shape:
                # self.display.DisplayShape(shape, color='GREEN', transparency=0.9)
                # self.display.Context.Remove(shape)#######
                # self.display.Context.
                ind = self.faces_shape.index(shape)

                self.faces_shape.pop(ind)
                self.faces.pop(ind)
                self.faces_name.pop(ind)

            else:
                # self.display.DisplayShape(shape, color='RED', transparency=0.8)
                # self.display.FitAll()
                self.faces.append([centre, normal, X_axis, bounds])
                self.faces_shape.append(shape)
                self.faces_name.append(bounds[0] * bounds[1])

            # self.display.SetCloseAllContexts()
            self.reload_faces()
            self.display.SetSelectionModeFace()  # switch to Face selection mode
Exemplo n.º 15
0
        tpedg = Topo(edg)
        for v in tpedg.vertices():
            pnt = brt.Pnt(topods_Vertex(v))
            edge_points.append(Point([pnt.X(), pnt.Y(), pnt.Z()]))

            display.DisplayColoredShape(pnt, 'GREEN')
        all_points.append(edge_points)
    if len(all_points) != 0:
        pol = segments_to_polyline(all_points)
        all_edges = polyline3d_to_edges(pol)
    for edg in all_edges:
        face_explorer = TopExp_Explorer(faces1[f].Shape(), TopAbs_FACE)
        while False:  #face_explorer.More():
            try:
                TopOpeBRepTool_CurveTool_MakePCurveOnFace(
                    edg, topods_Face(face_explorer.Current()))
                print 'done'
            except:
                print 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr'
            face_explorer.Next()
    print 'out'
    ss = BRepFeat_SplitShape(faces1[f].Shape())
    ss.SetCheckInterior(True)
    for edg in all_edges:
        face = TopoDS_Face()
        if section.HasAncestorFaceOn1(edg, face):
            ss.Add(edg, face)
            display.DisplayColoredShape(face, 'RED')
    ss.Build()
    dl = ss.DirectLeft()
    test = TopTools_ListIteratorOfListOfShape(dl)
Exemplo n.º 16
0
a1 = []
a1.append(gp_Pnt(-4, 0, 2))
a1.append(gp_Pnt(-7, 2, 2))
a1.append(gp_Pnt(-6, 3, 1))
a1.append(gp_Pnt(-4, 3, -1))
a1.append(gp_Pnt(-3, 5, -2))

pt_list1 = point_list_to_TColgp_Array1OfPnt(a1)
SPL1 = GeomAPI_PointsToBSpline(pt_list1).Curve()

a2 = []
a2.append(gp_Pnt(-4, 0, 2))
a2.append(gp_Pnt(-2, 2, 0))
a2.append(gp_Pnt(2, 3, -1))
a2.append(gp_Pnt(3, 7, -2))
a2.append(gp_Pnt(4, 9, -1))

pt_list2 = point_list_to_TColgp_Array1OfPnt(a2)
SPL2 = GeomAPI_PointsToBSpline(pt_list2).Curve()

fill = GeomFill_BSplineCurves(SPL1, SPL2, GeomFill_CoonsStyle)
surface = fill.Surface()
face = topods_Face(BRepBuilderAPI_MakeFace(surface, 1e-6).Shape())

step_writer = STEPControl_Writer()
Interface_Static_SetCVal("write.step.schema", "AP203")

step_writer.Transfer(face, STEPControl_AsIs)
status = step_writer.Write("surface1.stp")
Exemplo n.º 17
0
my_renderer = JupyterRenderer()

# Generation of a box

# In[4]:

S = BRepPrimAPI_MakeBox(20., 30., 15.).Shape()

# Apply a draft angle.

# In[5]:

adraft = BRepOffsetAPI_DraftAngle(S)
topExp = TopExp_Explorer()
topExp.Init(S, TopAbs_FACE)
while topExp.More():
    face = topods_Face(topExp.Current())
    surf = Geom_Plane.DownCast(BRep_Tool_Surface(face))
    dirf = surf.Pln().Axis().Direction()
    ddd = gp_Dir(0, 0, 1)
    if dirf.IsNormal(ddd, precision_Angular()):
        adraft.Add(face, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))
    topExp.Next()
adraft.Build()
shp = adraft.Shape()

# In[6]:

my_renderer.DisplayShape(shp, render_edges=True, update=True)
Exemplo n.º 18
0
# ==============================================================================
# BRep
# ==============================================================================

brep = BRep()
brep.shape = face

# mesh = brep.to_tesselation()

BRepMesh_IncrementalMesh(brep.shape, 0.1, False, 0.1, False)

bt = BRep_Tool()
ex = TopExp_Explorer(brep.shape, TopAbs_FACE)
while ex.More():
    face = topods_Face(ex.Current())
    location = TopLoc_Location()
    facing = (bt.Triangulation(face, location))
    tab = facing.Nodes()
    tri = facing.Triangles()
    for i in range(1, facing.NbTriangles() + 1):
        trian = tri.Value(i)
        index1, index2, index3 = trian.Get()
        # for j in range(1, 4):
        #     if j == 1:
        #         m = index1
        #         n = index2
        #     elif j == 2:
        #         n = index3
        #     elif j == 3:
        #         m = index2
Exemplo n.º 19
0
 def face(self, face) -> None:
     self._face = topods_Face(face)
Exemplo n.º 20
0
    def __init__(self, shape):
        from OCC.Core.BRep import BRep_Tool
        from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
        from OCC.Core.TopAbs import TopAbs_FACE, TopAbs_VERTEX
        from OCC.Core.TopExp import TopExp_Explorer
        from OCC.Core.TopLoc import TopLoc_Location
        from OCC.Core.TopoDS import topods_Face, topods_Vertex, TopoDS_Iterator

        vertices = []  # a (nested) list of vec3
        triangles = []  # a (flat) list of integers
        normals = []
        uv = []

        # Mesh the shape
        linDeflection = 0.8
        BRepMesh_IncrementalMesh(shape, linDeflection)
        bt = BRep_Tool()

        # Explore the faces of the shape
        # each face is triangulated, we need to collect all the parts
        expFac = TopExp_Explorer(shape, TopAbs_FACE)
        while expFac.More():
            face = topods_Face(expFac.Current())
            location = TopLoc_Location()
            facing = (bt.Triangulation(face, location))
            try:
                tri = facing.Triangles()
                nTri = facing.NbTriangles()
                ver = facing.Nodes()
            except:
                tri = None
                nTri = None
                ver = None
            # store origin of the face's local coordinates
            transf = face.Location().Transformation()

            # iterate over triangles and store indices of vertices defining each triangle
            # OCC uses one-based indexing
            for i in range(1, nTri + 1):
                # each triangle is defined by three points
                # each point is defined by its index in the list of vertices
                index1, index2, index3 = tri.Value(i).Get()
                indices = [index1, index2, index3]

                # python uses zero-based indexing
                # for each vertex of a triangle, check whether it is already known
                # then store it (or not) and update the index
                for idx in [0, 1, 2]:
                    # read global coordinates of each point
                    vec3 = [
                        ver.Value(indices[idx]).Transformed(transf).X(),
                        ver.Value(indices[idx]).Transformed(transf).Y(),
                        ver.Value(indices[idx]).Transformed(transf).Z()
                    ]
                    if vec3 not in vertices:
                        vertices.append(vec3)
                    indices[idx] = vertices.index(vec3)
                triangles.extend(indices)
            expFac.Next()

        self.shape = shape
        self.vertices = vertices
        self.triangles = triangles
        self.normals = normals
        self.uv = uv
Exemplo n.º 21
0
    def write(self, mesh_points, filename, tolerance=None):
        """
        Writes a output file, called `filename`, copying all the structures
        from self.filename but the coordinates. `mesh_points` is a matrix
        that contains the new coordinates to write in the output file.

        :param numpy.ndarray mesh_points: it is a *n_points*-by-3 matrix
            containing the coordinates of the points of the mesh.
        :param str filename: name of the output file.
        :param float tolerance: tolerance for the construction of the faces
            and wires in the write function. If not given it uses
            `self.tolerance`.
        """
        self._check_filename_type(filename)
        self._check_extension(filename)
        self._check_infile_instantiation()

        self.outfile = filename

        if tolerance is not None:
            self.tolerance = tolerance

        # cycle on the faces to update the control points position
        # init some quantities
        faces_explorer = TopExp_Explorer(self.shape, TopAbs_FACE)
        n_faces = 0
        control_point_position = self._control_point_position

        compound_builder = BRep_Builder()
        compound = TopoDS_Compound()
        compound_builder.MakeCompound(compound)

        while faces_explorer.More():
            # similar to the parser method
            face = topods_Face(faces_explorer.Current())
            nurbs_converter = BRepBuilderAPI_NurbsConvert(face)
            nurbs_converter.Perform(face)
            nurbs_face = nurbs_converter.Shape()
            face_aux = topods_Face(nurbs_face)
            brep_face = BRep_Tool.Surface(topods_Face(nurbs_face))
            bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face)
            occ_face = bspline_face

            n_poles_u = occ_face.NbUPoles()
            n_poles_v = occ_face.NbVPoles()

            i = 0
            for pole_u_direction in range(n_poles_u):
                for pole_v_direction in range(n_poles_v):
                    control_point_coordinates = mesh_points[
                        i + control_point_position[n_faces], :]
                    point_xyz = gp_XYZ(*control_point_coordinates)

                    gp_point = gp_Pnt(point_xyz)
                    occ_face.SetPole(pole_u_direction + 1,
                                     pole_v_direction + 1, gp_point)
                    i += 1

            # construct the deformed wire for the trimmed surfaces
            wire_maker = BRepBuilderAPI_MakeWire()
            tol = ShapeFix_ShapeTolerance()
            brep = BRepBuilderAPI_MakeFace(occ_face, self.tolerance).Face()
            brep_face = BRep_Tool.Surface(brep)

            # cycle on the edges
            edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE)
            while edge_explorer.More():
                edge = topods_Edge(edge_explorer.Current())
                # edge in the (u,v) coordinates
                edge_uv_coordinates = BRep_Tool.CurveOnSurface(edge, face_aux)
                # evaluating the new edge: same (u,v) coordinates, but
                # different (x,y,x) ones
                edge_phis_coordinates_aux = BRepBuilderAPI_MakeEdge(
                    edge_uv_coordinates[0], brep_face)
                edge_phis_coordinates = edge_phis_coordinates_aux.Edge()
                tol.SetTolerance(edge_phis_coordinates, self.tolerance)
                wire_maker.Add(edge_phis_coordinates)
                edge_explorer.Next()

            # grouping the edges in a wire
            wire = wire_maker.Wire()

            # trimming the surfaces
            brep_surf = BRepBuilderAPI_MakeFace(occ_face, wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
Exemplo n.º 22
0
 def occ_face(self):
     return topods_Face(self.occ_shape)
Exemplo n.º 23
0
from compas.datastructures import Mesh
from compas_view2.app import App

box = BRepPrimAPI_MakeBox(1, 1, 1).Shape()

print(box.NbChildren())
print(box.ShapeType())

tool = BRep_Tool()

polygons = []

faces = TopExp_Explorer(box, TopAbs_FACE)

while faces.More():
    face = topods_Face(faces.Current())
    vertices = TopExp_Explorer(face, TopAbs_VERTEX)
    points = []

    while vertices.More():
        vertex = topods_Vertex(vertices.Current())
        point = tool.Pnt(vertex)
        x = point.X()
        y = point.Y()
        z = point.Z()
        points.append([x, y, z])
        vertices.Next()

    polygons.append(points[:4])
    polygons.append(points[4:])
    faces.Next()
    def __call__(self, obj, dst=None):
        """
        This method performs the deformation on the CAD geometry. If `obj` is a
        TopoDS_Shape, the method returns a TopoDS_Shape containing the deformed
        geometry. If `obj` is a filename, the method deforms the geometry
        contained in the file and writes the deformed shape to `dst` (which has
        to be set).
        
        :param obj: the input geometry.
        :type obj: str or TopoDS_Shape
        :param str dst: if `obj` is a string containing the input filename,
            `dst` refers to the file where the deformed geometry is saved.
        """
        # Manage input
        if isinstance(obj, str):  # if a input filename is passed
            if dst is None:
                raise ValueError(
                    'Source file is provided, but no destination specified')
            shape = self.read_shape(obj)
        elif isinstance(obj, TopoDS_Shape):
            shape = obj
        # Maybe do we need to handle also Compound?
        else:
            raise TypeError

        #create compound to store modified faces
        compound_builder = BRep_Builder()
        compound = TopoDS_Compound()
        compound_builder.MakeCompound(compound)

        # cycle on the faces to get the control points

        # iterator to faces (TopoDS_Shape) contained in the shape
        faces_explorer = TopExp_Explorer(shape, TopAbs_FACE)

        while faces_explorer.More():
            # performing some conversions to get the right
            # format (BSplineSurface)
            # TopoDS_Face obtained from iterator
            face = topods_Face(faces_explorer.Current())
            # performing some conversions to get the right
            # format (BSplineSurface)
            bspline_surface = self._bspline_surface_from_face(face)

            # add the required amount of poles in u and v directions
            self._enrich_surface_knots(bspline_surface)

            # deform the Bspline surface through FFD
            self._deform_bspline_surface(bspline_surface)

            # through moving the control points, we now changed the SURFACE
            # underlying FACE we are processing. we now need to obtain the
            # curves (actually, the WIRES) that define the bounds of the
            # surface and TRIM the surface with them, to obtain the new FACE

            #we now start really looping on the wires
            #we will create a single curve joining all the edges in the wire
            # the curve must be a bspline curve so we need to make conversions
            # through all the way

            # list that will contain the (single) outer wire of the face
            outer_wires = []
            # list that will contain all the inner wires (holes) of the face
            inner_wires = []
            # iterator to loop over TopoDS_Wire in the original (undeformed)
            # face
            wire_explorer = TopExp_Explorer(face, TopAbs_WIRE)
            while wire_explorer.More():
                # wire obtained from the iterator
                wire = topods_Wire(wire_explorer.Current())

                # getting a bpline curve joining all the edges of the wire
                composite_curve = self._bspline_curve_from_wire(wire)

                # adding all the required knots to the Bspline curve
                self._enrich_curve_knots(composite_curve)

                # deforming the Bspline curve through FFD
                self._deform_bspline_curve(composite_curve)

                # the GeomCurve corresponding to the whole edge has now
                # been deformed. Now we must make it become an proper
                # wire

                # list of shapes (needed by the wire generator)
                shapes_list = TopTools_ListOfShape()

                # edge (to be converted to wire) obtained from the modified
                # Bspline curve
                modified_composite_edge = \
                    BRepBuilderAPI_MakeEdge(composite_curve).Edge()
                # modified edge is added to shapes_list
                shapes_list.Append(modified_composite_edge)

                # wire builder
                wire_maker = BRepBuilderAPI_MakeWire()
                wire_maker.Add(shapes_list)
                # deformed wire is finally obtained
                modified_wire = wire_maker.Wire()

                # now, the wire can be outer or inner. we store the outer
                # and (possible) inner ones in different lists
                # this is because we first need to trim the surface
                # using the outer wire, and then we can trim it
                # with the wires corresponding to all the holes.
                # the wire order is important, in the trimming process
                if wire == breptools_OuterWire(face):
                    outer_wires.append(modified_wire)
                else:
                    inner_wires.append(modified_wire)
                wire_explorer.Next()

            # so once we finished looping on all the wires to modify them,
            # we first use the only outer one to trim the surface
            # face builder object
            face_maker = BRepBuilderAPI_MakeFace(bspline_surface,
                                                 outer_wires[0])

            # and then add all other inner wires for the holes
            for inner_wire in inner_wires:
                face_maker.Add(inner_wire)

            # finally, we get our trimmed face with all its holes
            trimmed_modified_face = face_maker.Face()

            # trimmed_modified_face is added to the modified faces compound
            compound_builder.Add(compound, trimmed_modified_face)

            # and move to the next face
            faces_explorer.Next()

        ## END SURFACES #################################################

        if isinstance(dst, str):  # if a input filename is passed
            # save the shape exactly to the filename, aka `dst`
            self.write_shape(dst, compound)
        else:
            return compound
Exemplo n.º 25
0
    def parse(self, filename):
        """
        Method to parse the file `filename`. It returns a matrix with all
        the coordinates.

        :param string filename: name of the input file.

        :return: mesh_points: it is a `n_points`-by-3 matrix containing
            the coordinates of the points of the mesh
        :rtype: numpy.ndarray

        """
        self.infile = filename
        self.shape = self.load_shape_from_file(filename)

        # cycle on the faces to get the control points
        # init some quantities
        n_faces = 0
        control_point_position = [0]
        faces_explorer = TopExp_Explorer(self.shape, TopAbs_FACE)
        mesh_points = np.zeros(shape=(0, 3))

        while faces_explorer.More():
            # performing some conversions to get the right format (BSplineSurface)
            face = topods_Face(faces_explorer.Current())
            nurbs_converter = BRepBuilderAPI_NurbsConvert(face)
            nurbs_converter.Perform(face)
            nurbs_face = nurbs_converter.Shape()
            brep_face = BRep_Tool.Surface(topods_Face(nurbs_face))
            bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face)

            # openCascade object
            occ_face = bspline_face

            # extract the Control Points of each face
            n_poles_u = occ_face.NbUPoles()
            n_poles_v = occ_face.NbVPoles()
            control_polygon_coordinates = np.zeros(shape=(n_poles_u *
                                                          n_poles_v, 3))

            # cycle over the poles to get their coordinates
            i = 0
            for pole_u_direction in range(n_poles_u):
                for pole_v_direction in range(n_poles_v):
                    control_point_coordinates = occ_face.Pole(
                        pole_u_direction + 1, pole_v_direction + 1)
                    control_polygon_coordinates[i, :] = [
                        control_point_coordinates.X(),
                        control_point_coordinates.Y(),
                        control_point_coordinates.Z()
                    ]
                    i += 1
            # pushing the control points coordinates to the mesh_points array
            # (used for FFD)
            mesh_points = np.append(mesh_points,
                                    control_polygon_coordinates,
                                    axis=0)
            control_point_position.append(control_point_position[-1] +
                                          n_poles_u * n_poles_v)

            n_faces += 1
            faces_explorer.Next()
        self._control_point_position = control_point_position
        return mesh_points