コード例 #1
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
コード例 #2
0
def write_stl_file(a_shape,
                   filename,
                   mode="ascii",
                   linear_deflection=0.9,
                   angular_deflection=0.5):
    """ export the shape to a STL file
    Be careful, the shape first need to be explicitely meshed using BRepMesh_IncrementalMesh
    a_shape: the topods_shape to export
    filename: the filename
    mode: optional, "ascii" by default. Can either be "binary"
    linear_deflection: optional, default to 0.001. Lower, more occurate mesh
    angular_deflection: optional, default to 0.5. Lower, more accurate_mesh
    """
    assert not a_shape.IsNull()
    assert mode in ["ascii", "binary"]
    if os.path.isfile(filename):
        print("Warning: %s file already exists and will be replaced" %
              filename)
    # first mesh the shape
    mesh = BRepMesh_IncrementalMesh(a_shape, linear_deflection, False,
                                    angular_deflection, True)
    #mesh.SetDeflection(0.05)
    mesh.Perform()
    assert mesh.IsDone()

    stl_exporter = StlAPI_Writer()
    if mode == "ascii":
        stl_exporter.SetASCIIMode(True)
    else:  # binary, just set the ASCII flag to False
        stl_exporter.SetASCIIMode(False)
    stl_exporter.Write(a_shape, filename)

    assert os.path.isfile(filename)
コード例 #3
0
def export_stl_file(shape, filename, tolerance=1e-4):
    """Exports a shape to a STL mesh file.  The mesh is automatically
    computed prior to export and the resolution/tolerance of the mesh
    can optionally be changed from the default of 1e-4"""
    mesh = BRepMesh_IncrementalMesh(shape.val().wrapped, tolerance, True)
    mesh.Perform()
    writer = StlAPI_Writer()
    writer.Write(shape.val().wrapped, filename)
コード例 #4
0
def _to_stl(shp, path, delta):
    path = os.path.expanduser(path)

    mesh = BRepMesh_IncrementalMesh(shp.Shape(), delta)

    if mesh.IsDone() is False:
        return False

    stl_writer = StlAPI_Writer()
    stl_writer.Write(shp.Shape(), path)
    return True
コード例 #5
0
def getStl(g, step=0.6):
    global geom_counter
    geom_counter = geom_counter + 1
    name_base = "./tmp_g_" + str(fem_counter)
    stl_file = name_base + ".stl"
    mesh = BRepMesh_IncrementalMesh(g, step)
    mesh.Perform()
    stl_exporter = StlAPI_Writer()
    stl_exporter.SetASCIIMode(
        True)  # change to False if you need binary export
    stl_exporter.Write(g, stl_file)
    return stl_file
コード例 #6
0
def _triangulate_face(shp, deflection):
    mesh = BRepMesh_IncrementalMesh(shp.Shape(), deflection)

    reverse_orientation = shp.Face().Orientation() == TopAbs_REVERSED

    L = TopLoc_Location()
    triangulation = BRep_Tool.Triangulation(shp.Face(), L)

    Nodes = triangulation.Nodes()
    Triangles = triangulation.Triangles()

    triangles = []
    for i in range(1, triangulation.NbTriangles() + 1):
        tri = Triangles(i)
        a, b, c = tri.Get()

        if reverse_orientation:
            triangles.append((b - 1, a - 1, c - 1))
        else:
            triangles.append((a - 1, b - 1, c - 1))

    nodes = []
    for i in range(1, triangulation.NbNodes() + 1):
        nodes.append(point3(Nodes(i)))

    return nodes, triangles
