예제 #1
0
def vertex_fillet(cube, vert):
    # apply a fillet on incident edges on a vertex
    afillet = BRepFilletAPI_MakeFillet(cube)
    cnt = 0
    # find edges from vertex
    _map = TopTools_IndexedDataMapOfShapeListOfShape()
    topexp_MapShapesAndAncestors(cube, TopAbs_VERTEX, TopAbs_EDGE, _map)
    results = _map.FindFromKey(vert)
    topology_iterator = TopTools_ListIteratorOfListOfShape(results)
    while topology_iterator.More():
        edge = topods_Edge(topology_iterator.Value())
        topology_iterator.Next()
        first, last = topexp_FirstVertex(edge), topexp_LastVertex(edge)
        vertex, first_vert, last_vert = BRep_Tool().Pnt(vert), BRep_Tool().Pnt(
            first), BRep_Tool().Pnt(last)
        if edge.Orientation():
            if not vertex.IsEqual(first_vert, 0.001):
                afillet.Add(0, 20., edge)
            else:
                afillet.Add(20, 0, edge)
        cnt += 1
    afillet.Build()
    if afillet.IsDone():
        return afillet.Shape()
    else:
        raise AssertionError('you failed on me you fool!')
예제 #2
0
def poles_from_bsplinecurve_edge(occedge):
    """
    This function fetches the poles of a bspline OCCedge.
 
    Parameters
    ----------
    occedge : OCCedge
        The OCCedge to be examined. The OCCedge needs to contain a bspline curve
        
    Returns
    -------
    List of poles : pyptlist
        List of poles of the bspline curve
    """
    adaptor = BRepAdaptor_Curve(occedge)
    adaptor_handle = BRepAdaptor_HCurve(adaptor)
    handle_bspline = Handle_Geom_BSplineCurve()
    bspline = handle_bspline.DownCast(adaptor.Curve().Curve()).GetObject()

    npoles =  bspline.NbPoles()
    polelist = []
    for np in range(npoles):
        pole = bspline.Pole(np+1)
        pypole = (pole.X(), pole.Y(), pole.Z())
        polelist.append(pypole)
        
    if topods_Edge(occedge).Orientation() == TopAbs_REVERSED:
        polelist.reverse()

    return polelist
예제 #3
0
def occ_topo_list(shape):
    """ return the edges & faces from `shape`

    :param shape: a TopoDS_Shape
    :return: a list of edges and faces
    """

    from OCC.TopAbs import TopAbs_FACE
    from OCC.TopAbs import TopAbs_EDGE
    from OCC.TopExp import TopExp_Explorer
    from OCC.TopoDS import topods_Face, topods_Edge


    topExp = TopExp_Explorer()
    topExp.Init(shape, TopAbs_FACE)
    faces = []
    edges = []

    while topExp.More():
        face = topods_Face(topExp.Current())
        faces.append(face)
        topExp.Next()

    topExp.Init(shape, TopAbs_EDGE)

    while topExp.More():
        edge = topods_Edge(topExp.Current())
        edges.append(edge)
        topExp.Next()

    return faces, edges
예제 #4
0
    def write_edge(points_edge, topo_edge):
        """
        Method to recreate an Edge associated to a geometric curve
        after the modification of its points.
        :param points_edge: the deformed points array.
        :param topo_edge: the Edge to be modified
        :return: Edge (Shape)

        :rtype: TopoDS_Edge

        """
        # convert Edge to Geom B-spline Curve
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_edge)
        nurbs_converter.Perform(topo_edge)
        nurbs_curve = nurbs_converter.Shape()
        topo_curve = topods_Edge(nurbs_curve)
        h_geomcurve = BRep_Tool.Curve(topo_curve)[0]
        h_bcurve = geomconvert_CurveToBSplineCurve(h_geomcurve)
        bspline_edge_curve = h_bcurve.GetObject()

        # Edge geometric properties
        nb_cpt = bspline_edge_curve.NbPoles()
        # check consistency
        if points_edge.shape[0] != nb_cpt:
            raise ValueError("Input control points do not have not have the "
                             "same number as the geometric edge!")

        else:
            for i in range(1, nb_cpt + 1):
                cpt = points_edge[i - 1]
                bspline_edge_curve.SetPole(i, gp_Pnt(cpt[0], cpt[1], cpt[2]))

        new_edge = BRepBuilderAPI_MakeEdge(bspline_edge_curve.GetHandle())

        return new_edge.Edge()
