Пример #1
0
def make_wire(*args):
    # if we get an iterable, than add all edges to wire builder
    if isinstance(args[0], (list, tuple)):
        wire = BRepBuilderAPI_MakeWire()
        for i in args[0]:
            wire.Add(i)
        wire.Build()
        return wire.Wire()
    wire = BRepBuilderAPI_MakeWire(*args)
    return wire.Wire()
Пример #2
0
def _polysegment(pnts, closed=False) -> Shape:
    if len(pnts) <= 1:
        raise Exception("Need at least two points for polysegment")

    mkWire = BRepBuilderAPI_MakeWire()

    def __make_edge(a, b):
        try:
            return BRepBuilderAPI_MakeEdge(to_Pnt(a), to_Pnt(b)).Edge()
        except:
            raise Exception(f"Cannot make edge segment from points {a}, {b}")

    for i in range(len(pnts) - 1):
        mkWire.Add(__make_edge(pnts[i], pnts[i + 1]))

    if (closed):
        mkWire.Add(__make_edge(pnts[len(pnts) - 1], pnts[0]))

    return Shape(mkWire.Wire())
Пример #3
0
def wire_from_polyline(pol3d):
    lines = []
    for i, p in enumerate(pol3d[:-1]):
        gp0 = gp_Pnt(p[0], p[1], p[2])
        gp1 = gp_Pnt(pol3d[i + 1][0], pol3d[i + 1][1], pol3d[i + 1][2])
        lines.append(BRepBuilderAPI_MakeEdge(gp0, gp1).Edge())
    wire = BRepBuilderAPI_MakeWire(lines[0])

    for l in lines[1:]:
        wire.Add(l)
    return wire
Пример #4
0
def make_wire(*args):
    # if we get an iterable, than add all edges to wire builder
    if isinstance(args[0], (list, tuple)):
        wire = BRepBuilderAPI_MakeWire()
        for i in args[0]:
            wire.Add(i)
        wire.Build()
        return wire.Wire()
    wire = BRepBuilderAPI_MakeWire(*args)
    assert_isdone(wire, "failed to produce wire")
    return wire.Wire()
 def generate_planar_slices(nozz_dia, sur_nozz_dia):
     xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(part_shape)
     print(xmax - xmin, ",", ymax - ymin, ",", zmax - zmin)
     wires = []
     slices = []
     contours = []
     for z in numpy.arange(zmin+(nozz_dia/2)+(sur_nozz_dia/2), \
      zmax-(nozz_dia/2)-(sur_nozz_dia/2), nozz_dia):
         plane = gp_Pln(gp_Pnt(0., 0., z), gp_Dir(0., 0., 1.))
         slices.append(Slicing.plane_shape_intersection(plane, part_shape))
     for s in range(0, len(slices)):
         wire = []
         wires.append([])
         while len(slices[s]) != 0:
             for i in range(0, len(slices[s])):
                 if len(wire) == 0:
                     wire.append(slices[s][i])
                     slices[s].remove(slices[s][i])
                     break
                 elif Slicing.do_edges_connect(slices[s][i], wire[-1]):
                     wire.append(slices[s][i])
                     slices[s].remove(slices[s][i])
                     break
             if Slicing.do_edges_connect(wire[0], wire[-1]):
                 if len(wire) > 2:
                     wires[s].append(wire)
                     wire = []
                 elif len(wire) == 2 and Slicing.do_edges_loop(
                         wire[0], wire[-1]):
                     wires[s].append(wire)
                     wire = []
     for k in range(0, len(wires)):
         contours.append([])
         for l in range(0, len(wires[k])):
             make_wire = BRepBuilderAPI_MakeWire()
             for edge in wires[k][l]:
                 make_wire.Add(edge)
             try:
                 made_wire = make_wire.Wire()
                 contours[k].append(made_wire)
             except:
                 print("Skipped a contour!")
                 continue
     contour_faces = []
     for contour in contours:
         if len(contour) == 1:
             contour_faces.append(
                 BRepBuilderAPI_MakeFace(contour[0]).Face())
         else:
             contour_faces.extend(Slicing.get_layer_faces(contour))
     # for l in range(0,len(contour_faces)):
     #   display.DisplayShape(contour_faces[l], color=colour[l%5],\
     #   	transparency=0.95, update=True)
     return contour_faces
 def make_wire(edges, fillets=None):
     # the wire
     # print("adding wire")
     makeWire = BRepBuilderAPI_MakeWire()
     makeWire.Add(edges[0])
     if fillets is None:
         for edge in edges[1:]:
             makeWire.Add(edge)
     else:
         for fillet, edge in zip(fillets, edges[1:]):
             makeWire.Add(fillet)
             makeWire.Add(edge)
     # print("build wire")
     makeWire.Build()
     # print("make wire")
     try:
         wire = makeWire.Wire()
     except RuntimeError as e:
         print(type(makeWire))
         raise e
     return wire
Пример #7
0
def face_polyline3d(pol3d):
    from OCC.Core.TopoDS import topods
    lines = []
    for i, p in enumerate(pol3d[:-1]):
        gp0 = gp_Pnt(p[0], p[1], p[2])
        gp1 = gp_Pnt(pol3d[i + 1][0], pol3d[i + 1][1], pol3d[i + 1][2])
        lines.append(BRepBuilderAPI_MakeEdge(gp0, gp1).Edge())
    wire = BRepBuilderAPI_MakeWire(lines[0])
    for l in lines[1:]:
        wire.Add(l)
    face = BRepBuilderAPI_MakeFace(wire.Wire())
    return face
Пример #8
0
 def __init__(self, edges):
     super().__init__()
     self.wire = None
     mkwire = BRepBuilderAPI_MakeWire()
     if isinstance(edges, TopoDS_Edge):
         mkwire.Add(edges)
         self.done = True
         self.wire = mkwire.Wire()
     elif len(edges) > 0:
         for edge in edges:
             if isinstance(edge, list):
                 for e in edge:
                     mkwire.Add(e)
             else:
                 mkwire.Add(edge)
         if not mkwire.IsDone():
             OCCWrapper.OccError('OccWire', mkwire)
         else:
             self.done = True
             self.wire = mkwire.Wire()
     return
Пример #9
0
 def makeWire(self):
     """Generate a wire from the edges in self.edgeList."""
     wireBldr = BRepBuilderAPI_MakeWire()
     occ_seq = TopTools_ListOfShape()
     for edge in self.edgeList:
         occ_seq.Append(edge)
     wireBldr.Add(occ_seq)
     if wireBldr.IsDone():
         self.wire = wireBldr.Wire()
         status = True
     else:
         status = False
     return status
 def display_path(lay, col, nozz_dia=0):
     wire = BRepBuilderAPI_MakeWire()
     for i in range(1, len(lay)):
         if lay[i - 1][0].Distance(lay[i][0]) < 8 and i < len(lay) - 1:
             ray = BRepBuilderAPI_MakeEdge(lay[i - 1][0], lay[i][0]).Edge()
             wire.Add(ray)
         else:
             display.DisplayShape(wire.Wire(), color=col, update=False)
             wire = BRepBuilderAPI_MakeWire()
         if i < len(lay) - 1:
             display.DisplayShape(ray, color=col, update=False)
         else:
             display.DisplayShape(ray, color=col, update=True)