コード例 #7
0
    def __init__(self, shape1, shape2, pnt=None, tol=-1.):
        shape = IntersectShapes(shape1, shape2).shape

        pnt = CheckGeom.to_point(pnt)

        self._found = False
        self._pln = None
        if pnt is None:
            tool = PlaneByEdges(shape, tol)
            self._found = tool.found
            self._pln = tool.plane
        elif CheckGeom.is_point(pnt):
            edges = shape.edges
            pnts = [pnt]
            for edge in edges:
                BRepMesh_IncrementalMesh(edge.object, 0.001)
                loc = TopLoc_Location()
                poly3d = BRep_Tool.Polygon3D_(edge.object, loc)
                if poly3d.NbNodes == 0:
                    continue
                tcol_pnts = poly3d.Nodes()
                for i in range(1, tcol_pnts.Length() + 1):
                    gp_pnt = tcol_pnts.Value(i)
                    pnt = CheckGeom.to_point(gp_pnt)
                    pnts.append(pnt)
            if len(pnts) < 3:
                raise ValueError('Less than three points to fit a plane.')
            if tol < 0.:
                tol = 1.0e-7
            tool = PlaneByApprox(pnts, tol)
            self._found = True
            self._pln = tool.plane
        else:
            raise TypeError('Invalid input.')
コード例 #8
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)
コード例 #9
0
ファイル: base_occ.py プロジェクト: tnakaicode/OCCGO
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
コード例 #10
0
def triangle_mesh_solid(solid, lin_tol=1e-2, ang_tol=0.5):
    """Computes a triangular mesh for a solid using BRepMesh.
    The resolution or quality of the mesh approximation can be
    adjusted with lin_tol and ang_tol (linear and angular tolerances).
    The computed mesh is returned as a tuple of lists:
       triangles - a list of each triangles' 3x vertices
                   represented as indexes into the vertices list
       vertices - a list of the mesh's 3D vertices
    """
    if isinstance(solid, Solid):
        obj = [solid.wrapped]
    elif isinstance(solid, list):
        obj = [x.wrapped for x in solid]
    else:
        obj = [solid]
    vertices = []
    triangles = []
    for o in obj:
        mesh = BRepMesh_IncrementalMesh(o, lin_tol, False, ang_tol)
        mesh.Perform()
        ms = Shape.cast(mesh.Shape())
        bt = BRep_Tool()
        mesh_faces = ms.Faces()
        for mesh_face in mesh_faces:
            face = mesh_face.wrapped
            location = TopLoc_Location()
            facing = bt.Triangulation(face, location)
            tri = facing.Triangles()
            num_tri = facing.NbTriangles()
            vtx = facing.Nodes()
            txf = face.Location().Transformation()
            rev = (True if face.Orientation()
                   == TopAbs_Orientation.TopAbs_REVERSED else False)
            for i in range(1, num_tri + 1):
                idx = list(tri.Value(i).Get())
                ci = [0, 2, 1] if rev else [0, 1, 2]
                for j in ci:
                    pt = [
                        vtx.Value(idx[j]).Transformed(txf).X(),
                        vtx.Value(idx[j]).Transformed(txf).Y(),
                        vtx.Value(idx[j]).Transformed(txf).Z(),
                    ]
                    if pt not in vertices:
                        vertices.append(pt)
                    idx[j] = vertices.index(pt)
                triangles.append(idx)
    return triangles, vertices
コード例 #11
0
ファイル: occ_utils.py プロジェクト: hducg/CADGen
def triangulation_from_shape(shape):
    linear_deflection = 0.01
    angular_deflection = 0.5
    mesh = BRepMesh_IncrementalMesh(shape, linear_deflection, False, angular_deflection, True)
    mesh.Perform()
    assert mesh.IsDone()
    
    pts = []
    uvs = []
    triangles = []
    triangle_faces = []
    faces = list_face(shape)
    offset = 0
    for f in faces:
        aLoc = TopLoc_Location()
        aTriangulation = BRep_Tool().Triangulation(f, aLoc)
        aTrsf = aLoc.Transformation()
        aOrient = f.Orientation()

        aNodes = aTriangulation.Nodes()
        aUVNodes = aTriangulation.UVNodes()
        aTriangles = aTriangulation.Triangles()
        
        for i in range(1, aTriangulation.NbNodes() + 1):
            pt = aNodes.Value(i)
            pt.Transform(aTrsf)
            pts.append([pt.X(),pt.Y(),pt.Z()])
            uv = aUVNodes.Value(i)
            uvs.append([uv.X(),uv.Y()])
        
        for i in range(1, aTriangulation.NbTriangles() + 1):
            n1, n2, n3 = aTriangles.Value(i).Get()
            n1 -= 1
            n2 -= 1
            n3 -= 1
            if aOrient == TopAbs_REVERSED:
                tmp = n1
                n1 = n2
                n2 = tmp
            n1 += offset
            n2 += offset
            n3 += offset
            triangles.append([n1, n2, n3])
            triangle_faces.append(f)
        offset += aTriangulation.NbNodes()

    return pts, uvs, triangles, triangle_faces