예제 #5
0
def mesh_edge(a_topods_edge):
    """ Take a TopoDS_Edge and returns a list of points
    """
    edg = topods_Edge(a_topods_edge)
    assert not edg.IsNull()  # This might be to remove
    # build a curve from the edge
    curve_handle, U1, U2 = BRep_Tool_Curve(edg)
    curve = curve_handle.GetObject()
    if curve is None:
        return False
    IS_LINE = curve.IsInstance('Geom_Line')
    points = []
    if IS_LINE:
        p1 = curve.Value(U1)
        p2 = curve.Value(U2)
        points.append(p1.Coord())
        points.append(p2.Coord())
    else:
        U = U1
        nbp = 10  # this is related to edge quality. TODO: compute the best quality
        dU = (U2 - U1)/nbp
        while U <= U2:
            p = curve.Value(U)
            points.append(p.Coord())
            U += dU
    return points
예제 #6
0
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
예제 #7
0
    def write_edge(points_edge, topo_edge):
        """
        Method to recreate an Edge associated to a geometric curve
        after the modification of its points.
        :param points_edge: the deformed points array.
        :param topo_edge: the Edge to be modified
        :return: Edge (Shape)

        :rtype: TopoDS_Edge

        """
        # convert Edge to Geom B-spline Curve
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_edge)
        nurbs_converter.Perform(topo_edge)
        nurbs_curve = nurbs_converter.Shape()
        topo_curve = topods_Edge(nurbs_curve)
        h_geomcurve = BRep_Tool.Curve(topo_curve)[0]
        h_bcurve = geomconvert_CurveToBSplineCurve(h_geomcurve)
        bspline_edge_curve = h_bcurve.GetObject()

        # Edge geometric properties
        nb_cpt = bspline_edge_curve.NbPoles()
        # check consistency
        if points_edge.shape[0] != nb_cpt:
            raise ValueError("Input control points do not have not have the "
                             "same number as the geometric edge!")

        else:
            for i in range(1, nb_cpt + 1):
                cpt = points_edge[i - 1]
                bspline_edge_curve.SetPole(i, gp_Pnt(cpt[0], cpt[1], cpt[2]))

        new_edge = BRepBuilderAPI_MakeEdge(bspline_edge_curve.GetHandle())

        return new_edge.Edge()
예제 #8
0
def occ_topo_list(shape):
    """ return the edges & faces from `shape`

    :param shape: a TopoDS_Shape
    :return: a list of edges and faces
    """

    from OCC.TopAbs import TopAbs_FACE
    from OCC.TopAbs import TopAbs_EDGE
    from OCC.TopExp import TopExp_Explorer
    from OCC.TopoDS import topods_Face, topods_Edge

    topExp = TopExp_Explorer()
    topExp.Init(shape, TopAbs_FACE)
    faces = []
    edges = []

    while topExp.More():
        face = topods_Face(topExp.Current())
        faces.append(face)
        topExp.Next()

    topExp.Init(shape, TopAbs_EDGE)

    while topExp.More():
        edge = topods_Edge(topExp.Current())
        edges.append(edge)
        topExp.Next()

    return faces, edges
예제 #9
0
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
예제 #10
0
def iter_edges(shape):
    """
    Generator / Iterator over the edges of a shape
    """

    exp = TopExp_Explorer(shape, TopAbs_EDGE)
    while exp.More():
        yield topods_Edge(exp.Current())
        exp.Next()
예제 #11
0
def iter_edges_from_wire(wire):
    """
    Generator / Iterator over the edges of a wire

    Compared to iter_edges, it preserves the order
    of the edges.
    """
    exp = BRepTools_WireExplorer(wire)
    while exp.More():
        yield topods_Edge(exp.Current())
        exp.Next()