def brepfeat_prism(event=None):
    box = BRepPrimAPI_MakeBox(400, 250, 300).Shape()
    faces = TopologyExplorer(box).faces()

    for i in range(5):
        face = next(faces)

    srf = BRep_Tool_Surface(face)

    c = gp_Circ2d(gp_Ax2d(gp_Pnt2d(200, 130),
                          gp_Dir2d(1, 0)), 75)

    circle = Geom2d_Circle(c)

    wire = BRepBuilderAPI_MakeWire()
    wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, 0., pi).Edge())
    wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, pi, 2. * pi).Edge())
    wire.Build()

    display.DisplayShape(wire.Wire())

    mkf = BRepBuilderAPI_MakeFace()
    mkf.Init(srf, False, 1e-6)
    mkf.Add(wire.Wire())
    mkf.Build()

    new_face = mkf.Face()
    breplib_BuildCurves3d(new_face)

    display.DisplayShape(new_face)

    prism = BRepFeat_MakeDPrism(box, mkf.Face(), face, 100, True, True)

    prism.Perform(400)
    assert prism.IsDone()
    display.EraseAll()
    display.DisplayShape(prism.Shape())
    display.DisplayColoredShape(wire.Wire(), 'RED')
    display.FitAll()
Пример #12
0
def make_wire(*args):
    # if we get an iterable, than add all edges to wire builder
    if isinstance(args[0], list) or isinstance(args[0], tuple):
        wire = BRepBuilderAPI_MakeWire()
        for i in args[0]:
            wire.Add(i)
        wire.Build()
        return wire.Wire()

    wire = BRepBuilderAPI_MakeWire(*args)
    wire.Build()
    with assert_isdone(wire, 'failed to produce wire'):
        result = wire.Wire()
        return result
Пример #13
0
    def create_model(self):
        boltCylinderex = BRepPrimAPI_MakeCylinder(
            gp_Ax2(getGpPt(self.p1), getGpDir(-self.shaftDir)), self.r,
            self.cylex_length).Shape()
        boltCylinder1 = BRepPrimAPI_MakeCylinder(
            gp_Ax2(getGpPt(self.p1), getGpDir(self.shaftDir)), self.r,
            self.cyl1_length).Shape()
        boltCylinder2 = BRepPrimAPI_MakeCylinder(
            gp_Ax2(getGpPt(self.p2), getGpDir(self.cyl2_angle)), self.r,
            self.cyl2_ht).Shape()
        boltCylinder3 = BRepPrimAPI_MakeCylinder(
            gp_Ax2(getGpPt(self.p3), getGpDir(self.shaftDir)), self.r,
            self.cyl3_length).Shape()
        boltCylinder4 = BRepPrimAPI_MakeCylinder(
            gp_Ax2(getGpPt(self.p6), getGpDir(-self.shaftDir)), self.r,
            self.cyl5_length).Shape()

        sphere1 = BRepPrimAPI_MakeSphere(getGpPt(self.p2), self.r).Shape()
        sphere2 = BRepPrimAPI_MakeSphere(getGpPt(self.p3), self.r).Shape()

        edg_points = gp_Circ(gp_Ax2(getGpPt(self.p4), getGpDir(self.shaftDir)),
                             self.r)
        hexwire = BRepBuilderAPI_MakeWire()
        hexedge = BRepBuilderAPI_MakeEdge(edg_points).Edge()
        hexwire.Add(hexedge)
        hexwire_wire = hexwire.Wire()
        hexface = BRepBuilderAPI_MakeFace(hexwire_wire).Face()
        revolve_axis = gp_Ax1(getGpPt(self.p5), gp_Dir(0, -1, 0))
        revolved_shape = BRepPrimAPI_MakeRevol(hexface, revolve_axis,
                                               math.radians(180.)).Shape()

        Anchor_BOlt = BRepAlgoAPI_Fuse(boltCylinder1, boltCylinder2).Shape()
        Anchor_BOlt = BRepAlgoAPI_Fuse(boltCylinder3, Anchor_BOlt).Shape()
        Anchor_BOlt = BRepAlgoAPI_Fuse(revolved_shape, Anchor_BOlt).Shape()
        Anchor_BOlt = BRepAlgoAPI_Fuse(boltCylinder4, Anchor_BOlt).Shape()

        Anchor_BOlt = BRepAlgoAPI_Fuse(sphere1, Anchor_BOlt).Shape()
        Anchor_BOlt = BRepAlgoAPI_Fuse(sphere2, Anchor_BOlt).Shape()

        Anchor_BOlt = BRepAlgoAPI_Fuse(boltCylinderex, Anchor_BOlt).Shape()

        return Anchor_BOlt
Пример #14
0
def face_polyline(polyline, frame):
    pol3d = polyline.to_frame(frame)
    lines = []
    yb_point = Point([frame[0][i] for i in range(3)])
    yb_vec = Vector([frame[3][i] for i in range(3)]).unit()
    orig = gp_Pnt(frame[0][0], frame[0][1], frame[0][2])
    vec = gp_Dir(yb_vec[0], yb_vec[1], yb_vec[2])
    plane = gp_Pln(orig, vec)

    for i, p in enumerate(pol3d[:-1]):
        gp0 = gp_Pnt(p[0], p[1], p[2])
        gp1 = gp_Pnt(pol3d[i + 1][0], pol3d[i + 1][1], pol3d[i + 1][2])
        lines.append(BRepBuilderAPI_MakeEdge(gp0, gp1).Edge())

    wire = BRepBuilderAPI_MakeWire(lines[0])

    for l in lines[1:]:
        wire.Add(l)

    face = BRepBuilderAPI_MakeFace(wire.Wire())
    return face.Shape()
def revolved_cut(base):
    # Define 7 points
    face_points = TColgp_Array1OfPnt(1, 7)
    face_inner_radius = 0.6

    pts = [
        gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05),
        gp_Pnt(face_inner_radius - 0.10, 0.0, -0.025),
        gp_Pnt(face_inner_radius - 0.10, 0.0, 0.025),
        gp_Pnt(face_inner_radius + 0.10, 0.0, 0.025),
        gp_Pnt(face_inner_radius + 0.10, 0.0, -0.025),
        gp_Pnt(face_inner_radius + 0.05, 0.0, -0.05),
        gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05),
    ]

    for n, i in enumerate(pts):
        face_points.SetValue(n + 1, i)

    # Use these points to create edges and add these edges to a wire
    hexwire = BRepBuilderAPI_MakeWire()

    for i in range(1, 7):
        hexedge = BRepBuilderAPI_MakeEdge(face_points.Value(i), face_points.Value(i + 1)).Edge()
        hexwire.Add(hexedge)

    # Turn the wire into a 6 sided face
    hexface = BRepBuilderAPI_MakeFace(hexwire.Wire()).Face()

    # Revolve the face around an axis
    revolve_axis = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))
    revolved_shape = BRepPrimAPI_MakeRevol(hexface, revolve_axis).Shape()

    # Move the generated shape
    move = gp_Trsf()
    move.SetTranslation(gp_Pnt(0, 0, 0), gp_Pnt(0, 0, sin(0.5)))
    moved_shape = BRepBuilderAPI_Transform(revolved_shape, move, False).Shape()

    # Remove the revolved shape
    cut = BRepAlgoAPI_Cut(base, moved_shape).Shape()
    return cut