コード例 #12
0
    def _fromTopoDS(cls, shape, tol=None, optimal=False):
        '''
        Constructs a bounding box from a TopoDS_Shape
        '''
        tol = TOL if tol is None else tol  # tol = TOL (by default)
        bbox = Bnd_Box()
        bbox.SetGap(tol)
        if optimal:
            raise NotImplementedError
            # brepbndlib_AddOptimal(shape, bbox) #this is 'exact' but expensive - not yet wrapped by PythonOCC
        else:
            mesh = BRepMesh_IncrementalMesh(shape, TOL, True)
            mesh.Perform()
            # this is adds +margin but is faster
            brepbndlib_Add(shape, bbox, True)

        return cls(bbox)
コード例 #13
0
def write_stl(shape, filename, definition=0.1):
    from OCC.Core.StlAPI import StlAPI_Writer
    import os

    directory = os.path.split(__name__)[0]
    stl_output_dir = os.path.abspath(directory)
    assert os.path.isdir(stl_output_dir)

    stl_file = os.path.join(stl_output_dir, filename)

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(False)

    from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
    mesh = BRepMesh_IncrementalMesh(shape, definition)
    mesh.Perform()
    assert mesh.IsDone()

    stl_writer.Write(shape, stl_file)
    assert os.path.isfile(stl_file)
    return stl_file
コード例 #14
0
def get_boundingbox(shape: TopoDS_Shape,
                    tol=1e-6,
                    use_mesh=True) -> Tuple[tuple, tuple]:
    """

    :param shape: TopoDS_Shape or a subclass such as TopoDS_Face the shape to compute the bounding box from
    :param tol: tolerance of the computed boundingbox
    :param use_mesh: a flag that tells whether or not the shape has first to be meshed before the bbox computation.
                     This produces more accurate results
    :return: return the bounding box of the TopoDS_Shape `shape`
    """

    bbox = Bnd_Box()
    bbox.SetGap(tol)
    if use_mesh:
        mesh = BRepMesh_IncrementalMesh()
        mesh.SetParallelDefault(True)
        mesh.SetShape(shape)
        mesh.Perform()
        if not mesh.IsDone():
            raise AssertionError("Mesh not done.")
    brepbndlib_Add(shape, bbox, use_mesh)

    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    return (xmin, ymin, zmin), (xmax, ymax, zmax)
コード例 #15
0
def get_boundingbox(shape, tol=1e-6, use_mesh=True):
    """ return the bounding box of the TopoDS_Shape `shape`
    Parameters
    ----------
    shape : TopoDS_Shape or a subclass such as TopoDS_Face
        the shape to compute the bounding box from
    tol: float
        tolerance of the computed boundingbox
    use_mesh : bool
        a flag that tells whether or not the shape has first to be meshed before the bbox
        computation. This produces more accurate results
    """
    bbox = Bnd_Box()
    bbox.SetGap(tol)
    if use_mesh:
        mesh = BRepMesh_IncrementalMesh()
        mesh.SetParallel(True)
        mesh.SetShape(shape)
        mesh.Perform()
        if not mesh.IsDone():
            raise AssertionError("Mesh not done.")
    brepbndlib_Add(shape, bbox, use_mesh)

    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    return xmin, ymin, zmin, xmax, ymax, zmax, xmax - xmin, ymax - ymin, zmax - zmin