예제 #12
0
def get_edges(_shape):
    """ return the edges from `_shape`

    :param _shape: TopoDS_Shape, or a subclass like TopoDS_Solid
    :return: a list of edges found in `_shape`
    """
    topExp = TopExp_Explorer()
    topExp.Init(_shape, TopAbs_EDGE)
    _edges = []

    while topExp.More():
        edge = topods_Edge(topExp.Current())
        _edges.append(edge)
        topExp.Next()

    return _edges
예제 #13
0
def shape2shapetype(occ_shape):
    shapetype = occ_shape.ShapeType()
    if shapetype == TopAbs_COMPOUND:  #compound
        orig_topo = topods_Compound(occ_shape)
    if shapetype == TopAbs_COMPSOLID:  #compsolid
        orig_topo = topods_CompSolid(occ_shape)
    if shapetype == TopAbs_SOLID:  #solid
        orig_topo = topods_Solid(occ_shape)
    if shapetype == TopAbs_SHELL:  #shell
        orig_topo = topods_Shell(occ_shape)
    if shapetype == TopAbs_FACE:  #face
        orig_topo = topods_Face(occ_shape)
    if shapetype == TopAbs_WIRE:  #wire
        orig_topo = topods_Wire(occ_shape)
    if shapetype == TopAbs_EDGE:  #edge
        orig_topo = topods_Edge(occ_shape)
    if shapetype == TopAbs_VERTEX:  #vertex
        orig_topo = topods_Vertex(occ_shape)
    return orig_topo
예제 #14
0
def geom_explorer(geom2explore, shapetype2find):
    geom_list = []
    if shapetype2find == "compound":
        shapetype2find_topABS = TopAbs_COMPOUND
    if shapetype2find == "compsolid":
        shapetype2find_topABS = TopAbs_COMPSOLID
    if shapetype2find == "solid":
        shapetype2find_topABS = TopAbs_SOLID
    if shapetype2find == "shell":
        shapetype2find_topABS = TopAbs_SHELL
    if shapetype2find == "face":
        shapetype2find_topABS = TopAbs_FACE
    if shapetype2find == "wire":
        shapetype2find_topABS = TopAbs_WIRE
    if shapetype2find == "edge":
        shapetype2find_topABS = TopAbs_EDGE
    if shapetype2find == "vertex":
        shapetype2find_topABS = TopAbs_VERTEX

    ex = TopExp_Explorer(geom2explore, 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
예제 #15
0
def poles_from_bsplinecurve_edge(occedge):
    '''
    occedge: the edge to be measured
    type: occedge
    '''
    #occutil_edge = edge.Edge(occedge)
    adaptor = BRepAdaptor_Curve(occedge)
    adaptor_handle = BRepAdaptor_HCurve(adaptor)
    handle_bspline = Handle_Geom_BSplineCurve()
    bspline = handle_bspline.DownCast(adaptor.Curve().Curve()).GetObject()

    npoles = bspline.NbPoles()
    polelist = []
    for np in range(npoles):
        pole = bspline.Pole(np + 1)
        pypole = (pole.X(), pole.Y(), pole.Z())
        polelist.append(pypole)

    if topods_Edge(occedge).Orientation() == TopAbs_REVERSED:
        polelist.reverse()

    return polelist
예제 #16
0
def discretize(shape, tol):
    """This method discretizes the OpenCascade shape.

    :param shape: Shape to discretize
    :type shape:
    :return: discretized face; profile coordinates; id of the surface the\
    coordinates belong to
    :rtype: OCC.TopoDS.TopoDS_Compound; numpy.ndarray; numpy.ndarray
    """
    BRepMesh_IncrementalMesh(shape, tol, False, 5)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_EDGE)
    edge_coords = np.zeros([0, 3])
    edge_ids = np.zeros([0], dtype=int)
    edge_id = 0
    while ex.More():
        edge = topods_Edge(ex.Current())
        location = TopLoc_Location()
        edging = (bt.Polygon3D(edge, location)).GetObject()
        tab = edging.Nodes()
        for i in range(1, edging.NbNodes() + 1):
            p = tab.Value(i)
            edge_coords = np.append(edge_coords,
                                    [[p.X(), p.Y(), p.Z()]],
                                    axis=0)
            edge_ids = np.append(edge_ids, edge_id)
            mv = BRepBuilderAPI_MakeVertex(p)
            if mv.IsDone():
                builder.Add(comp, mv.Vertex())
        edge_id += 1
        ex.Next()

    edge_coords = np.round(edge_coords, 8)
    return edge_coords, edge_ids
