Esempio n. 1
0
def through_sections():
    #ruled
    circle_1 = gp_Circ(gp_Ax2(gp_Pnt(-100., 0., -100.), gp_Dir(0., 0., 1.)),
                       40.)
    wire_1 = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_1).Edge()).Wire()
    circle_2 = gp_Circ(gp_Ax2(gp_Pnt(-10., 0., -0.), gp_Dir(0., 0., 1.)), 40.)
    wire_2 = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_2).Edge()).Wire()
    circle_3 = gp_Circ(gp_Ax2(gp_Pnt(-75., 0., 100.), gp_Dir(0., 0., 1.)), 40.)
    wire_3 = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_3).Edge()).Wire()
    circle_4 = gp_Circ(gp_Ax2(gp_Pnt(0., 0., 200.), gp_Dir(0., 0., 1.)), 40.)
    wire_4 = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_4).Edge()).Wire()

    generatorA = BRepOffsetAPI_ThruSections(False, True)
    # the use of the map function fails at producing the ThruSection
    # on py3k. Why ?
    # map(generatorA.AddWire, [wire_1, wire_2, wire_3, wire_4])
    # we have to use a loop
    for wir in [wire_1, wire_2, wire_3, wire_4]:
        generatorA.AddWire(wir)
    generatorA.Build()
    display.DisplayShape(generatorA.Shape())

    #smooth
    circle_1b = gp_Circ(gp_Ax2(gp_Pnt(100., 0., -100.), gp_Dir(0., 0., 1.)),
                        40.)
    wire_1b = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_1b).Edge()).Wire()
    circle_2b = gp_Circ(gp_Ax2(gp_Pnt(210., 0., -0.), gp_Dir(0., 0., 1.)), 40.)
    wire_2b = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_2b).Edge()).Wire()
    circle_3b = gp_Circ(gp_Ax2(gp_Pnt(275., 0., 100.), gp_Dir(0., 0., 1.)),
                        40.)
    wire_3b = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_3b).Edge()).Wire()
    circle_4b = gp_Circ(gp_Ax2(gp_Pnt(200., 0., 200.), gp_Dir(0., 0., 1.)),
                        40.)
    wire_4b = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(circle_4b).Edge()).Wire()
    generatorB = BRepOffsetAPI_ThruSections(True, False)
    # same here, the following line fails
    # map(generatorB.AddWire, [wire_1b, wire_2b, wire_3b, wire_4b])
    for wir in [wire_1b, wire_2b, wire_3b, wire_4b]:
        generatorB.AddWire(wir)
    generatorB.Build()
    display.DisplayShape(generatorB.Shape(), update=True)
Esempio n. 2
0
def extrusion_to_ruled_surfaces(extrusion, cap=True):
    from OCC.Core.BRepOffsetAPI import BRepOffsetAPI_ThruSections
    from youbastard.geometry.Extrusion import Extrusion
    from youbastard.geo_functions import assembly_polylines3d
    #from OCC.Display.SimpleGui import init_display
    #display, start_display, add_menu, add_function_to_menu = init_display()
    dico = {}
    for k in extrusion.keys():
        array_of_polylines = extrusion[k]
        generator = BRepOffsetAPI_ThruSections(False, True)
        for pol in array_of_polylines:
            wire = wire_from_polyline(pol)
            generator.AddWire(wire.Wire())
            #dico[k].append(wire.Shape())
        generator.Build()
        dico[k] = generator
    if cap:
        first_cap_polylines = []
        last_cap_polylines = []
        for k in extrusion.keys():
            first_cap_polylines.append(extrusion[k][0])
            last_cap_polylines.append(extrusion[k][-1])
        ordered_first = assembly_polylines3d(first_cap_polylines)
        ordered_last = assembly_polylines3d(last_cap_polylines)
        print ordered_first
        dico['first_tip'] = face_polyline3d(ordered_first)
        dico['last_tip'] = face_polyline3d(ordered_last)
    return dico
