Beispiel #1
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

        # 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)

        return new_edge.Edge()
Beispiel #2
0
class OccNURBSFromShape:
    def __init__(self, shape: TopoDS_Shape):
        self.mknurbs = BRepBuilderAPI_NurbsConvert(shape)
        self.shape = shape
        #self.mknurbs.Perform(shape) # Perform the conversion of the shape to a NURBS rep (curve or surface?)

    def Shape(self):
        return self.mknurbs.Shape()

    def IsDone(self) -> bool:
        return self.mknurbs.IsDone()
Beispiel #3
0
    def _bspline_curve_from_wire(self, wire):
        """
        Private method that takes a TopoDS_Wire and transforms it into a
        Bspline_Curve.

        :param TopoDS_Wire wire: the TopoDS_Face to be converted
        :rtype: Geom_BSplineSurface
        """
        if not isinstance(wire, TopoDS_Wire):
            raise TypeError("wire must be a TopoDS_Wire")

        # joining all the wire edges in a single curve here
        # composite curve builder (can only join Bspline curves)
        composite_curve_builder = GeomConvert_CompCurveToBSplineCurve()

        # iterator to edges in the TopoDS_Wire
        edge_explorer = TopExp_Explorer(wire, TopAbs_EDGE)
        while edge_explorer.More():
            # getting the edge from the iterator
            edge = topods_Edge(edge_explorer.Current())

            # edge can be joined only if it is not degenerated (zero length)
            if BRep_Tool.Degenerated(edge):
                edge_explorer.Next()
                continue

            # the edge must be converted to Nurbs edge
            nurbs_converter = BRepBuilderAPI_NurbsConvert(edge)
            nurbs_converter.Perform(edge)
            nurbs_edge = topods_Edge(nurbs_converter.Shape())

            # here we extract the underlying curve from the Nurbs edge
            nurbs_curve = BRep_Tool_Curve(nurbs_edge)[0]

            # we convert the Nurbs curve to Bspline curve
            bspline_curve = geomconvert_CurveToBSplineCurve(nurbs_curve)

            # we can now add the Bspline curve to the composite wire curve
            composite_curve_builder.Add(bspline_curve, self.tolerance)
            edge_explorer.Next()

        # GeomCurve obtained by the builder after edges are joined
        comp_curve = composite_curve_builder.BSplineCurve()
        return comp_curve
Beispiel #4
0
    def to_meshes(self, u=16, v=16):
        """Convert the faces of the BRep shape to meshes.

        Parameters
        ----------
        u : int, optional
            The number of mesh faces in the U direction of the underlying surface geometry of every face of the BRep.
        v : int, optional
            The number of mesh faces in the V direction of the underlying surface geometry of every face of the BRep.

        Returns
        -------
        list[:class:`~compas.datastructures.Mesh`]

        """
        converter = BRepBuilderAPI_NurbsConvert(self.shape, False)
        brep = BRep()
        brep.shape = converter.Shape()
        meshes = []
        for face in brep.faces:
            srf = OCCNurbsSurface.from_face(face.face)
            mesh = srf.to_vizmesh(u, v)
            meshes.append(mesh)
        return meshes
 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
<head>
    <meta name='generator' content='pythonocc-7.4.1-dev X3D exporter (www.pythonocc.org)'/>
    <meta name='creator' content='pythonocc-7.4.1-dev generator'/>
    <meta name='identifier' content='http://www.pythonocc.org'/>
    <meta name='description' content='pythonocc-7.4.1-dev x3dom based shape rendering'/>
</head>
    <Scene>
    %s
    </Scene>
</X3D>
"""

base_shape = BRepPrimAPI_MakeTorus(3, 1).Shape()

# conversion to a nurbs representation
nurbs_converter = BRepBuilderAPI_NurbsConvert(base_shape, True)
# nurbs_converter.Perform()
converted_shape = nurbs_converter.Shape()

# now, all edges should be BSpline curves and surfaces BSpline surfaces

# https://castle-engine.io/x3d_implementation_nurbs.php#section_homogeneous_coordinates
expl = TopologyExplorer(converted_shape)

nurbs_node_str = ""

face_idx = 1

for face in expl.faces():
    surf = BRepAdaptor_Surface(face, True)
    surf_type = surf.GetType()
Beispiel #7
0
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)))
Beispiel #8
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
Beispiel #9
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

        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, 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())
Beispiel #10
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

                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

        # 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
Beispiel #11
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)
Beispiel #12
0
 def __init__(self, shape: TopoDS_Shape):
     self.mknurbs = BRepBuilderAPI_NurbsConvert(shape)
     self.shape = shape