예제 #17
0
    def write_face(self, points_face, list_points_edge, topo_face, toledge):
        """
        Method to recreate a Face associated to a geometric surface
        after the modification of Face points. It returns a TopoDS_Face.

        :param points_face: the new face points array.
        :param list_points_edge: new edge points
        :param topo_face: the face to be modified
        :param toledge: tolerance on the surface creation after modification
        :return: TopoDS_Face (Shape)

        :rtype: TopoDS_Shape

        """

        # convert Face to Geom B-spline Surface
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face)
        nurbs_converter.Perform(topo_face)
        nurbs_face = nurbs_converter.Shape()
        topo_nurbsface = topods.Face(nurbs_face)
        h_geomsurface = BRep_Tool.Surface(topo_nurbsface)
        h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface)
        bsurface = h_bsurface.GetObject()

        nb_u = bsurface.NbUPoles()
        nb_v = bsurface.NbVPoles()
        # check consistency
        if points_face.shape[0] != nb_u * nb_v:
            raise ValueError("Input control points do not have not have the "
                             "same number as the geometric face!")

        # cycle on the face points
        indice_cpt = 0
        for iu in range(1, nb_u + 1):
            for iv in range(1, nb_v + 1):
                cpt = points_face[indice_cpt]
                bsurface.SetPole(iu, iv, gp_Pnt(cpt[0], cpt[1], cpt[2]))
                indice_cpt += 1

        # create modified new face
        new_bspline_tface = BRepBuilderAPI_MakeFace()
        toler = precision_Confusion()
        new_bspline_tface.Init(bsurface.GetHandle(), False, toler)

        # cycle on the wires
        face_wires_explorer = TopExp_Explorer(
            topo_nurbsface.Oriented(TopAbs_FORWARD), TopAbs_WIRE)
        ind_edge_total = 0

        while face_wires_explorer.More():
            # get old wire
            twire = topods_Wire(face_wires_explorer.Current())

            # cycle on the edges
            ind_edge = 0
            wire_explorer_edge = TopExp_Explorer(
                twire.Oriented(TopAbs_FORWARD), TopAbs_EDGE)
            # check edges order on the wire
            mode3d = True
            tolerance_edges = toledge

            wire_order = ShapeAnalysis_WireOrder(mode3d, tolerance_edges)
            # an edge list
            deformed_edges = []
            # cycle on the edges
            while wire_explorer_edge.More():
                tedge = topods_Edge(wire_explorer_edge.Current())
                new_bspline_tedge = self.write_edge(
                    list_points_edge[ind_edge_total], tedge)

                deformed_edges.append(new_bspline_tedge)
                analyzer = topexp()
                vfirst = analyzer.FirstVertex(new_bspline_tedge)
                vlast = analyzer.LastVertex(new_bspline_tedge)
                pt1 = BRep_Tool.Pnt(vfirst)
                pt2 = BRep_Tool.Pnt(vlast)

                wire_order.Add(pt1.XYZ(), pt2.XYZ())

                ind_edge += 1
                ind_edge_total += 1
                wire_explorer_edge.Next()

            # grouping the edges in a wire, then in the face
            # check edges order and connectivity within the wire
            wire_order.Perform()
            # new wire to be created
            stol = ShapeFix_ShapeTolerance()
            new_bspline_twire = BRepBuilderAPI_MakeWire()
            for order_i in range(1, wire_order.NbEdges() + 1):
                deformed_edge_i = wire_order.Ordered(order_i)
                if deformed_edge_i > 0:
                    # insert the deformed edge to the new wire
                    new_edge_toadd = deformed_edges[deformed_edge_i - 1]
                    stol.SetTolerance(new_edge_toadd, toledge)
                    new_bspline_twire.Add(new_edge_toadd)
                    if new_bspline_twire.Error() != 0:
                        stol.SetTolerance(new_edge_toadd, toledge * 10.0)
                        new_bspline_twire.Add(new_edge_toadd)
                else:
                    deformed_edge_revers = deformed_edges[
                        np.abs(deformed_edge_i) - 1]
                    stol.SetTolerance(deformed_edge_revers, toledge)
                    new_bspline_twire.Add(deformed_edge_revers)
                    if new_bspline_twire.Error() != 0:
                        stol.SetTolerance(deformed_edge_revers, toledge * 10.0)
                        new_bspline_twire.Add(deformed_edge_revers)
            # add new wire to the Face
            new_bspline_tface.Add(new_bspline_twire.Wire())
            face_wires_explorer.Next()

        return topods.Face(new_bspline_tface.Face())