Esempio n. 3
0
    def __init__(self):
        plotocc.__init__(self)
        self.axs = gp_Ax3()

        p_array = TColgp_Array1OfPnt(1, 100)
        for idx, pt in enumerate(np.linspace(-2.0, 2.0, 100)):
            pnt = gp_Pnt(300 * np.sin(pt), 100 * np.cos(3 * pt), 0)
            p_array.SetValue(idx + 1, pnt)
        api = GeomAPI_PointsToBSpline(p_array)
        self.curv = api.Curve()
        print(self.curv)

        api = BRepOffsetAPI_ThruSections()
        api.SetSmoothing(True)
        num_list = [
            3, 3, 3, 3, 3,
            6, 6, 6, 6, 6, 6, 6, 6, 6,
            7, 7, 7, 7, 7, 7, 7, 7,
            4, 4, 4
        ]
        p1, v1, v2 = gp_Pnt(), gp_Vec(), gp_Vec()
        for idx, pt in enumerate(np.linspace(0.0, 0.5, len(num_list))):
            GeomLProp_CurveTool.D2(self.curv, pt, p1, v1, v2)
            v3 = v1.Crossed(v2)
            axis = gp_Ax3(p1, vec_to_dir(v1), vec_to_dir(v2))
            poly = self.make_PolyWire(num=num_list[idx], radi=20, axs=axis)
            api.AddWire(poly)
            self.show_axs_pln(axis, scale=10)
            self.display.DisplayShape(poly)
        api.Build()
        self.display.DisplayShape(api.Shape())
        write_step_file(api.Shape(), "./tmp/ThruPipe_Hex.stp")

        api = BRepOffsetAPI_ThruSections()
        # api.SetSmoothing(True)
        p1, v1, v2 = gp_Pnt(), gp_Vec(), gp_Vec()
        for idx, pt in enumerate(np.linspace(0.55, 1.0, 20)):
            GeomLProp_CurveTool.D2(self.curv, pt, p1, v1, v2)
            v3 = v1.Crossed(v2)
            axis = gp_Ax3(p1, vec_to_dir(v1), vec_to_dir(v2))
            shft = 90 * pt
            poly = self.make_Ellip(rxy=[15, 10], shft=shft, axs=axis)
            api.AddWire(poly)
            self.display.DisplayShape(poly)
        api.Build()
        self.display.DisplayShape(api.Shape())
        write_step_file(api.Shape(), "./tmp/ThruPipe_Ellip.stp")
Esempio n. 4
0
 def make_Thru(self, num=50):
     api = BRepOffsetAPI_ThruSections()
     print(self.poly.Location().Transformation())
     for idx, phi in enumerate(np.linspace(0, 2 * np.pi, num)):
         ax = self.poly_axs.Rotated(self.axs.Axis(), phi)
         poly_i = self.poly.Located(set_loc(gp_Ax3(), ax))
         # print(poly_i.Location().Transformation())
         api.AddWire(poly_i)
         self.display.DisplayShape(poly_i)
     api.Build()
     return api.Shape()
Esempio n. 5
0
def _loft(arr, smooth=False, shell=False, maxdegree=4):
    builder = BRepOffsetAPI_ThruSections(not shell, not smooth)
    builder.SetMaxDegree(maxdegree)

    for v in arr:
        if v.Shape().ShapeType() == TopAbs_FACE:
            raise Exception("Loft argument must be array of Wires or Edges")

    for r in arr:
        builder.AddWire(r.Wire_orEdgeToWire())

    return Shape(builder.Shape())
Esempio n. 6
0
    def gen_through(self):
        obj = BRepOffsetAPI_ThruSections()

        ax2_1 = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))
        crl_1 = gp_Circ(ax2_1, 100)
        obj.AddWire(crl_1)

        ax2_2 = gp_Ax2(gp_Pnt(0, 0, 100), gp_Dir(0, 0, 1))
        crl_2 = gp_Circ(ax2_2, 200)
        obj.AddWire(crl_2)

        obj.Build()
        self.display.DisplayShape(obj.Shape())