コード例 #16
0
ファイル: dataIO.py プロジェクト: lentychang/rel_pose_ext
def stp2stl(filename, fileIODir, linDeflection=0.1, angDeflection=0.1, solidOnly=True):
    # make sure the path exists otherwise OCE get confused
    assert os.path.isdir(fileIODir)

    nameBase = filename.split('.')[0]

    stpName = os.path.abspath(os.path.join(fileIODir, nameBase + '.stp'))
    modelShp = read_step_file(stpName)
    if solidOnly:
        solids = list(Topo(modelShp).solids())
        modelShp = solids[0]
    mesh = BRepMesh_IncrementalMesh(modelShp, linDeflection)
    mesh.Perform()
    assert mesh.IsDone()

    # set the directory where to output the
    stlName = os.path.abspath(os.path.join(fileIODir, nameBase + '.stl'))

    stl_exporter = StlAPI_Writer()
    stl_exporter.SetASCIIMode(True)  # change to False if you need binary export
    stl_exporter.Write(modelShp, stlName)
    # make sure the program was created
    assert os.path.isfile(stlName)
コード例 #17
0
def write_stl_file(a_shape,
                   filename,
                   mode="ascii",
                   linear_deflection=0.9,
                   angular_deflection=0.5):
    """export the shape to a STL file
    Be careful, the shape first need to be explicitly meshed using BRepMesh_IncrementalMesh
    a_shape: the topods_shape to export
    filename: the filename
    mode: optional, "ascii" by default. Can either be "binary"
    linear_deflection: optional, default to 0.001. Lower, more occurate mesh
    angular_deflection: optional, default to 0.5. Lower, more accurate_mesh
    """
    if a_shape.IsNull():
        raise AssertionError("Shape is null.")
    if mode not in ["ascii", "binary"]:
        raise AssertionError("mode should be either ascii or binary")
    if os.path.isfile(filename):
        print(f"Warning: {filename} already exists and will be replaced")
    # first mesh the shape
    mesh = BRepMesh_IncrementalMesh(a_shape, linear_deflection, False,
                                    angular_deflection, True)
    # mesh.SetDeflection(0.05)
    mesh.Perform()
    if not mesh.IsDone():
        raise AssertionError("Mesh is not done.")

    stl_exporter = StlAPI_Writer()
    if mode == "ascii":
        stl_exporter.SetASCIIMode(True)
    else:  # binary, just set the ASCII flag to False
        stl_exporter.SetASCIIMode(False)
    stl_exporter.Write(a_shape, filename)

    if not os.path.isfile(filename):
        raise IOError("File not written to disk.")
コード例 #18
0
def get_boundingbox(shape: TopoDS_Shape, tol=1e-6, use_mesh=True):
    bbox = Bnd_Box()
    bbox.SetGap(tol)
    if use_mesh:
        mesh = BRepMesh_IncrementalMesh()
        mesh.SetParallelDefault(True)
        mesh.SetShape(shape)
        mesh.Perform()
        if not mesh.IsDone():
            raise AssertionError("Mesh not done.")
    brepbndlib_Add(shape, bbox, use_mesh)

    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    return xmin, ymin, zmin, xmax, ymax, zmax, xmax - xmin, ymax - ymin, zmax - zmin
コード例 #19
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)
コード例 #20
0
def z_max_finder(stl_shp,tol=1e-6,use_mesh=True):
    """first change the model to mesh form in order to get an
    accurate MAX and Min bounfing box from topology"""
    bbox = Bnd_Box()
    bbox.SetGap(tol)
    if use_mesh:
        mesh = BRepMesh_IncrementalMesh()
        mesh.SetParallelDefault(True)
        mesh.SetShape(stl_shp)
        mesh.Perform()
        if not mesh.IsDone():
            raise AssertionError("Mesh not done.")
    brepbndlib_Add(stl_shp, bbox, use_mesh)
    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    return zmax