#!/usr/bin/env python
def find_intersected_faces(face, volume1, volume2, hint_face, tolerance=0.00001):
    """
    Try to find bordering faces
    """

    # Get bordering points from face
    primitives0 = brep_explorer.shape_disassembly(face)
    brt = BRep_Tool()
    border_points = []
    for vert_shape in primitives0[7].values():
        vert = topods_Vertex(vert_shape)
        pnt = brt.Pnt(topods_Vertex(vert))
        border_points.append(pnt)

    # Get curves from edges of face
    brt = BRep_Tool()
    curves = []
    for edge_shape in primitives0[6].values():
        edge = topods_Edge(edge_shape)
        curve_handle = brt.Curve(edge)[0]
        curve = curve_handle.GetObject()
        curves.append(curve)

    # Get candidate points from hint_face
    primitives2 = brep_explorer.shape_disassembly(hint_face)
    brt = BRep_Tool()
    cand_points = []
    for vert_shape in primitives2[7].values():
        vert = topods_Vertex(vert_shape)
        pnt = brt.Pnt(topods_Vertex(vert))
        cand_points.append(pnt)

    # Iterate over all curves and try to find intersection points
    inter_points = []
    for curve in curves:
        distances = {}
        # Compute distances between candidate points and curve
        for point in cand_points:
            proj = GeomAPI_ProjectPointOnCurve(point, curve.GetHandle())
            try:
                low_dist = proj.LowerDistance()
            # I tried to find, where does this exception come from: "StdFail_NotDone"
            # but was not able to find it anywhere. So using this wild catching
            except:
                pass
            else:
                distances[low_dist] = point
        # Try to get candidate with lowest distance
        if len(distances) > 0:
            min_dist = min(distances.keys())
            # When distance is lower then tolerance, then we found point at intersection
            if min_dist <= tolerance:
                inter_points.append(distances[min_dist])

    if len(inter_points) == 0:
        return []

    # When some intersection points was found, then extend list of border points
    # with these intersection points
    border_points.extend(inter_points)

    border_coords = [(pnt.X(), pnt.Y(), pnt.Z()) for pnt in border_points]

    # Get list of all faces in volumes
    primitives3 = brep_explorer.shapes_disassembly((volume1, volume2))
    brt = BRep_Tool()
    border_faces = []
    for face_shape in primitives3[4].values():
        face_traverse = traverse.Topo(face_shape)
        vertices = face_traverse.vertices_from_face(face_shape)
        face_coords = []
        for vert in vertices:
            pnt = brt.Pnt(topods_Vertex(vert))
            face_coords.append((pnt.X(), pnt.Y(), pnt.Z()))
        
        # TODO: use better check in coordinates matches then: `coo in border_coords`
        # e.g.: use some distance and tolerance
        res = [coo in border_coords for coo in face_coords]
        if all(res) is True:
            border_faces.append(face_shape)

    # TODO: Check if these faces covers original face completely

    return border_faces