Пример #16
0
def revolved_shape():
    """ demonstrate how to create a revolved shape from an edge
    adapted from algotopia.com's opencascade_basic tutorial:
    http://www.algotopia.com/contents/opencascade/opencascade_basic
    """
    face_inner_radius = 0.6
    # point to create an edge from
    edg_points = [
        gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05),
        gp_Pnt(face_inner_radius - 0.10, 0.0, -0.025),
        gp_Pnt(face_inner_radius - 0.10, 0.0, 0.025),
        gp_Pnt(face_inner_radius + 0.10, 0.0, 0.025),
        gp_Pnt(face_inner_radius + 0.10, 0.0, -0.025),
        gp_Pnt(face_inner_radius + 0.05, 0.0, -0.05),
        gp_Pnt(face_inner_radius - 0.05, 0.0, -0.05),
    ]

    # aggregate edges in wire
    hexwire = BRepBuilderAPI_MakeWire()

    for i in range(6):
        hexedge = BRepBuilderAPI_MakeEdge(edg_points[i],
                                          edg_points[i + 1]).Edge()
        hexwire.Add(hexedge)

    hexwire_wire = hexwire.Wire()
    # face from wire
    hexface = BRepBuilderAPI_MakeFace(hexwire_wire).Face()
    revolve_axis = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))
    # create revolved shape
    revolved_shape_ = BRepPrimAPI_MakeRevol(hexface, revolve_axis,
                                            math.radians(90.)).Shape()

    # render wire & revolved shape
    display.DisplayShape([revolved_shape_, hexwire_wire])
    display.FitAll()
    start_display()
Пример #17
0
def sweep_pipe(edge, xvec, r, wt, geom_repr=ElemType.SOLID):
    if geom_repr not in [ElemType.SOLID, ElemType.SHELL]:
        raise ValueError("Sweeping pipe must be either 'solid' or 'shell'")

    t = TopologyExplorer(edge)
    points = [v for v in t.vertices()]
    point = BRep_Tool_Pnt(points[0])
    # x, y, z = point.X(), point.Y(), point.Z()
    direction = gp_Dir(*unit_vector(xvec).astype(float).tolist())

    # pipe
    makeWire = BRepBuilderAPI_MakeWire()
    makeWire.Add(edge)
    makeWire.Build()
    wire = makeWire.Wire()
    try:
        if geom_repr == ElemType.SOLID:
            i = make_circular_sec_face(point, direction, r - wt)
            elbow_i = BRepOffsetAPI_MakePipe(wire, i).Shape()
            o = make_circular_sec_face(point, direction, r)
            elbow_o = BRepOffsetAPI_MakePipe(wire, o).Shape()
        else:
            elbow_i = None
            o = make_circular_sec_wire(point, direction, r)
            elbow_o = BRepOffsetAPI_MakePipe(wire, o).Shape()
    except RuntimeError as e:
        logging.error(f'Pipe sweep failed: "{e}"')
        return wire
    if geom_repr == ElemType.SOLID:
        boolean_result = BRepAlgoAPI_Cut(elbow_o, elbow_i).Shape()
        if boolean_result.IsNull():
            logging.debug("Boolean returns None")
    else:
        boolean_result = elbow_o

    return boolean_result
Пример #18
0
def brep_feat_rib(event=None):
    mkw = BRepBuilderAPI_MakeWire()

    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(0., 0., 0.), gp_Pnt(200., 0.,
                                                           0.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(200., 0., 0.), gp_Pnt(200., 0.,
                                                             50.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(200., 0., 50.), gp_Pnt(50., 0.,
                                                              50.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 0., 50.), gp_Pnt(50., 0.,
                                                             200.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 0., 200.), gp_Pnt(0., 0.,
                                                              200.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(0., 0., 200.), gp_Pnt(0., 0.,
                                                             0.)).Edge())

    S = BRepPrimAPI_MakePrism(
        BRepBuilderAPI_MakeFace(mkw.Wire()).Face(),
        gp_Vec(gp_Pnt(0., 0., 0.), gp_Pnt(0., 100., 0.)))
    display.EraseAll()
    #    display.DisplayShape(S.Shape())

    W = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 45., 100.), gp_Pnt(100., 45.,
                                                               50.)).Edge())

    aplane = Geom_Plane(0., 1., 0., -45.)

    aform = BRepFeat_MakeLinearForm(S.Shape(), W.Wire(), aplane,
                                    gp_Vec(0., 10., 0.), gp_Vec(0., 0., 0.), 1,
                                    True)
    aform.Perform()
    display.DisplayShape(aform.Shape())
    display.FitAll()