Esempio n. 7
0
File: blade.py Progetto: o4fr/BladeX
    def _generate_tip(self, maxDeg):
        """
        Private method to generate the surface that closing the blade tip.

        :param int maxDeg: Define the maximal U degree of generated surface
        """
        self._import_occ_libs()

        generator = BRepOffsetAPI_ThruSections(False, False, 1e-10)
        generator.SetMaxDegree(maxDeg)
        # npoints_up == npoints_down
        npoints = len(self.blade_coordinates_down[-1][0])
        vertices_1 = TColgp_HArray1OfPnt(1, npoints)
        vertices_2 = TColgp_HArray1OfPnt(1, npoints)
        for j in range(npoints):
            vertices_1.SetValue(
                j + 1,
                gp_Pnt(1000 * self.blade_coordinates_down[-1][0][j],
                       1000 * self.blade_coordinates_down[-1][1][j],
                       1000 * self.blade_coordinates_down[-1][2][j]))

            vertices_2.SetValue(
                j + 1,
                gp_Pnt(1000 * self.blade_coordinates_up[-1][0][j],
                       1000 * self.blade_coordinates_up[-1][1][j],
                       1000 * self.blade_coordinates_up[-1][2][j]))

        # Initializes an algorithm for constructing a constrained
        # BSpline curve passing through the points of the blade last
        # section, with tolerance = 1e-9
        bspline_1 = GeomAPI_Interpolate(vertices_1, False, 1e-9)
        bspline_1.Perform()

        bspline_2 = GeomAPI_Interpolate(vertices_2, False, 1e-9)
        bspline_2.Perform()

        edge_1 = BRepBuilderAPI_MakeEdge(bspline_1.Curve()).Edge()
        edge_2 = BRepBuilderAPI_MakeEdge(bspline_2.Curve()).Edge()

        # Add BSpline wire to the generator constructor
        generator.AddWire(BRepBuilderAPI_MakeWire(edge_1).Wire())
        generator.AddWire(BRepBuilderAPI_MakeWire(edge_2).Wire())
        # Returns the shape built by the shape construction algorithm
        generator.Build()
        # Returns the Face generated by each edge of the first section
        self.generated_tip = generator.GeneratedFace(edge_1)
Esempio n. 8
0
def make_loft(elements, ruled=False, tolerance=TOLERANCE, continuity=GeomAbs_C2, check_compatibility=True):
    from OCC.Core.BRepOffsetAPI import BRepOffsetAPI_ThruSections
    sections = BRepOffsetAPI_ThruSections(False, ruled, tolerance)
    for i in elements:
        if isinstance(i, TopoDS_Wire):
            sections.AddWire(i)
        elif isinstance(i, TopoDS_Vertex):
            sections.AddVertex(i)
        else:
            raise TypeError('elements is a list of TopoDS_Wire or TopoDS_Vertex, found a %s fool' % i.__class__)

    sections.CheckCompatibility(check_compatibility)
    sections.SetContinuity(continuity)
    sections.Build()
    with assert_isdone(sections, 'failed lofting'):
        te = ShapeToTopology()
        loft = te(sections.Shape())
        return loft
Esempio n. 9
0
def getShapeSkin(pntStart, wires, pntEnd):

    # Initialize and build
    skiner = BRepOffsetAPI_ThruSections()
    skiner.SetSmoothing(True)
    #skiner.SetMaxDegree(5)

    vstart = BRepBuilderAPI_MakeVertex(pntStart).Vertex()
    skiner.AddVertex(vstart)

    for wire in wires:
        skiner.AddWire(wire)

    vend = BRepBuilderAPI_MakeVertex(pntEnd).Vertex()
    skiner.AddVertex(vend)

    skiner.Build()

    return skiner.Shape()
Esempio n. 10
0
    def loft(self, solid=True, ruled=True, precision=0.000001):
        wires = collect_wires(self)

        self.children = []

        generator = BRepOffsetAPI_ThruSections(solid, ruled, precision)

        for w in wires:
            debug("wire: %s" % (str(w), ))
            generator.AddWire(w)
        generator.Build()

        shape = generator.Shape()
        scls = SCLShape(shape)
        sclp = SCLPart3(self)
        sclp.set_shape(scls)
        name = get_inc_name("loft")
        sclp.set_name(name)
        debug("Creating loft %s" % (name, ))
        self.add_child_context(sclp)
Esempio n. 11
0
    def __init__(self,
                 sections,
                 is_solid=False,
                 make_ruled=False,
                 pres3d=1.0e-6,
                 check_compatibility=None,
                 use_smoothing=None,
                 par_type=None,
                 continuity=None,
                 max_degree=None):
        self._tool = BRepOffsetAPI_ThruSections(is_solid, make_ruled, pres3d)

        if check_compatibility is not None:
            self._tool.CheckCompatibility(check_compatibility)

        if use_smoothing is not None:
            self._tool.SetSmoothing(use_smoothing)

        if par_type is not None:
            self._tool.SetParType(par_type)

        if continuity is not None:
            self._tool.SetContinuity(continuity)

        if max_degree is not None:
            self._tool.SetMaxDegree(max_degree)

        for section in sections:
            if section.is_vertex:
                self._tool.AddVertex(section.object)
            elif section.is_edge:
                wire = Wire.by_edge(section)
                self._tool.AddWire(wire.object)
            elif section.is_wire:
                self._tool.AddWire(section.object)
            else:
                raise TypeError('Invalid shape type in loft.')

        self._tool.Build()
