コード例 #1
0
 def test_wires_out_of_scope(self):
     # check pointers going out of scope
     wire = next(topo.wires())
     _edges, _vertices = [], []
     for edg in WireExplorer(wire).ordered_edges():
         _edges.append(edg)
     for edg in _edges:
         self.assertFalse(edg.IsNull())
     for vert in WireExplorer(wire).ordered_vertices():
         _vertices.append(vert)
     for v in _vertices:
         self.assertFalse(v.IsNull())
コード例 #2
0
def build_plate(polygon, points):
    '''
    build a surface from a constraining polygon(s) and point(s)
    @param polygon:     list of polygons ( TopoDS_Shape)
    @param points:      list of points ( gp_Pnt )
    '''
    # plate surface
    bpSrf = GeomPlate_BuildPlateSurface(3, 15, 2)

    # add curve constraints
    for poly in polygon:
        for edg in WireExplorer(poly).ordered_edges():
            c = BRepAdaptor_HCurve()
            c.ChangeCurve().Initialize(edg)
            constraint = BRepFill_CurveConstraint(c.GetHandle(), 0)
            bpSrf.Add(constraint.GetHandle())

    # add point constraint
    for pt in points:
        bpSrf.Add(GeomPlate_PointConstraint(pt, 0).GetHandle())
        bpSrf.Perform()

    maxSeg, maxDeg, critOrder = 9, 8, 0
    tol = 1e-4
    dmax = max([tol, 10 * bpSrf.G0Error()])

    srf = bpSrf.Surface()
    plate = GeomPlate_MakeApprox(srf, tol, maxSeg, maxDeg, dmax, critOrder)
    uMin, uMax, vMin, vMax = srf.GetObject().Bounds()

    return make_face(plate.Surface(), uMin, uMax, vMin, vMax, 1e-4)
コード例 #3
0
def wire_gcode(wire):
    print(f'Wire Orientation: {o(wire)}')
    if wire.Orientation() == TopAbs_REVERSED:
        wire.Reverse()

    for edge in WireExplorer(wire).ordered_edges():
        print(f'Edge Orientation: {o(edge)}')
        tmp = BRepAdaptor_Curve(edge)
        # get underlying curve
        c, start, end = BRep_Tool.Curve(edge)
        # display start and endpoints of curve
        start_point = tmp.Value(tmp.FirstParameter())
        end_point = tmp.Value(tmp.LastParameter())

        if edge.Orientation() == TopAbs_FORWARD:
            display.DisplayColoredShape(
                BRepBuilderAPI_MakeVertex(start_point).Vertex(), "BLUE")
            display.DisplayColoredShape(
                BRepBuilderAPI_MakeVertex(end_point).Vertex(), "RED")
        else:
            display.DisplayColoredShape(
                BRepBuilderAPI_MakeVertex(start_point).Vertex(), "RED")
            display.DisplayColoredShape(
                BRepBuilderAPI_MakeVertex(end_point).Vertex(), "BLUE")

        # display individual curve
        display.DisplayShape(edge, update=True)
        time.sleep(1)
コード例 #4
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)))