コード例 #21
0
ファイル: cad.py プロジェクト: mmorse1217/cadmesh
def get_boundingbox(shape, tol=1e-6, use_mesh=True):
    bbox = Bnd_Box()
    bbox.SetGap(tol)
    if use_mesh:
        mesh = BRepMesh_IncrementalMesh()
        mesh.SetParallel(True)
        mesh.SetShape(shape)
        mesh.Perform()
        assert mesh.IsDone()
    brepbndlib_Add(shape, bbox, use_mesh)

    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    return [
        xmin, ymin, zmin, xmax, ymax, zmax, xmax - xmin, ymax - ymin,
        zmax - zmin
    ]
コード例 #22
0
    def test_NCollection_Datamap_extension(self) -> None:
        """ NCollection_DataMap class adds a Keys() method that return keys in a Python List
        """
        box1 = BRepPrimAPI_MakeBox(gp_Pnt(0, 0, 0), gp_Pnt(20, 20, 20)).Shape()
        box2 = BRepPrimAPI_MakeBox(gp_Pnt(10, 10, 10), gp_Pnt(30, 30, 30)).Shape()

        # Create meshes for the proximity algorithm
        deflection = 1e-3
        mesher1 = BRepMesh_IncrementalMesh(box1, deflection)
        mesher2 = BRepMesh_IncrementalMesh(box2, deflection)
        mesher1.Perform()
        mesher2.Perform()

        # Perform shape proximity check
        tolerance = 0.1
        isect_test = BRepExtrema_ShapeProximity(box1, box2, tolerance)
        isect_test.Perform()

        # Get intersect faces from Shape1
        overlaps1 = isect_test.OverlapSubShapes1()
        face_indices1 = overlaps1.Keys()
        self.assertEqual(face_indices1, [1, 3, 5])
コード例 #23
0
from OCC.Core.gp import gp_Pnt
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
from OCC.Core.BRepExtrema import BRepExtrema_ShapeProximity
from OCC.Display.SimpleGui import init_display

display, start_display, add_menu, add_function_to_menu = init_display()

# create two boxes that intersect
box1 = BRepPrimAPI_MakeBox(gp_Pnt(0, 0, 0), gp_Pnt(20, 20, 20)).Shape()
box2 = BRepPrimAPI_MakeBox(gp_Pnt(10, 10, 10), gp_Pnt(30, 30, 30)).Shape()

# Create meshes for the proximity algorithm
deflection = 1e-3
mesher1 = BRepMesh_IncrementalMesh(box1, deflection)
mesher2 = BRepMesh_IncrementalMesh(box2, deflection)
mesher1.Perform()
mesher2.Perform()

# Perform shape proximity check
tolerance = 0.1
isect_test = BRepExtrema_ShapeProximity(box1, box2, tolerance)
isect_test.Perform()

# Get intersect faces from Shape1
overlaps1 = isect_test.OverlapSubShapes1()
face_indices1 = overlaps1.Keys()
shape_1_faces = []
for ind in face_indices1:
    face = isect_test.GetSubShape1(ind)