Esempio n. 12
0
File: blade.py Progetto: o4fr/BladeX
    def _generate_lower_face(self, maxDeg):
        """
        Private method to generate the blade lower face.

        :param int maxDeg: Define the maximal U degree of generated surface
        """
        self._import_occ_libs()
        # Initializes ThruSections algorithm for building a shell passing
        # through a set of sections (wires). The generated faces between
        # the edges of every two consecutive wires are smoothed out with
        # a precision criterion = 1e-10
        generator = BRepOffsetAPI_ThruSections(False, False, 1e-10)
        generator.SetMaxDegree(maxDeg)
        # Define upper edges (wires) for the face generation
        for i in range(self.n_sections):
            npoints = len(self.blade_coordinates_down[i][0])
            vertices = TColgp_HArray1OfPnt(1, npoints)
            for j in range(npoints):
                vertices.SetValue(
                    j + 1,
                    gp_Pnt(1000 * self.blade_coordinates_down[i][0][j],
                           1000 * self.blade_coordinates_down[i][1][j],
                           1000 * self.blade_coordinates_down[i][2][j]))
            # Initializes an algorithm for constructing a constrained
            # BSpline curve passing through the points of the blade i-th
            # section, with tolerance = 1e-9
            bspline = GeomAPI_Interpolate(vertices, False, 1e-9)
            bspline.Perform()
            edge = BRepBuilderAPI_MakeEdge(bspline.Curve()).Edge()
            if i == 0:
                bound_root_edge = edge
            # Add BSpline wire to the generator constructor
            generator.AddWire(BRepBuilderAPI_MakeWire(edge).Wire())
        # Returns the shape built by the shape construction algorithm
        generator.Build()
        # Returns the Face generated by each edge of the first section
        self.generated_lower_face = generator.GeneratedFace(bound_root_edge)
Esempio n. 13
0
    def getDaoSkinningSurface(self, offset):

        limitPoints = self.getCached('getDaoOffsetPoints', offset)
        beginPoint = limitPoints['Begin']
        endPoint = limitPoints['End']

        skinner = BRepOffsetAPI_ThruSections(True)
        skinner.SetSmoothing(True)

        beginVertex = BRepBuilderAPI_MakeVertex(beginPoint).Vertex()
        skinner.AddVertex(beginVertex)

        ks = self.aSkinningSlicesKs
        for i in range(len(ks)):
            sliceWire = self.getCached('getDaoSliceWire', offset, ks[i])
            skinner.AddWire(sliceWire)

        endVertex = BRepBuilderAPI_MakeVertex(endPoint).Vertex()
        skinner.AddVertex(endVertex)

        skinner.Build()
        surface = skinner.Shape()

        return surface
Esempio n. 14
0
def get_aligned_boundingbox_ratio(shape, tol=1e-6, optimal_BB=True, ratio=1):
    """ return the bounding box of the TopoDS_Shape `shape`

    Parameters
    ----------

    shape : TopoDS_Shape or a subclass such as TopoDS_Face
        the shape to compute the bounding box from

    tol: float
        tolerance of the computed boundingbox

    use_triangulation : bool, True by default
        This makes the computation more accurate

    ratio : float, 1.0 by default.

    Returns
    -------
        if `as_pnt` is True, return a tuple of gp_Pnt instances
         for the lower and another for the upper X,Y,Z values representing the bounding box

        if `as_pnt` is False, return a tuple of lower and then upper X,Y,Z values
         representing the bounding box
    """
    bbox = Bnd_Box()
    bbox.SetGap(tol)

    # note: useTriangulation is True by default, we set it explicitely, but t's not necessary
    if optimal_BB:
        use_triangulation = True
        use_shapetolerance = True
        brepbndlib_AddOptimal(shape, bbox, use_triangulation,
                              use_shapetolerance)
    else:
        brepbndlib_Add(shape, bbox)

    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    dx, mx = (xmax - xmin) * ratio, (xmax + xmin) / 2
    dy, my = (ymax - ymin) * ratio, (ymax + ymin) / 2
    dz, mz = (zmax - zmin) * ratio, (zmax + zmin) / 2
    x0, x1 = mx - dx / 2, mx + dx / 2
    y0, y1 = my - dy / 2, my + dy / 2
    z0, z1 = mz - dz / 2, mz + dz / 2
    corner1 = gp_Pnt(x0, y0, z0)
    corner2 = gp_Pnt(x1, y1, z1)
    center = midpoint(corner1, corner2)

    rim0 = make_polygon([
        gp_Pnt(x0, y0, z0),
        gp_Pnt(x1, y0, z0),
        gp_Pnt(x1, y1, z0),
        gp_Pnt(x0, y1, z0)
    ],
                        closed=True)

    rim1 = make_polygon([
        gp_Pnt(x0, y0, z1),
        gp_Pnt(x1, y0, z1),
        gp_Pnt(x1, y1, z1),
        gp_Pnt(x0, y1, z1)
    ],
                        closed=True)
    api = BRepOffsetAPI_ThruSections(True, False, 1.0E-9)
    api.AddWire(rim0)
    api.AddWire(rim1)
    box_shp = api.Shape()
    #box_shp = BRepPrimAPI_MakeBox(corner1, corner2).Shape()
    return center, [dx, dy, dz], box_shp