Пример #19
0
def startBottle(startOnly=True):  # minus the neck fillet, shelling & threads
    partName = "Bottle-start"
    # The points we'll use to create the profile of the bottle's body
    aPnt1 = gp_Pnt(-width / 2.0, 0, 0)
    aPnt2 = gp_Pnt(-width / 2.0, -thickness / 4.0, 0)
    aPnt3 = gp_Pnt(0, -thickness / 2.0, 0)
    aPnt4 = gp_Pnt(width / 2.0, -thickness / 4.0, 0)
    aPnt5 = gp_Pnt(width / 2.0, 0, 0)

    aArcOfCircle = GC_MakeArcOfCircle(aPnt2, aPnt3, aPnt4)
    aSegment1 = GC_MakeSegment(aPnt1, aPnt2)
    aSegment2 = GC_MakeSegment(aPnt4, aPnt5)

    # Could also construct the line edges directly using the points
    # instead of the resulting line.
    aEdge1 = BRepBuilderAPI_MakeEdge(aSegment1.Value())
    aEdge2 = BRepBuilderAPI_MakeEdge(aArcOfCircle.Value())
    aEdge3 = BRepBuilderAPI_MakeEdge(aSegment2.Value())

    # Create a wire out of the edges
    aWire = BRepBuilderAPI_MakeWire(aEdge1.Edge(), aEdge2.Edge(),
                                    aEdge3.Edge())

    # Quick way to specify the X axis
    xAxis = gp_OX()

    # Set up the mirror
    aTrsf = gp_Trsf()
    aTrsf.SetMirror(xAxis)

    # Apply the mirror transformation
    aBRespTrsf = BRepBuilderAPI_Transform(aWire.Wire(), aTrsf)

    # Get the mirrored shape back out of the transformation
    # and convert back to a wire
    aMirroredShape = aBRespTrsf.Shape()

    # A wire instead of a generic shape now
    aMirroredWire = topods.Wire(aMirroredShape)

    # Combine the two constituent wires
    mkWire = BRepBuilderAPI_MakeWire()
    mkWire.Add(aWire.Wire())
    mkWire.Add(aMirroredWire)
    myWireProfile = mkWire.Wire()

    # The face that we'll sweep to make the prism
    myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile)

    # We want to sweep the face along the Z axis to the height
    aPrismVec = gp_Vec(0, 0, height)
    myBody = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec)

    # Add fillets to all edges through the explorer
    mkFillet = BRepFilletAPI_MakeFillet(myBody.Shape())
    anEdgeExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_EDGE)

    while anEdgeExplorer.More():
        anEdge = topods.Edge(anEdgeExplorer.Current())
        mkFillet.Add(thickness / 12.0, anEdge)

        anEdgeExplorer.Next()

    myBody = mkFillet.Shape()

    # Create the neck of the bottle
    neckLocation = gp_Pnt(0, 0, height)
    neckAxis = gp_DZ()
    neckAx2 = gp_Ax2(neckLocation, neckAxis)

    myNeckRadius = thickness / 4.0
    myNeckHeight = height / 10.0

    mkCylinder = BRepPrimAPI_MakeCylinder(neckAx2, myNeckRadius, myNeckHeight)
    myBody = BRepAlgoAPI_Fuse(myBody, mkCylinder.Shape())
    if startOnly:  # quit here
        uid = win.getNewPartUID(myBody.Shape(), name=partName)
        win.redraw()
        return

    partName = "Bottle-complete"
    # Our goal is to find the highest Z face and remove it
    faceToRemove = None
    zMax = -1

    # We have to work our way through all the faces to find the highest Z face
    aFaceExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_FACE)
    while aFaceExplorer.More():
        aFace = topods.Face(aFaceExplorer.Current())

        if face_is_plane(aFace):
            aPlane = geom_plane_from_face(aFace)

            # We want the highest Z face, so compare this to the previous faces
            aPnt = aPlane.Location()
            aZ = aPnt.Z()
            if aZ > zMax:
                zMax = aZ
                faceToRemove = aFace

        aFaceExplorer.Next()

    facesToRemove = TopTools_ListOfShape()
    facesToRemove.Append(faceToRemove)

    myBody = BRepOffsetAPI_MakeThickSolid(myBody.Shape(), facesToRemove,
                                          -thickness / 50.0, 0.001)

    # Set up our surfaces for the threading on the neck
    neckAx2_Ax3 = gp_Ax3(neckLocation, gp_DZ())
    aCyl1 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 0.99)
    aCyl2 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 1.05)

    # Set up the curves for the threads on the bottle's neck
    aPnt = gp_Pnt2d(2.0 * math.pi, myNeckHeight / 2.0)
    aDir = gp_Dir2d(2.0 * math.pi, myNeckHeight / 4.0)
    anAx2d = gp_Ax2d(aPnt, aDir)

    aMajor = 2.0 * math.pi
    aMinor = myNeckHeight / 10.0

    anEllipse1 = Geom2d_Ellipse(anAx2d, aMajor, aMinor)
    anEllipse2 = Geom2d_Ellipse(anAx2d, aMajor, aMinor / 4.0)

    anArc1 = Geom2d_TrimmedCurve(anEllipse1, 0, math.pi)
    anArc2 = Geom2d_TrimmedCurve(anEllipse2, 0, math.pi)

    anEllipsePnt1 = anEllipse1.Value(0)
    anEllipsePnt2 = anEllipse1.Value(math.pi)

    aSegment = GCE2d_MakeSegment(anEllipsePnt1, anEllipsePnt2)

    # Build edges and wires for threading
    anEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(anArc1, aCyl1)
    anEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl1)
    anEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(anArc2, aCyl2)
    anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl2)

    threadingWire1 = BRepBuilderAPI_MakeWire(anEdge1OnSurf1.Edge(),
                                             anEdge2OnSurf1.Edge())
    threadingWire2 = BRepBuilderAPI_MakeWire(anEdge1OnSurf2.Edge(),
                                             anEdge2OnSurf2.Edge())

    # Compute the 3D representations of the edges/wires
    breplib.BuildCurves3d(threadingWire1.Shape())
    breplib.BuildCurves3d(threadingWire2.Shape())

    # Create the surfaces of the threading
    aTool = BRepOffsetAPI_ThruSections(True)
    aTool.AddWire(threadingWire1.Wire())
    aTool.AddWire(threadingWire2.Wire())
    aTool.CheckCompatibility(False)
    myThreading = aTool.Shape()

    # Build the resulting compound
    aRes = TopoDS_Compound()
    aBuilder = BRep_Builder()
    aBuilder.MakeCompound(aRes)
    aBuilder.Add(aRes, myBody.Shape())
    aBuilder.Add(aRes, myThreading)
    uid = win.getNewPartUID(aRes, name=partName)
    win.redraw()
Пример #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

        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())
Пример #21
0
def brep_feat_extrusion_protrusion(event=None):
    # Extrusion
    S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape()
    faces = TopologyExplorer(S).faces()
    F = next(faces)
    surf1 = BRep_Tool_Surface(F)

    Pl1 = Geom_Plane.DownCast(surf1)

    D1 = Pl1.Pln().Axis().Direction().Reversed()
    MW = BRepBuilderAPI_MakeWire()
    p1, p2 = gp_Pnt2d(200., -100.), gp_Pnt2d(100., -100.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge())

    p1, p2 = gp_Pnt2d(100., -100.), gp_Pnt2d(100., -200.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge())

    p1, p2 = gp_Pnt2d(100., -200.), gp_Pnt2d(200., -200.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge())

    p1, p2 = gp_Pnt2d(200., -200.), gp_Pnt2d(200., -100.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge())

    MKF = BRepBuilderAPI_MakeFace()
    MKF.Init(surf1, False, 1e-6)
    MKF.Add(MW.Wire())
    FP = MKF.Face()
    breplib_BuildCurves3d(FP)

    display.EraseAll()
    MKP = BRepFeat_MakePrism(S, FP, F, D1, 0, True)
    MKP.PerformThruAll()

    res1 = MKP.Shape()
    display.DisplayShape(res1)

    # Protrusion
    next(faces)
    F2 = next(faces)
    surf2 = BRep_Tool_Surface(F2)
    Pl2 = Geom_Plane.DownCast(surf2)
    D2 = Pl2.Pln().Axis().Direction().Reversed()
    MW2 = BRepBuilderAPI_MakeWire()
    p1, p2 = gp_Pnt2d(100., 100.), gp_Pnt2d(200., 100.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge())

    p1, p2 = gp_Pnt2d(200., 100.), gp_Pnt2d(150., 200.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge())

    p1, p2 = gp_Pnt2d(150., 200.), gp_Pnt2d(100., 100.)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge())

    MKF2 = BRepBuilderAPI_MakeFace()
    MKF2.Init(surf2, False, 1e-6)
    MKF2.Add(MW2.Wire())
    MKF2.Build()

    FP = MKF2.Face()
    breplib_BuildCurves3d(FP)
    MKP2 = BRepFeat_MakePrism(res1, FP, F2, D2, 0, True)
    MKP2.PerformThruAll()
    display.EraseAll()

    trf = gp_Trsf()
    trf.SetTranslation(gp_Vec(0, 0, 300))
    gtrf = gp_GTrsf()
    gtrf.SetTrsf(trf)
    tr = BRepBuilderAPI_GTransform(MKP2.Shape(), gtrf, True)

    fused = BRepAlgoAPI_Fuse(tr.Shape(), MKP2.Shape())
    fused.Build()

    display.DisplayShape(fused.Shape())
    display.FitAll()