예제 #20
0
    def write_face(self, points_face, list_points_edge, topo_face, toledge):
        """
        Method to recreate a Face associated to a geometric surface
        after the modification of Face points. It returns a TopoDS_Face.

        :param points_face: the new face points array.
        :param list_points_edge: new edge points
        :param topo_face: the face to be modified
        :param toledge: tolerance on the surface creation after modification
        :return: TopoDS_Face (Shape)

        :rtype: TopoDS_Shape

        """

        # convert Face to Geom B-spline Surface
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face)
        nurbs_converter.Perform(topo_face)
        nurbs_face = nurbs_converter.Shape()
        topo_nurbsface = topods.Face(nurbs_face)
        h_geomsurface = BRep_Tool.Surface(topo_nurbsface)
        h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface)
        bsurface = h_bsurface.GetObject()

        nb_u = bsurface.NbUPoles()
        nb_v = bsurface.NbVPoles()
        # check consistency
        if points_face.shape[0] != nb_u * nb_v:
            raise ValueError("Input control points do not have not have the "
                             "same number as the geometric face!")

        # cycle on the face points
        indice_cpt = 0
        for iu in range(1, nb_u + 1):
            for iv in range(1, nb_v + 1):
                cpt = points_face[indice_cpt]
                bsurface.SetPole(iu, iv, gp_Pnt(cpt[0], cpt[1], cpt[2]))
                indice_cpt += 1

        # create modified new face
        new_bspline_tface = BRepBuilderAPI_MakeFace()
        toler = precision_Confusion()
        new_bspline_tface.Init(bsurface.GetHandle(), False, toler)

        # cycle on the wires
        face_wires_explorer = TopExp_Explorer(
            topo_nurbsface.Oriented(TopAbs_FORWARD), TopAbs_WIRE)
        ind_edge_total = 0

        while face_wires_explorer.More():
            # get old wire
            twire = topods_Wire(face_wires_explorer.Current())

            # cycle on the edges
            ind_edge = 0
            wire_explorer_edge = TopExp_Explorer(
                twire.Oriented(TopAbs_FORWARD), TopAbs_EDGE)
            # check edges order on the wire
            mode3d = True
            tolerance_edges = toledge

            wire_order = ShapeAnalysis_WireOrder(mode3d, tolerance_edges)
            # an edge list
            deformed_edges = []
            # cycle on the edges
            while wire_explorer_edge.More():
                tedge = topods_Edge(wire_explorer_edge.Current())
                new_bspline_tedge = self.write_edge(
                    list_points_edge[ind_edge_total], tedge)

                deformed_edges.append(new_bspline_tedge)
                analyzer = topexp()
                vfirst = analyzer.FirstVertex(new_bspline_tedge)
                vlast = analyzer.LastVertex(new_bspline_tedge)
                pt1 = BRep_Tool.Pnt(vfirst)
                pt2 = BRep_Tool.Pnt(vlast)

                wire_order.Add(pt1.XYZ(), pt2.XYZ())

                ind_edge += 1
                ind_edge_total += 1
                wire_explorer_edge.Next()

            # grouping the edges in a wire, then in the face
            # check edges order and connectivity within the wire
            wire_order.Perform()
            # new wire to be created
            stol = ShapeFix_ShapeTolerance()
            new_bspline_twire = BRepBuilderAPI_MakeWire()
            for order_i in range(1, wire_order.NbEdges() + 1):
                deformed_edge_i = wire_order.Ordered(order_i)
                if deformed_edge_i > 0:
                    # insert the deformed edge to the new wire
                    new_edge_toadd = deformed_edges[deformed_edge_i - 1]
                    stol.SetTolerance(new_edge_toadd, toledge)
                    new_bspline_twire.Add(new_edge_toadd)
                    if new_bspline_twire.Error() != 0:
                        stol.SetTolerance(new_edge_toadd, toledge * 10.0)
                        new_bspline_twire.Add(new_edge_toadd)
                else:
                    deformed_edge_revers = deformed_edges[
                        np.abs(deformed_edge_i) - 1]
                    stol.SetTolerance(deformed_edge_revers, toledge)
                    new_bspline_twire.Add(deformed_edge_revers)
                    if new_bspline_twire.Error() != 0:
                        stol.SetTolerance(deformed_edge_revers, toledge * 10.0)
                        new_bspline_twire.Add(deformed_edge_revers)
            # add new wire to the Face
            new_bspline_tface.Add(new_bspline_twire.Wire())
            face_wires_explorer.Next()

        return topods.Face(new_bspline_tface.Face())