Esempio n. 15
0
a_point = [
    Point([0., span / float(ndisc), 0.]),
    Point([0.01, span / 4, 0.002]),
    Point([0., span / 2, 0.01]),
    Point([-0.02, 2. * span / 3., 0.015]),
    Point([-0.08, span, -0.02])
]

generator = Spline3D(a_point)
fa = generator.frame_array(mode=Vector([0., 0., 1.]), n=ndisc)

#fa = [Frame([[0.,0.,0.], [[0.,0.,1.],[1.,0.,0.],[0.,1.,0.]]])] + fa

shapes = []
generator_extrados = BRepOffsetAPI_ThruSections(False, True)
generator_intrados = BRepOffsetAPI_ThruSections(False, True)
generator_trailing_edge = BRepOffsetAPI_ThruSections(False, True)
generator = BRepOffsetAPI_ThruSections(False, True)
print dir(generator)

chord = lambda x: max_chord * chordf(x)
for i, f in enumerate(fa):
    # adimensioned position along span
    xspan = distance(fa[0][0], f[0]) / span

    # dimesioned chord value at xspan
    local_chord = chord(xspan)

    # the profile at this position
    pf = Profile(typ='fon',
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
bottle = TopoDS_Compound()
aBuilder = BRep_Builder()
aBuilder.MakeCompound(bottle)
aBuilder.Add(bottle, myBody_step3.Shape())
aBuilder.Add(bottle, myThreading)
print("bottle created")

export_shape_to_svg(bottle, "./test_mypy_classic_occ_bottle.svg")
write_step_file(bottle, "./test_mypy_classic_occ_bottle.stp")
Esempio n. 17
0
    wz = w0 * np.sqrt(1 + (wave * pz / (np.pi * w0**2))**2)
    t0 = wave / (np.pi * w0)

    obj_plt = plot2d(aspect="auto")
    obj_plt.axs.plot(pz, rz)

    obj_plt.new_fig(aspect="auto")
    obj_plt.axs.plot(pz, wz)
    obj_plt.axs.plot(pz, np.tan(t0) * pz)
    obj_plt.Show()

    #obj = plotocc()

    display, start_display, add_menu, add_function_to_menu = init_display()

    api = BRepOffsetAPI_ThruSections()
    for z in np.linspace(0, 1000, 10):
        r_z = z + 1 / z * (np.pi * w0 / wave)**2
        w_z = w0 * np.sqrt(1 + (wave * z / (np.pi * w0**2))**2)
        print(z, r_z, w_z)
        pnt = gp_Pnt(0, 0, z)
        axs = gp_Ax3(pnt, gp_Dir(0, 0, 1))
        ax2 = axs.Ax2()
        px = np.linspace(-1, 1, 100) * 100
        py = np.linspace(-1, 1, 100) * 100
        pxy = np.meshgrid(px, py)
        pz = -1 * (pxy[0]**2 / (2 * r_z) + pxy[1]**2 / (2 * r_z))
        pln = surf_spl(*pxy, pz, axs)
        wxy = Geom_Ellipse(ax2, w_z, w_z).Elips()
        wxy = BRepBuilderAPI_MakeWire(
            BRepBuilderAPI_MakeEdge(wxy).Edge()).Wire()
Esempio n. 18
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()
Esempio n. 19
0
 def through_section(sec_a, sec_b, solid_):
     generator_sec = BRepOffsetAPI_ThruSections(solid_, False)
     generator_sec.AddWire(sec_a)
     generator_sec.AddWire(sec_b)
     generator_sec.Build()
     return generator_sec.Shape()