Пример #22
0
    def max_counter(self, facesS_2):
        section_edges = list(Topo(facesS_2).edges())
        # print(len(section_edges))

        if len(section_edges) > 0:

            Wire_c = BRepBuilderAPI_MakeWire()
            prep_list = []
            Wire_c.Add(section_edges[0])
            prep_list.append(section_edges[0])
            ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

            # no need for a loop since we know for a fact that
            # the edge has only one start and one end
            c = ex.Current()
            cv = topods_Vertex(c)
            v0 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            v1 = BRep_Tool_Pnt(cv)
            section_edges.pop(0)
            flag = 0
            wires = []

            while len(section_edges) > 0:

                new_list = []

                for edges in section_edges:
                    # Wire_c.Add(edges)
                    ex = TopExp_Explorer(edges, TopAbs_VERTEX)
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    End_1 = BRep_Tool_Pnt(cv)
                    ex.Next()
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    End_2 = BRep_Tool_Pnt(cv)

                    if End_1.X() == v0.X() and End_1.Y() == v0.Y() and End_1.Z(
                    ) == v0.Z():
                        Wire_c.Add(edges)
                        v0 = End_2
                        flag = 0
                    elif End_1.X() == v1.X() and End_1.Y() == v1.Y(
                    ) and End_1.Z() == v1.Z():
                        Wire_c.Add(edges)
                        v1 = End_2
                        flag = 0
                    elif End_2.X() == v0.X() and End_2.Y() == v0.Y(
                    ) and End_2.Z() == v0.Z():
                        Wire_c.Add(edges)
                        v0 = End_1
                        flag = 0
                    elif End_2.X() == v1.X() and End_2.Y() == v1.Y(
                    ) and End_2.Z() == v1.Z():
                        Wire_c.Add(edges)
                        v1 = End_1
                        flag = 0
                    else:
                        new_list.append(edges)

                flag += 1
                section_edges = new_list

                if flag >= 5:
                    # print('number_ostalos', len(section_edges))
                    wires.append(Wire_c.Wire())
                    Wire_c = BRepBuilderAPI_MakeWire()

                    Wire_c.Add(section_edges[0])
                    ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

                    # no need for a loop since we know for a fact that
                    # the edge has only one start and one end
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    v0 = BRep_Tool_Pnt(cv)
                    ex.Next()
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    v1 = BRep_Tool_Pnt(cv)
                    section_edges.pop(0)
                    flag = 0

            wires.append(Wire_c.Wire())

            areas = []
            props = GProp_GProps()

            for wire in wires:
                brown_face = BRepBuilderAPI_MakeFace(wire)
                brown_face = brown_face.Face()
                # props = GProp_GProps()
                brepgprop_SurfaceProperties(brown_face, props)
                areas.append(props.Mass())

            return max(areas)

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

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

        # cycle on the faces to get the control points

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if isinstance(dst, str):  # if a input filename is passed
            # save the shape exactly to the filename, aka `dst`
            self.write_shape(dst, compound)
        else:
            return compound
Пример #24
0
def round_tooth(wedge):
    round_x = 2.6
    round_z = 0.06 * pitch
    round_radius = pitch

    # Determine where the circle used for rounding has to start and stop
    p2d_1 = gp_Pnt2d(top_radius - round_x, 0)
    p2d_2 = gp_Pnt2d(top_radius, round_z)

    # Construct the rounding circle
    round_circle = GccAna_Circ2d2TanRad(p2d_1, p2d_2, round_radius, 0.01)
    if (round_circle.NbSolutions() != 2):
        sys.exit(-2)

    round_circle_2d_1 = round_circle.ThisSolution(1)
    round_circle_2d_2 = round_circle.ThisSolution(2)

    if (round_circle_2d_1.Position().Location().Coord()[1] >= 0):
        round_circle_2d = round_circle_2d_1
    else:
        round_circle_2d = round_circle_2d_2

    # Remove the arc used for rounding
    trimmed_circle = GCE2d_MakeArcOfCircle(round_circle_2d, p2d_1, p2d_2).Value()

    # Calculate extra points used to construct lines
    p1 = gp_Pnt(p2d_1.X(), 0, p2d_1.Y())
    p2 = gp_Pnt(p2d_2.X(), 0, p2d_2.Y())
    p3 = gp_Pnt(p2d_2.X() + 1, 0, p2d_2.Y())
    p4 = gp_Pnt(p2d_2.X() + 1, 0, p2d_1.Y() - 1)
    p5 = gp_Pnt(p2d_1.X(), 0, p2d_1.Y() - 1)

    # Convert the arc and four extra lines into 3D edges
    plane = gp_Pln(gp_Ax3(gp_Origin(), gp_DY().Reversed(), gp_DX()))
    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_circle, plane)).Edge()
    lin1 = BRepBuilderAPI_MakeEdge(p2, p3).Edge()
    lin2 = BRepBuilderAPI_MakeEdge(p3, p4).Edge()
    lin3 = BRepBuilderAPI_MakeEdge(p4, p5).Edge()
    lin4 = BRepBuilderAPI_MakeEdge(p5, p1).Edge()

    # Make a wire composed of the edges
    round_wire = BRepBuilderAPI_MakeWire(arc1)
    round_wire.Add(lin1)
    round_wire.Add(lin2)
    round_wire.Add(lin3)
    round_wire.Add(lin4)

    # Turn the wire into a face
    round_face = BRepBuilderAPI_MakeFace(round_wire.Wire()).Shape()

    # Revolve the face around the Z axis over the tooth angle
    rounding_cut_1 = BRepPrimAPI_MakeRevol(round_face, gp_OZ(), tooth_angle).Shape()

    # Construct a mirrored copy of the first cutting shape
    mirror = gp_Trsf()
    mirror.SetMirror(gp_XOY())
    mirrored_cut_1 = BRepBuilderAPI_Transform(rounding_cut_1, mirror, True).Shape()

    # and translate it so that it ends up on the other side of the wedge
    translate = gp_Trsf()
    translate.SetTranslation(gp_Vec(0, 0, thickness))
    rounding_cut_2 = BRepBuilderAPI_Transform(mirrored_cut_1, translate, False).Shape()

    # Cut the wedge using the first and second cutting shape
    cut_1 = BRepAlgoAPI_Cut(wedge, rounding_cut_1).Shape()
    cut_2 = BRepAlgoAPI_Cut(cut_1, rounding_cut_2).Shape()

    return cut_2