コード例 #24
0
ファイル: cad.py プロジェクト: mmorse1217/cadmesh
def mesh_model(model, res_path, convert=True, all_edges=True):
    fil = model.split("/")[-1][:-5]
    folder = "/".join(model.split("/")[:-1])
    with fileinput.FileInput(model, inplace=True) as fi:
        for line in fi:
            print(line.replace(
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )",
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )"
            ),
                  end='')

    occ_steps = read_step_file(model)
    bt = BRep_Tool()

    for occ_cnt in range(len(occ_steps)):
        if convert:
            try:
                nurbs_converter = BRepBuilderAPI_NurbsConvert(
                    occ_steps[occ_cnt])
                nurbs_converter.Perform(occ_steps[occ_cnt])
                nurbs = nurbs_converter.Shape()
            except:
                print("Conversion failed")
                continue
        else:
            nurbs = occ_steps[occ_cnt]

        mesh = BRepMesh_IncrementalMesh(occ_steps[occ_cnt], 0.9, False, 0.5,
                                        True)
        mesh.Perform()
        if not mesh.IsDone():
            print("Mesh is not done.")
            continue

        occ_topo = TopologyExplorer(nurbs)
        occ_top = Topo(nurbs)
        occ_topo1 = TopologyExplorer(occ_steps[occ_cnt])
        occ_top1 = Topo(occ_steps[occ_cnt])

        d1_feats = []
        d2_feats = []
        t_curves = []
        tr_curves = []
        stats = {}
        stats["model"] = model
        total_edges = 0
        total_surfs = 0
        stats["curves"] = []
        stats["surfs"] = []
        c_cnt = 0
        t_cnt = 0

        # Iterate over edges
        for edge in occ_topo.edges():
            curve = BRepAdaptor_Curve(edge)
            stats["curves"].append(edge_map[curve.GetType()])
            d1_feat = convert_curve(curve)

            if edge_map[curve.GetType()] == "Other":
                continue

            for f in occ_top.faces_from_edge(edge):
                if f == None:
                    print("Broken face")
                    continue
                su = BRepAdaptor_Surface(f)
                c = BRepAdaptor_Curve2d(edge, f)
                t_curve = {
                    "surface": f,
                    "3dcurve": edge,
                    "3dcurve_id": c_cnt,
                    "2dcurve_id": t_cnt
                }
                t_curves.append(t_curve)
                tr_curves.append(convert_2dcurve(c))
                t_cnt += 1

            d1_feats.append(d1_feat)
            c_cnt += 1
            total_edges += 1

        patches = []
        faces1 = list(occ_topo1.faces())
        # Iterate over faces
        for fci, face in enumerate(occ_topo.faces()):
            surf = BRepAdaptor_Surface(face)
            stats["surfs"].append(surf_map[surf.GetType()])
            d2_feat = convert_surface(surf)

            if surf_map[surf.GetType()] == "Other":
                continue

            for tc in t_curves:
                if tc["surface"] == face:
                    patch = {
                        "3dcurves": [],
                        "2dcurves": [],
                        "orientations": [],
                        "surf_orientation": face.Orientation(),
                        "wire_ids": [],
                        "wire_orientations": []
                    }

                    for wc, fw in enumerate(occ_top.wires_from_face(face)):
                        patch["wire_orientations"].append(fw.Orientation())
                        if all_edges:
                            edges = [
                                i for i in WireExplorer(fw).ordered_edges()
                            ]
                        else:
                            edges = list(occ_top.edges_from_wire(fw))
                        for fe in edges:
                            for ttc in t_curves:
                                if ttc["3dcurve"].IsSame(fe) and tc[
                                        "surface"] == ttc["surface"]:
                                    patch["3dcurves"].append(ttc["3dcurve_id"])
                                    patch["2dcurves"].append(ttc["2dcurve_id"])
                                    patch["wire_ids"].append(wc)
                                    orientation = fe.Orientation()
                                    patch["orientations"].append(orientation)

                    patches.append(patch)
                    break

            location = TopLoc_Location()
            facing = (bt.Triangulation(faces1[fci], location))
            if facing != None:
                tab = facing.Nodes()
                tri = facing.Triangles()
                verts = []
                for i in range(1, facing.NbNodes() + 1):
                    verts.append(list(tab.Value(i).Coord()))

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

                os.makedirs(res_path, exist_ok=True)
                igl.write_triangle_mesh(
                    "%s/%s_%03i_mesh_%04i.obj" % (res_path, fil, occ_cnt, fci),
                    np.array(verts), np.array(faces))
                d2_feat["faces"] = faces
                d2_feat["verts"] = verts
            else:
                print("Missing triangulation")
                continue

            d2_feats.append(d2_feat)
            total_surfs += 1

        bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=False)
        xmin, ymin, zmin, xmax, ymax, zmax = bbox[:6]
        bbox1 = [
            "%.2f" % xmin,
            "%.2f" % ymin,
            "%.2f" % zmin,
            "%.2f" % xmax,
            "%.2f" % ymax,
            "%.2f" % zmax,
            "%.2f" % (xmax - xmin),
            "%.2f" % (ymax - ymin),
            "%.2f" % (zmax - zmin)
        ]
        stats["#edges"] = total_edges
        stats["#surfs"] = total_surfs

        # Fix possible orientation problems
        if convert:
            for p in patches:

                # Check orientation of first curve
                if len(p["2dcurves"]) >= 2:
                    cur = tr_curves[p["2dcurves"][0]]
                    nxt = tr_curves[p["2dcurves"][1]]
                    c_ori = p["orientations"][0]
                    n_ori = p["orientations"][1]
                    if c_ori == 0:
                        pole0 = np.array(cur["poles"][0])
                        pole1 = np.array(cur["poles"][-1])
                    else:
                        pole0 = np.array(cur["poles"][-1])
                        pole1 = np.array(cur["poles"][0])

                    if n_ori == 0:
                        pole2 = np.array(nxt["poles"][0])
                        pole3 = np.array(nxt["poles"][-1])
                    else:
                        pole2 = np.array(nxt["poles"][-1])
                        pole3 = np.array(nxt["poles"][0])

                    d02 = np.abs(pole0 - pole2)
                    d12 = np.abs(pole1 - pole2)
                    d03 = np.abs(pole0 - pole3)
                    d13 = np.abs(pole1 - pole3)

                    amin = np.argmin([d02, d12, d03, d13])

                    if amin == 0 or amin == 2:  # Orientation of first curve incorrect, fix
                        p["orientations"][0] = abs(c_ori - 1)

                # Fix all orientations
                for i in range(len(p["2dcurves"]) - 1):
                    cur = tr_curves[p["2dcurves"][i]]
                    nxt = tr_curves[p["2dcurves"][i + 1]]
                    c_ori = p["orientations"][i]
                    n_ori = p["orientations"][i + 1]
                    if c_ori == 0:
                        pole1 = np.array(cur["poles"][-1])
                    else:
                        pole1 = np.array(cur["poles"][0])

                    if n_ori == 0:
                        pole2 = np.array(nxt["poles"][0])
                        pole3 = np.array(nxt["poles"][-1])
                    else:
                        pole2 = np.array(nxt["poles"][-1])
                        pole3 = np.array(nxt["poles"][0])

                    d12 = np.abs(pole1 - pole2)
                    d13 = np.abs(pole1 - pole3)

                    amin = np.min([d12, d13])

                    if amin == 1:  # Incorrect orientation, flip
                        p["orientations"][i + 1] = abs(n_ori - 1)

        features = {
            "curves": d1_feats,
            "surfaces": d2_feats,
            "trim": tr_curves,
            "topo": patches,
            "bbox": bbox1
        }

        os.makedirs(res_path, exist_ok=True)
        fip = fil + "_features2"
        with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili:
            yaml.dump(features, fili, indent=2)

        fip = fil + "_features"
        with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili:
            features2 = copy.deepcopy(features)
            for sf in features2["surfaces"]:
                del sf["faces"]
                del sf["verts"]
            yaml.dump(features2, fili, indent=2)