예제 #21
0
    def write(cls, filename, data, tolerance=1e-6):

        # cycle on the faces to update the control points position
        # init some quantities
        shape = data.shape
        control_point_position = data.control_point_position
        mesh_points = data.points

        faces_explorer = TopExp_Explorer(shape, TopAbs_FACE)
        n_faces = 0
        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.GetObject()

            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[
                        +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.GetHandle(),
                                           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, 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.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()

        IGESControl_Controller_Init()
        writer = IGESControl_Writer()
        writer.AddShape(compound)
        writer.Write(filename)
예제 #22
0
    def parse_face(topo_face):
        """
        Method to parse a single `Face` (a single patch nurbs surface).
        It returns a matrix with all the coordinates of control points of the
        `Face` and a second list with all the control points related to the
        `Edges` of the `Face.`

        :param Face topo_face: the input Face.

        :return: control points of the `Face`, control points related to
            `Edges`.
        :rtype: tuple(numpy.ndarray, list)

        """
        # get some Face - Edge - Vertex data map information
        mesh_points_edge = []
        face_exp_wire = TopExp_Explorer(topo_face, TopAbs_WIRE)
        # loop on wires per face
        while face_exp_wire.More():
            twire = topods_Wire(face_exp_wire.Current())
            wire_exp_edge = TopExp_Explorer(twire, TopAbs_EDGE)
            # loop on edges per wire
            while wire_exp_edge.More():
                edge = topods_Edge(wire_exp_edge.Current())
                bspline_converter = BRepBuilderAPI_NurbsConvert(edge)
                bspline_converter.Perform(edge)
                bspline_tshape_edge = bspline_converter.Shape()
                h_geom_edge = BRep_Tool_Curve(
                    topods_Edge(bspline_tshape_edge))[0]
                h_bspline_edge = geomconvert_CurveToBSplineCurve(h_geom_edge)
                bspline_geom_edge = h_bspline_edge.GetObject()

                nb_poles = bspline_geom_edge.NbPoles()

                # Edge geometric properties
                edge_ctrlpts = TColgp_Array1OfPnt(1, nb_poles)
                bspline_geom_edge.Poles(edge_ctrlpts)

                points_single_edge = np.zeros((0, 3))
                for i in range(1, nb_poles + 1):
                    ctrlpt = edge_ctrlpts.Value(i)
                    ctrlpt_position = np.array(
                        [[ctrlpt.Coord(1),
                          ctrlpt.Coord(2),
                          ctrlpt.Coord(3)]])
                    points_single_edge = np.append(
                        points_single_edge, ctrlpt_position, axis=0)

                mesh_points_edge.append(points_single_edge)

                wire_exp_edge.Next()

            face_exp_wire.Next()
        # extract mesh points (control points) on Face
        mesh_points_face = np.zeros((0, 3))
        # convert Face to Geom B-spline Face
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face)
        nurbs_converter.Perform(topo_face)
        nurbs_face = nurbs_converter.Shape()
        h_geomsurface = BRep_Tool.Surface(topods.Face(nurbs_face))
        h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface)
        bsurface = h_bsurface.GetObject()

        # get access to control points (poles)
        nb_u = bsurface.NbUPoles()
        nb_v = bsurface.NbVPoles()
        ctrlpts = TColgp_Array2OfPnt(1, nb_u, 1, nb_v)
        bsurface.Poles(ctrlpts)

        for indice_u_direction in range(1, nb_u + 1):
            for indice_v_direction in range(1, nb_v + 1):
                ctrlpt = ctrlpts.Value(indice_u_direction, indice_v_direction)
                ctrlpt_position = np.array(
                    [[ctrlpt.Coord(1),
                      ctrlpt.Coord(2),
                      ctrlpt.Coord(3)]])
                mesh_points_face = np.append(
                    mesh_points_face, ctrlpt_position, axis=0)

        return mesh_points_face, mesh_points_edge