# Set up the mirror
aTrsf = gp_Trsf()
aTrsf.SetMirror(xAxis)

# Apply the mirror transformation
aBRespTrsf = BRepBuilderAPI_Transform(aWire.Wire(), aTrsf)

# Get the mirrored shape back out of the transformation and convert back to a wire
aMirroredShape = aBRespTrsf.Shape()

# A wire instead of a generic shape now
aMirroredWire = topods.Wire(aMirroredShape)

# Combine the two constituent wires
mkWire = BRepBuilderAPI_MakeWire()
mkWire.Add(aWire.Wire())
mkWire.Add(aMirroredWire)
myWireProfile = mkWire.Wire()

# The face that we'll sweep to make the prism
myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile)

# We want to sweep the face along the Z axis to the height
aPrismVec = gp_Vec(0, 0, height)
myBody_step1 = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec)

# Add fillets to all edges through the explorer
mkFillet = BRepFilletAPI_MakeFillet(myBody_step1.Shape())
anEdgeExplorer = TopExp_Explorer(myBody_step1.Shape(), TopAbs_EDGE)

while anEdgeExplorer.More():
Пример #26
0
def glue_solids(event=None):
    display.EraseAll()
    display.Context.RemoveAll(True)
    # Without common edges
    S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.), gp_Pnt(100., 250., 300.)).Shape()
    # S2 = BRepPrimAPI_MakeBox(gp_Pnt(300., 300., 300.), gp_Pnt(600., 600., 600.)).Shape()
    S2 = read_step_file(os.path.join('..', 'part_of_sattelate', 'pribore', 'Camara_WS16.STEP'))
    bbox = Bnd_Box()
    brepbndlib_Add(S2, bbox)
    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    print(bbox.Get())
    p0 = gp_Pnt(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin+0.01)

    vnorm = gp_Dir(0, 0, 1)
    pln = gp_Pln(p0, vnorm)
    face = BRepBuilderAPI_MakeFace(pln, -(xmax - xmin) / 2 - 1, (xmax - xmin) / 2 + 1, -(ymax - ymin) / 2 - 1,
                                   (ymax - ymin) / 2 + 1).Face()
    # face = BRepBuilderAPI_MakeFace(pln, -10, 10, -10,10).Face()
    '''planeZ = BRepBuilderAPI_MakeFace(
        gp_Pln(gp_Pnt(xmin, ymin, zmin), gp_Pnt(xmax, ymax, zmin), gp_Pnt(xmin, ymax, zmin))).Face()'''
    facesS_2 = BRepAlgoAPI_Section(face, S2).Shape()
    # print(facesS_2)
    display.DisplayShape(face, update=True)
    display.DisplayShape(S2, update=True)
    display.DisplayShape(facesS_2, update=True)

    section_edges = list(Topo(facesS_2).edges())
    print(len(section_edges))

    '''toptool_seq_shape = TopTools_SequenceOfShape()
    for edge in section_edges:
        toptool_seq_shape.Append(edge)'''

    Wire_c = BRepBuilderAPI_MakeWire()
    prep_list = []
    Wire_c.Add(section_edges[0])
    prep_list.append(section_edges[0])
    ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

    # no need for a loop since we know for a fact that
    # the edge has only one start and one end
    c = ex.Current()
    cv = topods_Vertex(c)
    v0 = BRep_Tool_Pnt(cv)
    ex.Next()
    c = ex.Current()
    cv = topods_Vertex(c)
    v1 = BRep_Tool_Pnt(cv)
    section_edges.pop(0)
    flag = 0
    wires = []

    while len(section_edges) > 0:

        new_list = []

        for edges in section_edges:
            #Wire_c.Add(edges)
            ex = TopExp_Explorer(edges, TopAbs_VERTEX)
            c = ex.Current()
            cv = topods_Vertex(c)
            End_1 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            End_2 = BRep_Tool_Pnt(cv)

            if End_1.X() == v0.X() and End_1.Y() == v0.Y() and End_1.Z() == v0.Z():
                Wire_c.Add(edges)
                v0 = End_2
                flag = 0
            elif End_1.X() == v1.X() and End_1.Y() == v1.Y() and End_1.Z() == v1.Z():
                Wire_c.Add(edges)
                v1 = End_2
                flag = 0
            elif End_2.X() == v0.X() and End_2.Y() == v0.Y() and End_2.Z() == v0.Z():
                Wire_c.Add(edges)
                v0 = End_1
                flag = 0
            elif End_2.X() == v1.X() and End_2.Y() == v1.Y() and End_2.Z() == v1.Z():
                Wire_c.Add(edges)
                v1 = End_1
                flag = 0
            else:
                new_list.append(edges)

        flag += 1
        section_edges = new_list

        if flag >= 5:
            print('number_ostalos', len(section_edges))
            wires.append(Wire_c.Wire())
            #wir = Wire_c.Wire()
            print('ttttt')
            Wire_c = BRepBuilderAPI_MakeWire()

            Wire_c.Add(section_edges[0])
            ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

            # no need for a loop since we know for a fact that
            # the edge has only one start and one end
            c = ex.Current()
            cv = topods_Vertex(c)
            v0 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            v1 = BRep_Tool_Pnt(cv)
            section_edges.pop(0)
            flag = 0

    # wires.append(Wire_c.Wire())
    wires.append(bild_wire(Wire_c))
    props = GProp_GProps()

    yellow_wire = wires[0]
    brown_face = BRepBuilderAPI_MakeFace(yellow_wire)
    brown_face = brown_face.Face()
    brepgprop_SurfaceProperties(brown_face, props)
    face_surf = props.Mass()
    print(face_surf)
    #display.DisplayColoredShape(brown_face.Face(), 'BLUE')


    areas = []
    props = GProp_GProps()

    for wire in wires:
        brown_face = BRepBuilderAPI_MakeFace(wire)
        brown_face = brown_face.Face()
        #props = GProp_GProps()
        brepgprop_SurfaceProperties(brown_face, props)
        areas.append(props.Mass())


    print(areas)


    print(len(wires))