#        res_path = folder.replace("/step/", "/stat/")
#        fip = fil + "_stats"
#        with open("%s/%s_%03i.yml"%(res_path, fip, occ_cnt), "w") as fili:
#            yaml.dump(stats, fili, indent=2)

    print("Writing results for %s with %i parts." % (model, len(occ_steps)))
コード例 #25
0
ファイル: nsided.py プロジェクト: compas-dev/compas_occ
# Surface from BRep Filling Face
# ==============================================================================

face = nsided.Face()
surface = OCCNurbsSurface.from_face(face)

# ==============================================================================
# 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
コード例 #26
0
    def plot(self, plot_file=None, save_fig=False):
        """
        Method to plot a file. If `plot_file` is not given it plots
        `self.shape`.

        :param string plot_file: the filename you want to plot.
        :param bool save_fig: a flag to save the figure in png or not.
            If True the plot is not shown.

        :return: figure: matlplotlib structure for the figure of the
            chosen geometry
        :rtype: matplotlib.pyplot.figure
        """
        if plot_file is None:
            shape = self.shape
            plot_file = self.infile
        else:
            shape = self.load_shape_from_file(plot_file)

        stl_writer = StlAPI_Writer()
        # Do not switch SetASCIIMode() from False to True.
        stl_writer.SetASCIIMode(False)

        # Necessary to write to STL [to check]
        stl_mesh = BRepMesh_IncrementalMesh(shape, 0.01)
        stl_mesh.Perform()

        f = stl_writer.Write(shape, 'aux_figure.stl')

        # Create a new plot
        figure = pyplot.figure()
        axes = mplot3d.Axes3D(figure)

        # Load the STL files and add the vectors to the plot
        stl_mesh = mesh.Mesh.from_file('aux_figure.stl')
        os.remove('aux_figure.stl')
        axes.add_collection3d(
            mplot3d.art3d.Poly3DCollection(stl_mesh.vectors / 1000))

        # Get the limits of the axis and center the geometry
        max_dim = np.array([\
            np.max(stl_mesh.vectors[:, :, 0]) / 1000,\
            np.max(stl_mesh.vectors[:, :, 1]) / 1000,\
            np.max(stl_mesh.vectors[:, :, 2]) / 1000])
        min_dim = np.array([\
            np.min(stl_mesh.vectors[:, :, 0]) / 1000,\
            np.min(stl_mesh.vectors[:, :, 1]) / 1000,\
            np.min(stl_mesh.vectors[:, :, 2]) / 1000])

        max_lenght = np.max(max_dim - min_dim)
        axes.set_xlim(\
            -.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2,\
            .6 * max_lenght + (max_dim[0] + min_dim[0]) / 2)
        axes.set_ylim(\
            -.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2,\
            .6 * max_lenght + (max_dim[1] + min_dim[1]) / 2)
        axes.set_zlim(\
            -.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2,\
            .6 * max_lenght + (max_dim[2] + min_dim[2]) / 2)

        # Show the plot to the screen
        if not save_fig:
            pyplot.show()
        else:
            figure.savefig(plot_file.split('.')[0] + '.png')

        return figure