예제 #23
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.GetObject()

            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.GetHandle(),
                                           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.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
예제 #24
0
#!/usr/bin/env python
예제 #25
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 string 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.GetObject()

            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.GetHandle(),
                                           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.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
예제 #26
0
    def parse_face(topo_face):
        """
        Method to parse a single Face (a single patch nurbs surface).
        It returns a matrix with all the coordinates of control points of the
        Face and a second list with all the control points related to the
        Edges of the Face.

        :param topo_face: the input Face

        :return: mesh_points_face: it is a `n_points`-by-3 matrix containing the
        coordinates of the control points of the Face (a nurbs surface)

        :return: mesh_points_edge: it is a list of `n_points`-by-3 matrix

        :rtype: tuple(numpy.ndarray, list)

        """
        # get some Face - Edge - Vertex data map information
        mesh_points_edge = []
        face_exp_wire = TopExp_Explorer(topo_face, TopAbs_WIRE)
        # loop on wires per face
        while face_exp_wire.More():
            twire = topods_Wire(face_exp_wire.Current())
            wire_exp_edge = TopExp_Explorer(twire, TopAbs_EDGE)
            # loop on edges per wire
            while wire_exp_edge.More():
                edge = topods_Edge(wire_exp_edge.Current())
                bspline_converter = BRepBuilderAPI_NurbsConvert(edge)
                bspline_converter.Perform(edge)
                bspline_tshape_edge = bspline_converter.Shape()
                h_geom_edge = BRep_Tool_Curve(
                    topods_Edge(bspline_tshape_edge))[0]
                h_bspline_edge = geomconvert_CurveToBSplineCurve(h_geom_edge)
                bspline_geom_edge = h_bspline_edge.GetObject()

                nb_poles = bspline_geom_edge.NbPoles()

                # Edge geometric properties
                edge_ctrlpts = TColgp_Array1OfPnt(1, nb_poles)
                bspline_geom_edge.Poles(edge_ctrlpts)

                points_single_edge = np.zeros((0, 3))
                for i in range(1, nb_poles + 1):
                    ctrlpt = edge_ctrlpts.Value(i)
                    ctrlpt_position = np.array(
                        [[ctrlpt.Coord(1),
                          ctrlpt.Coord(2),
                          ctrlpt.Coord(3)]])
                    points_single_edge = np.append(points_single_edge,
                                                   ctrlpt_position,
                                                   axis=0)

                mesh_points_edge.append(points_single_edge)

                wire_exp_edge.Next()

            face_exp_wire.Next()
        # extract mesh points (control points) on Face
        mesh_points_face = np.zeros((0, 3))
        # convert Face to Geom B-spline Face
        nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face)
        nurbs_converter.Perform(topo_face)
        nurbs_face = nurbs_converter.Shape()
        h_geomsurface = BRep_Tool.Surface(topods.Face(nurbs_face))
        h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface)
        bsurface = h_bsurface.GetObject()

        # get access to control points (poles)
        nb_u = bsurface.NbUPoles()
        nb_v = bsurface.NbVPoles()
        ctrlpts = TColgp_Array2OfPnt(1, nb_u, 1, nb_v)
        bsurface.Poles(ctrlpts)

        for indice_u_direction in range(1, nb_u + 1):
            for indice_v_direction in range(1, nb_v + 1):
                ctrlpt = ctrlpts.Value(indice_u_direction, indice_v_direction)
                ctrlpt_position = np.array(
                    [[ctrlpt.Coord(1),
                      ctrlpt.Coord(2),
                      ctrlpt.Coord(3)]])
                mesh_points_face = np.append(mesh_points_face,
                                             ctrlpt_position,
                                             axis=0)

        return mesh_points_face, mesh_points_edge