Пример #27
0
def cut_out(base):
    outer = gp_Circ2d(gp_OX2d(), top_radius - 1.75 * roller_diameter)
    inner = gp_Circ2d(gp_OX2d(), center_radius + 0.75 * roller_diameter)

    geom_outer = GCE2d_MakeCircle(outer).Value()
    geom_inner = GCE2d_MakeCircle(inner).Value()
    geom_inner.Reverse()

    base_angle = (2. * M_PI) / mounting_hole_count
    hole_angle = atan(hole_radius / mounting_radius)
    correction_angle = 3 * hole_angle

    left = gp_Lin2d(gp_Origin2d(), gp_DX2d())
    right = gp_Lin2d(gp_Origin2d(), gp_DX2d())
    left.Rotate(gp_Origin2d(), correction_angle)
    right.Rotate(gp_Origin2d(), base_angle - correction_angle)

    geom_left = GCE2d_MakeLine(left).Value()
    geom_right = GCE2d_MakeLine(right).Value()

    inter_1 = Geom2dAPI_InterCurveCurve(geom_outer, geom_left)
    inter_2 = Geom2dAPI_InterCurveCurve(geom_outer, geom_right)
    inter_3 = Geom2dAPI_InterCurveCurve(geom_inner, geom_right)
    inter_4 = Geom2dAPI_InterCurveCurve(geom_inner, geom_left)

    if inter_1.Point(1).X() > 0:
        p1 = inter_1.Point(1)
    else:
        p1 = inter_1.Point(2)

    if inter_2.Point(1).X() > 0:
        p2 = inter_2.Point(1)
    else:
        p2 = inter_2.Point(2)

    if inter_3.Point(1).X() > 0:
        p3 = inter_3.Point(1)
    else:
        p3 = inter_3.Point(2)

    if inter_4.Point(1).X() > 0:
        p4 = inter_4.Point(1)
    else:
        p4 = inter_4.Point(2)

    trimmed_outer = GCE2d_MakeArcOfCircle(outer, p1, p2).Value()
    trimmed_inner = GCE2d_MakeArcOfCircle(inner, p4, p3).Value()

    plane = gp_Pln(gp_Origin(), gp_DZ())

    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_outer, plane)).Edge()

    lin1 = BRepBuilderAPI_MakeEdge(gp_Pnt(p2.X(), p2.Y(), 0),
                                   gp_Pnt(p3.X(), p3.Y(), 0)).Edge()

    arc2 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_inner, plane)).Edge()

    lin2 = BRepBuilderAPI_MakeEdge(gp_Pnt(p4.X(), p4.Y(), 0),
                                   gp_Pnt(p1.X(), p1.Y(), 0)).Edge()

    cutout_wire = BRepBuilderAPI_MakeWire(arc1)
    cutout_wire.Add(lin1)
    cutout_wire.Add(arc2)
    cutout_wire.Add(lin2)

    # Turn the wire into a face
    cutout_face = BRepBuilderAPI_MakeFace(cutout_wire.Wire())
    filleted_face = BRepFilletAPI_MakeFillet2d(cutout_face.Face())

    explorer = BRepTools_WireExplorer(cutout_wire.Wire())
    while explorer.More():
        vertex = explorer.CurrentVertex()
        filleted_face.AddFillet(vertex, roller_radius)
        explorer.Next()

    cutout = BRepPrimAPI_MakePrism(filleted_face.Shape(),
                                   gp_Vec(0.0, 0.0, thickness)).Shape()

    result = base
    rotate = gp_Trsf()
    for i in range(0, mounting_hole_count):
        rotate.SetRotation(gp_OZ(), i * 2. * M_PI / mounting_hole_count)
        rotated_cutout = BRepBuilderAPI_Transform(cutout, rotate, True)

        result = BRepAlgoAPI_Cut(result,
                                 rotated_cutout.Shape()).Shape()

    return result
Пример #28
0
def build_tooth():
    base_center = gp_Pnt2d(pitch_circle_radius + (tooth_radius - roller_radius), 0)
    base_circle = gp_Circ2d(gp_Ax2d(base_center, gp_Dir2d()), tooth_radius)
    trimmed_base = GCE2d_MakeArcOfCircle(base_circle,
                                         M_PI - (roller_contact_angle / 2.),
                                         M_PI).Value()
    trimmed_base.Reverse()  # just a trick
    p0 = trimmed_base.StartPoint()
    p1 = trimmed_base.EndPoint()

    # Determine the center of the profile circle
    x_distance = cos(roller_contact_angle / 2.) * (profile_radius + tooth_radius)
    y_distance = sin(roller_contact_angle / 2.) * (profile_radius + tooth_radius)
    profile_center = gp_Pnt2d(pitch_circle_radius - x_distance, y_distance)

    # Construct the profile circle gp_Circ2d
    profile_circle = gp_Circ2d(gp_Ax2d(profile_center, gp_Dir2d()),
                               profile_center.Distance(p1))
    geom_profile_circle = GCE2d_MakeCircle(profile_circle).Value()

    # Construct the outer circle gp_Circ2d
    outer_circle = gp_Circ2d(gp_Ax2d(gp_Pnt2d(0, 0), gp_Dir2d()), top_radius)
    geom_outer_circle = GCE2d_MakeCircle(outer_circle).Value()

    inter = Geom2dAPI_InterCurveCurve(geom_profile_circle, geom_outer_circle)
    num_points = inter.NbPoints()
    assert isinstance(p1, gp_Pnt2d)
    if num_points == 2:
        if p1.Distance(inter.Point(1)) < p1.Distance(inter.Point(2)):
            p2 = inter.Point(1)
        else:
            p2 = inter.Point(2)
    elif num_points == 1:
        p2 = inter.Point(1)
    else:
        sys.exit(-1)

    # Trim the profile circle and mirror
    trimmed_profile = GCE2d_MakeArcOfCircle(profile_circle, p1, p2).Value()

    # Calculate the outermost point
    p3 = gp_Pnt2d(cos(tooth_angle / 2.) * top_radius,
                  sin(tooth_angle / 2.) * top_radius)

    # and use it to create the third arc
    trimmed_outer = GCE2d_MakeArcOfCircle(outer_circle, p2, p3).Value()

    # Mirror and reverse the three arcs
    mirror_axis = gp_Ax2d(gp_Origin2d(), gp_DX2d().Rotated(tooth_angle / 2.))

    mirror_base = Geom2d_TrimmedCurve.DownCast(trimmed_base.Copy())
    mirror_profile = Geom2d_TrimmedCurve.DownCast(trimmed_profile.Copy())
    mirror_outer = Geom2d_TrimmedCurve.DownCast(trimmed_outer.Copy())

    mirror_base.Mirror(mirror_axis)
    mirror_profile.Mirror(mirror_axis)
    mirror_outer.Mirror(mirror_axis)

    mirror_base.Reverse()
    mirror_profile.Reverse()
    mirror_outer.Reverse()

    # Replace the two outer arcs with a single one
    outer_start = trimmed_outer.StartPoint()
    outer_mid = trimmed_outer.EndPoint()
    outer_end = mirror_outer.EndPoint()

    outer_arc = GCE2d_MakeArcOfCircle(outer_start, outer_mid, outer_end).Value()

    # Create an arc for the inside of the wedge
    inner_circle = gp_Circ2d(gp_Ax2d(gp_Pnt2d(0, 0), gp_Dir2d()),
                             top_radius - roller_diameter)
    inner_start = gp_Pnt2d(top_radius - roller_diameter, 0)
    inner_arc = GCE2d_MakeArcOfCircle(inner_circle, inner_start, tooth_angle).Value()
    inner_arc.Reverse()

    # Convert the 2D arcs and two extra lines to 3D edges
    plane = gp_Pln(gp_Origin(), gp_DZ())
    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_base, plane)).Edge()
    arc2 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_profile, plane)).Edge()
    arc3 = BRepBuilderAPI_MakeEdge(geomapi_To3d(outer_arc, plane)).Edge()
    arc4 = BRepBuilderAPI_MakeEdge(geomapi_To3d(mirror_profile, plane)).Edge()
    arc5 = BRepBuilderAPI_MakeEdge(geomapi_To3d(mirror_base, plane)).Edge()

    p4 = mirror_base.EndPoint()
    p5 = inner_arc.StartPoint()

    lin1 = BRepBuilderAPI_MakeEdge(gp_Pnt(p4.X(), p4.Y(), 0),
                                   gp_Pnt(p5.X(), p5.Y(), 0)).Edge()
    arc6 = BRepBuilderAPI_MakeEdge(geomapi_To3d(inner_arc, plane)).Edge()

    p6 = inner_arc.EndPoint()
    lin2 = BRepBuilderAPI_MakeEdge(gp_Pnt(p6.X(), p6.Y(), 0),
                                   gp_Pnt(p0.X(), p0.Y(), 0)).Edge()

    wire = BRepBuilderAPI_MakeWire(arc1)
    wire.Add(arc2)
    wire.Add(arc3)
    wire.Add(arc4)
    wire.Add(arc5)
    wire.Add(lin1)
    wire.Add(arc6)
    wire.Add(lin2)

    face = BRepBuilderAPI_MakeFace(wire.Wire())

    wedge = BRepPrimAPI_MakePrism(face.Shape(), gp_Vec(0.0, 0.0, thickness))

    return wedge.Shape()