コード例 #27
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
コード例 #28
0
ファイル: CutSurf_Trim.py プロジェクト: tnakaicode/GeomSurf
    poly2_proj = obj.proj_rim_pln(poly2, face2, axis1)
    print(face2, u0, u0, v0, v1)
    # write_stl_file(face2_stl, obj.tempname + "_face2_001.stp",
    #               linear_deflection=0.1, angular_deflection=0.1)
    # write_stl_file(face2_stl, obj.tempname + "_face2_002.stp",
    #               linear_deflection=0.001, angular_deflection=0.001)

    surf2_trim = Geom_RectangularTrimmedSurface(surf2, 0.1, 0.8, 0.5, 0.7,
                                                True, True)

    face3 = read_step_file("surf1.step")
    print(face3)
    #surf3 = BRep_Tool.Surface(face3)
    # print(surf3)

    mesh = BRepMesh_IncrementalMesh(face2, 0.01, True, 0.01, True)
    mesh.Perform()
    face3_mesh = mesh.Shape()

    obj.display.DisplayShape(surf1, color="BLUE", transparency=0.5)
    obj.display.DisplayShape(poly1)
    obj.display.DisplayShape(poly1_proj)
    obj.display.DisplayShape(face1_holl, color="GREEN", transparency=0.5)
    #obj.display.DisplayShape(face1_trim, color="BLACK", transparency=0.5)
    obj.display.DisplayShape(surf2, color="RED", transparency=0.9)
    obj.display.DisplayShape(poly2)
    obj.display.DisplayShape(poly2_proj)
    obj.display.DisplayShape(face3, color="YELLOW", transparency=0.9)
    obj.display.DisplayShape(surf2_trim, color="RED", transparency=0.5)
    obj.display.DisplayShape(surf2_uiso)
    obj.display.DisplayShape(surf2_viso)