Пример #29
0
def _build_solid(compound, divide_closed):
    """
    Try to build a solid from the OpenVSP compound of faces.

    :param afem.topology.entities.Compound compound: The compound.
    :param bool divide_closed: Option to divide closed faces.

    :return: The solid.
    :rtype: afem.topology.entities.Solid
    """
    # Get all the faces in the compound. The surfaces must be split. Discard
    # any with zero area.
    faces = []
    for face in compound.faces:
        area = SurfaceProps(face).area
        if area > 1.0e-7:
            faces.append(face)

    # Replace any planar B-Spline surfaces with planes.
    non_planar_faces = []
    planar_faces = []
    for f in faces:
        srf = f.surface
        try:
            pln = srf.as_plane()
            if pln:
                w = f.outer_wire
                # Fix the wire because they are usually degenerate edges in
                # the planar end caps.
                builder = BRepBuilderAPI_MakeWire()
                for e in w.edges:
                    if LinearProps(e).length > 1.0e-7:
                        builder.Add(e.object)
                w = builder.Wire()
                fix = ShapeFix_Wire()
                fix.Load(w)
                fix.SetSurface(pln.object)
                fix.FixReorder()
                fix.FixConnected()
                fix.FixEdgeCurves()
                fix.FixDegenerated()
                w = Wire(fix.WireAPIMake())
                fnew = Face.by_wire(w)
                planar_faces.append(fnew)
            else:
                non_planar_faces.append(f)
        except RuntimeError:
            logger.info('Failed to check for planar face...')
            non_planar_faces.append(f)

    # Make a compound of the faces
    shape = Compound.by_shapes(non_planar_faces + planar_faces)

    # Split closed faces
    if divide_closed:
        shape = DivideClosedShape(shape).shape

    # Sew shape
    sewn_shape = SewShape(shape).sewed_shape
    if isinstance(sewn_shape, Face):
        sewn_shape = sewn_shape.to_shell()

    # Attempt to unify planar domains
    shell = UnifyShape(sewn_shape).shape

    # Make solid
    if not isinstance(shell, Shell):
        logger.info('\tA valid shell was not able to be generated.')
        check = CheckShape(shell)
        if not check.is_valid:
            logger.info('\tShape errors:')
            check.log_errors()
        return shell, check.invalid_shapes

    solid = Solid.by_shell(shell)

    # Limit tolerance
    FixShape.limit_tolerance(solid)

    # Check the solid and attempt to fix
    invalid = []
    check = CheckShape(solid)
    if not check.is_valid:
        logger.info('\tFixing the solid...')
        solid = FixShape(solid).shape
        check = CheckShape(solid)
        if not check.is_valid:
            logger.info('\t...solid could not be fixed.')
            logger.info('\tShape errors:')
            check.log_errors()
            failed = check.invalid_shapes
            invalid += failed
    else:
        tol = solid.tol_avg
        logger.info(
            '\tSuccessfully generated solid with tolerance={}'.format(tol))

    return solid, invalid
Пример #30
0
def _helix(r, h, step=None, pitch=None, angle=0, left=False):
    radius = r
    height = h

    if pitch:
        pitch = math.sin(pitch) * 2 * math.pi * r
    else:
        pitch = step

    if pitch < precision_Confusion():
        raise Exception("Pitch of helix too small")

    if height < precision_Confusion():
        raise Exception("Height of helix too small")

    cylAx2 = gp_Ax2(gp_Pnt(0.0, 0.0, 0.0), gp_DZ())

    if abs(angle) < precision_Confusion():
        # Cylindrical helix
        if radius < precision_Confusion():
            raise Exception("Radius of helix too small")

        surf = Geom_CylindricalSurface(gp_Ax3(cylAx2), radius)
        isCylinder = True
    else:
        # Conical helix
        if abs(angle) < precision_Confusion():
            raise Exception("Angle of helix too small")

        surf = Geom_ConicalSurface(gp_Ax3(cylAx2), angle, radius)
        isCylinder = False

    turns = height / pitch
    wholeTurns = math.floor(turns)
    partTurn = turns - wholeTurns

    aPnt = gp_Pnt2d(0, 0)
    aDir = gp_Dir2d(2. * math.pi, pitch)
    coneDir = 1.0

    if left:
        aDir.SetCoord(-2. * math.pi, pitch)
        coneDir = -1.0

    aAx2d = gp_Ax2d(aPnt, aDir)
    line = Geom2d_Line(aAx2d)
    beg = line.Value(0)

    mkWire = BRepBuilderAPI_MakeWire()

    for i in range(wholeTurns):
        if isCylinder:
            end = line.Value(
                math.sqrt(4.0 * math.pi * math.pi + pitch * pitch) * (i + 1))
        else:
            u = coneDir * (i + 1) * 2.0 * math.pi
            v = ((i + 1) * pitch) / math.cos(angle)
            end = gp_Pnt2d(u, v)

        segm = GCE2d_MakeSegment(beg, end).Value()
        edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf).Edge()
        mkWire.Add(edgeOnSurf)
        beg = end

    if partTurn > precision_Confusion():
        if (isCylinder):
            end = line.Value(
                math.sqrt(4.0 * math.pi * math.pi + pitch * pitch) * turns)
        else:
            u = coneDir * turns * 2.0 * math.pi
            v = height / math.cos(angle)
            end = gp_Pnt2d(u, v)

        segm = GCE2d_MakeSegment(beg, end).Value()
        edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf).Edge()
        mkWire.Add(edgeOnSurf)

    shape = mkWire.Wire()
    breplib.BuildCurves3d(shape)
    return Shape(shape)