Exemple #1
0
 def Compute(self):
     if len(self.myCurves) == 2:
         self.myGeometry = GeomFill_BezierCurves(self.myCurves[0],
                                                 self.myCurves[1],
                                                 self.myStyle)
     elif len(self.myCurves) == 3:
         self.myGeometry = GeomFill_BezierCurves(self.myCurves[0],
                                                 self.myCurves[1],
                                                 self.myCurves[2],
                                                 self.myStyle)
     elif len(self.myCurves) == 4:
         self.myGeometry = GeomFill_BezierCurves(self.myCurves[0],
                                                 self.myCurves[1],
                                                 self.myCurves[2],
                                                 self.myCurves[3],
                                                 self.myStyle)
     self.myGeometry = self.myGeometry.Surface()
     face = BRepBuilderAPI_MakeFace()
     face.Init(self.myGeometry, True, 1.0e-6)
     face.Build()
     face = face.Shape()
     self.myAIS_InteractiveObject = AIS_Shape(face)
     self.myContext.Display(self.myAIS_InteractiveObject, True)
     self.SetCenter(face)
     self.InitClippingPlane()
 def Compute(self):
     self.myGeometry = Geom_SurfaceOfRevolution(self.myCurve, self.myRevolveAxis)
     face = BRepBuilderAPI_MakeFace()
     face.Init(self.myGeometry, True, 1.0e-6)
     face.Build()
     self.myAIS_InteractiveObject = AIS_Shape(face.Shape())
     self.myContext.Display(self.myAIS_InteractiveObject, True)
Exemple #3
0
def pull():
    """Pull profile on active WP onto active part."""
    wp = win.activeWp
    if win.lineEditStack:
        length = float(win.lineEditStack.pop()) * win.unitscale
        wireOK = wp.makeWire()
        if not wireOK:
            print("Unable to make wire.")
            return
        wire = wp.wire
        workPart = win.activePart
        uid = win.activePartUID
        pullProfile = BRepBuilderAPI_MakeFace(wire)
        aPrismVec = wp.wVec * length
        tool = BRepPrimAPI_MakePrism(pullProfile.Shape(), aPrismVec).Shape()
        newPart = BRepAlgoAPI_Fuse(workPart, tool).Shape()
        win.erase_shape(uid)
        doc.replaceShape(uid, newPart)
        win.draw_shape(uid)
        win.setActivePart(uid)
        win.statusBar().showMessage("Pull operation complete")
        win.clearCallback()
    else:
        win.registerCallback(pullC)
        win.lineEdit.setFocus()
        statusText = "Enter pull distance (pos in +w direction)"
        win.statusBar().showMessage(statusText)
Exemple #4
0
def main():

    vertices = [gp_Pnt(p[0], p[1], p[2]) for p in mesh['vertices']]
    oFaces = []

    builder = BRep_Builder()
    shell = TopoDS_Shell()
    builder.MakeShell(shell)

    for face in mesh['faces']:
        edges = []
        face.reverse()
        for i in range(len(face)):
            cur = face[i]
            nxt = face[(i + 1) % len(face)]
            segment = GC_MakeSegment(vertices[cur], vertices[nxt])
            edges.append(BRepBuilderAPI_MakeEdge(segment.Value()))

        wire = BRepBuilderAPI_MakeWire()
        for edge in edges:
            wire.Add(edge.Edge())

        oFace = BRepBuilderAPI_MakeFace(wire.Wire())
        builder.Add(shell, oFace.Shape())
    write_stl_file(shell, "./cube_binding.stl")
Exemple #5
0
def extrude():
    """Extrude profile on active WP to create a new part."""
    wp = win.activeWp
    if len(win.lineEditStack) == 2:
        name = win.lineEditStack.pop()
        length = float(win.lineEditStack.pop()) * win.unitscale
        wireOK = wp.makeWire()
        if not wireOK:
            print("Unable to make wire.")
            return
        myFaceProfile = BRepBuilderAPI_MakeFace(wp.wire)
        aPrismVec = wp.wVec * length
        myBody = BRepPrimAPI_MakePrism(myFaceProfile.Shape(),
                                       aPrismVec).Shape()
        uid = doc.addComponent(myBody, name, DEFAULT_COLOR)
        win.build_tree()
        win.setActivePart(uid)
        win.draw_shape(uid)
        win.syncUncheckedToHideList()
        win.statusBar().showMessage("New part created.")
        win.clearCallback()
    else:
        win.registerCallback(extrudeC)
        win.lineEdit.setFocus()
        statusText = "Enter extrusion length, then enter part name."
        win.statusBar().showMessage(statusText)
Exemple #6
0
def extrude_polyline2d(polyline, frame, height):
    pol3d = polyline.to_frame(frame)
    lines = []
    yb_point = Point([frame[0][i] for i in range(3)])
    yb_vec = Vector([frame[1][0][i] for i in range(3)]).unit()
    print '*************'
    print yb_vec
    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]):
        print p
        print 'zob'
        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())
    print 'normal'
    print[vec.X(), vec.Y(), vec.Z()]
    extrude = BRepPrimAPI_MakePrism(
        face.Shape(),
        gp_Vec(height * vec.X(), height * vec.Y(), height * vec.Z())).Shape()
    return extrude
 def Compute(self):
     self.myGeometry = GeomFill_Pipe(self.myPath, self.myProfile,
                                     self.myProfile)
     self.myGeometry.Perform()
     face = BRepBuilderAPI_MakeFace()
     face.Init(self.myGeometry.Surface(), True, 1.0e-6)
     face.Build()
     self.myAIS_InteractiveObject = AIS_Shape(face.Shape())
     self.myContext.Display(self.myAIS_InteractiveObject, True)
    def _create_from_svg(cls, filepath, height_mm):
        assert isinstance(filepath, pathlib.Path)
        if not filepath.is_file():
            raise IOError(
                "Unable to create Face from image file: {}. File does not exist"
                .format(filepath))

        # Load as a document rather than as paths directly (using svg2paths) because
        # the document respects any transforms
        doc = Document(str(filepath))
        paths = doc.paths()
        continuous_paths = cls._get_continuous_subpaths(paths)
        continuous_paths = cls._remove_zero_length_lines(continuous_paths)

        ymin = min([path.bbox()[2] for path in continuous_paths])
        ymax = max([path.bbox()[3] for path in continuous_paths])
        current_height = ymax - ymin
        assert current_height >= 0
        scaling_factor = height_mm / current_height
        scaled_paths = [
            path.scaled(scaling_factor, -scaling_factor)
            for path in continuous_paths
        ]

        # Line up to the x and y axes
        xmin = min([path.bbox()[0] for path in scaled_paths])
        ymin = min([path.bbox()[2] for path in scaled_paths])
        translated_paths = [
            path.translated(complex(-xmin, -ymin)) for path in scaled_paths
        ]

        normalized_paths = cls._normalize_paths_clockwise(translated_paths)
        path_hierarchies = cls._create_path_hierarchy(normalized_paths)
        # Currently only really support a single main contiguous shape with holes.
        # Although multiple disconnected shapes can be generated, they won't be
        # perfectly represented by the final geometry because some material has to
        # connect them
        assert len(path_hierarchies) == 1

        faceMaker = BRepBuilderAPI_MakeFace(PL_XZ)
        for path_hierarchy in path_hierarchies:
            root_edges = cls._create_edges_from_path(
                path_hierarchy.root_path())
            root_wire = cls._create_wire_from_edges(root_edges)
            faceMaker.Add(root_wire)
            for sub_path in path_hierarchy.child_paths():
                sub_path_edges = cls._create_edges_from_path(sub_path)
                sub_path_wire = cls._create_wire_from_edges(sub_path_edges)
                # reverse the wire so it creates a hole
                sub_path_wire.Reverse()
                faceMaker.Add(sub_path_wire)
        return faceMaker.Shape()
def constrained_filling(event=None):

    # left
    pts1 = point_list_to_TColgp_Array1OfPnt((gp_Pnt(0, 0, 0.0),
                                             gp_Pnt(0, 1, 0.3),
                                             gp_Pnt(0, 2, -0.3),
                                             gp_Pnt(0, 3, 0.15),
                                             gp_Pnt(0, 4, 0)))
    # front
    pts2 = point_list_to_TColgp_Array1OfPnt((gp_Pnt(0, 0, 0.0),
                                             gp_Pnt(1, 0, -0.3),
                                             gp_Pnt(2, 0, 0.15),
                                             gp_Pnt(3, 0, 0),
                                             gp_Pnt(4, 0, 0)))
    # back
    pts3 = point_list_to_TColgp_Array1OfPnt((gp_Pnt(0, 4, 0),
                                             gp_Pnt(1, 4, 0.3),
                                             gp_Pnt(2, 4, -0.15),
                                             gp_Pnt(3, 4, 0),
                                             gp_Pnt(4, 4, 1)))
    # rechts
    pts4 = point_list_to_TColgp_Array1OfPnt((gp_Pnt(4, 0, 0),
                                             gp_Pnt(4, 1, 0),
                                             gp_Pnt(4, 2, 2),
                                             gp_Pnt(4, 3, -0.15),
                                             gp_Pnt(4, 4, 1)))

    spl1, b1 = get_simple_bound(pts1)
    spl2, b2 = get_simple_bound(pts2)
    spl3, b3 = get_simple_bound(pts3)
    spl4, b4 = get_simple_bound(pts4)

    # build the constrained surface
    bConstrainedFilling = GeomFill_ConstrainedFilling(8, 2)
    bConstrainedFilling.Init(b1, b2, b3, b4, False)
    srf1 = bConstrainedFilling.Surface()

    display.EraseAll()
    for i in [spl1, spl2, spl3, spl4]:
        edg = BRepBuilderAPI_MakeEdge(i)
        edg.Build()
        _edg = edg.Shape()
        display.DisplayShape(_edg)

    f = BRepBuilderAPI_MakeFace(srf1, 1e-6)
    f.Build()
    shp = f.Shape()
    return shp
def beziercurve():

    # the first bezier curve
    array = TColgp_Array1OfPnt(1, 5)
    array.SetValue(1, gp_Pnt(0, 0,-5))
    array.SetValue(2, gp_Pnt(1, 2,1))
    array.SetValue(3, gp_Pnt(2, 3,2))
    array.SetValue(4, gp_Pnt(4, 3,-2))
    array.SetValue(5, gp_Pnt(10, 5,-2))
    beziercurve = Geom_BezierCurve(array)
    # the first bezier curve
    array1 = TColgp_Array1OfPnt(1, 5)
    array1.SetValue(1, gp_Pnt(0, 0, -5))
    array1.SetValue(2, gp_Pnt(2, -2, 1))
    array1.SetValue(3, gp_Pnt(2, -3, 2))
    array1.SetValue(4, gp_Pnt(-4, 1, -2))
    array1.SetValue(5, gp_Pnt(1, 5, -2))
    beziercurve1 = Geom_BezierCurve(array1)

    array2 = TColgp_Array1OfPnt(1, 5)
    array2.SetValue(1, gp_Pnt(0, 0, -5))
    array2.SetValue(2, gp_Pnt(-2, 2, 1))
    array2.SetValue(3, gp_Pnt(2, -2, 2))
    array2.SetValue(4, gp_Pnt(-4, 8, -2))
    array2.SetValue(5, gp_Pnt(1, 5, -9))
    beziercurve2 = Geom_BezierCurve(array2)

    plane = Geom_Plane(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0, 1, 1))
    display.DisplayShape(plane, color='RED')

    surface1=GeomFill_BezierCurves(beziercurve,beziercurve1,beziercurve2,GeomFill_CurvedStyle)
    surface2 = GeomFill_BezierCurves(beziercurve, beziercurve1, GeomFill_StretchStyle)
    surface3 = GeomFill_BezierCurves(beziercurve, beziercurve1, GeomFill_CoonsStyle)

    bounds = True
    toldegen = 1e-6
    face = BRepBuilderAPI_MakeFace()
    face.Init(surface1.Surface(), bounds, toldegen)
    face.Build()

    shapes = face.Shape()

    fix=AIS_FixRelation(shapes,plane)
    display.Context.Display(fix, True)
    display.DisplayShape(shapes, color="RED")
    def Compute(self):
        if self.myConstructionMethod == SweepConstructionMethod.Radius:
            myGeometry = GeomFill_Pipe(self.myPath, self.myRadius)
        elif self.myConstructionMethod == SweepConstructionMethod.ConstantSection:
            myGeometry = GeomFill_Pipe(self.myPath, self.mySections[0])
        elif self.myConstructionMethod == SweepConstructionMethod.EvolvingSection:
            myGeometry = GeomFill_Pipe(self.myPath, self.mySections[0],
                                       self.mySections[1])
        myGeometry.Perform()
        self.myGeometry = myGeometry.Surface()
        face = BRepBuilderAPI_MakeFace()
        face.Init(self.myGeometry, True, 1.0e-6)
        face.Build()
        face = face.Shape()
        self.myAIS_InteractiveObject = AIS_Shape(face)
        self.myContext.Display(self.myAIS_InteractiveObject, True)

        self.SetCenter(face)
        self.InitClippingPlane()
Exemple #12
0
def holes_in_face():
    aPlane = gp_Pln()
    print(type(gp_Pln()))
    print(type(gp_XOY()))

    aCircle1 = gp_Circ(gp_XOY(), 1.0)
    aCircle2 = gp_Circ(gp_XOY(), 1.0)
    aCircle3 = gp_Circ(gp_XOY(), 1.0)

    aCircle1.SetLocation(gp_Pnt(3.0, 3.0, 0.0))
    aCircle2.SetLocation(gp_Pnt(7.0, 3.0, 0.0))
    aCircle3.SetLocation(gp_Pnt(3.0, 7.0, 0.0))

    anEdgeMaker1 = BRepBuilderAPI_MakeEdge(aCircle1)
    anEdgeMaker2 = BRepBuilderAPI_MakeEdge(aCircle2)
    anEdgeMaker3 = BRepBuilderAPI_MakeEdge(aCircle3)

    aWireMaker1 = BRepBuilderAPI_MakeWire(anEdgeMaker1.Edge())
    aWireMaker2 = BRepBuilderAPI_MakeWire(anEdgeMaker2.Edge())
    aWireMaker3 = BRepBuilderAPI_MakeWire(anEdgeMaker3.Edge())

    aFaceMaker = BRepBuilderAPI_MakeFace(aPlane, 0.0, 10.0, 0.0, 10.0)

    if aWireMaker1.IsDone():
        aWire1 = aWireMaker1.Wire()
        aWire1.Reverse()  # Makes this a hole in outer profile
        aFaceMaker.Add(aWire1)

    if aWireMaker2.IsDone():
        aWire2 = aWireMaker2.Wire()
        aWire2.Reverse()  # Makes this a hole in outer profile
        aFaceMaker.Add(aWire2)

    if aWireMaker3.IsDone():
        aWire3 = aWireMaker3.Wire()
        aWire3.Reverse()  # Makes this a hole in outer profile
        aFaceMaker.Add(aWire3)

    if not aFaceMaker.IsDone():
        raise AssertionError("shape not Done.")

    return aFaceMaker.Shape()
Exemple #13
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()
Exemple #14
0
def extrude():
    """Extrude profile on active WP to create a new part."""
    wp = win.activeWp
    if len(win.lineEditStack) == 2:
        name = win.lineEditStack.pop()
        length = float(win.lineEditStack.pop()) * win.unitscale
        wireOK = wp.makeWire()
        if not wireOK:
            print("Unable to make wire.")
            return
        myFaceProfile = BRepBuilderAPI_MakeFace(wp.wire)
        aPrismVec = wp.wVec * length
        myBody = BRepPrimAPI_MakePrism(myFaceProfile.Shape(),
                                       aPrismVec).Shape()
        uid = win.getNewPartUID(myBody, name=name)
        win.redraw()
    else:
        win.registerCallback(extrudeC)
        win.lineEdit.setFocus()
        statusText = "Enter extrusion length, then enter part name."
        win.statusBar().showMessage(statusText)
Exemple #15
0
def mill():
    """Mill profile on active WP into active part."""
    wp = win.activeWp
    if win.lineEditStack:
        length = float(win.lineEditStack.pop()) * win.unitscale
        wire = wp.wire
        if not wire:
            print("Need to 'makeWire' first.")
            return
        workPart = win.activePart
        wrkPrtUID = win.activePartUID
        punchProfile = BRepBuilderAPI_MakeFace(wire)
        aPrismVec = wp.wVec * length
        tool = BRepPrimAPI_MakePrism(punchProfile.Shape(), aPrismVec).Shape()
        newPart = BRepAlgoAPI_Cut(workPart, tool).Shape()
        uid = win.getNewPartUID(newPart, ancestor=wrkPrtUID)
        win.statusBar().showMessage('Mill operation complete')
        win.clearCallback()
        win.redraw()
    else:
        win.registerCallback(millC)
        win.lineEdit.setFocus()
        statusText = "Enter milling depth for tool (Neg value for -W)"
        win.statusBar().showMessage(statusText)
Exemple #16
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        """ display one or a set of displayable objects
        """
        ais_shapes = []  # the list of all displayed shapes

        if issubclass(shapes.__class__, gp_Pnt):
            # if a gp_Pnt is passed, first convert to vertex
            vertex = BRepBuilderAPI_MakeVertex(shapes)
            shapes = [vertex.Shape()]
        elif isinstance(shapes, gp_Pnt2d):
            vertex = BRepBuilderAPI_MakeVertex(
                gp_Pnt(shapes.X(), shapes.Y(), 0))
            shapes = [vertex.Shape()]
        elif isinstance(shapes, Geom_Surface):
            bounds = True
            toldegen = 1e-6
            face = BRepBuilderAPI_MakeFace()
            face.Init(shapes, bounds, toldegen)
            face.Build()
            shapes = [face.Shape()]
        elif isinstance(shapes, Geom_Curve):
            edge = BRepBuilderAPI_MakeEdge(shapes)
            shapes = [edge.Shape()]
        elif isinstance(shapes, Geom2d_Curve):
            edge2d = BRepBuilderAPI_MakeEdge2d(shapes)
            shapes = [edge2d.Shape()]
        # if only one shapes, create a list with a single shape
        if not isinstance(shapes, list):
            shapes = [shapes]
        # build AIS_Shapes list
        for shape in shapes:
            if material or texture:
                if texture:
                    shape_to_display = AIS_TexturedShape(shape)
                    filename, toScaleU, toScaleV, toRepeatU, toRepeatV, originU, originV = texture.GetProperties(
                    )
                    shape_to_display.SetTextureFileName(
                        TCollection_AsciiString(filename))
                    shape_to_display.SetTextureMapOn()
                    shape_to_display.SetTextureScale(True, toScaleU, toScaleV)
                    shape_to_display.SetTextureRepeat(True, toRepeatU,
                                                      toRepeatV)
                    shape_to_display.SetTextureOrigin(True, originU, originV)
                    shape_to_display.SetDisplayMode(3)
                elif material:
                    shape_to_display = AIS_Shape(shape)
                    shape_to_display.SetMaterial(
                        Graphic3d_MaterialAspect(material))
            else:
                # TODO: can we use .Set to attach all TopoDS_Shapes
                # to this AIS_Shape instance?
                shape_to_display = AIS_Shape(shape)

            ais_shapes.append(shape_to_display)

        # if not SOLO:
        #     # computing graphic properties is expensive
        #     # if an iterable is found, so cluster all TopoDS_Shape under
        #     # an AIS_MultipleConnectedInteractive
        #     #shape_to_display = AIS_MultipleConnectedInteractive()
        #     for ais_shp in ais_shapes:
        #         # TODO : following line crashes with oce-0.18
        #         # why ? fix ?
        #         #shape_to_display.Connect(i)
        #         self.Context.Display(ais_shp, False)
        # set the graphic properties
        if material is None:
            #The default material is too shiny to show the object
            #color well, so I set it to something less reflective
            for shape_to_display in ais_shapes:
                shape_to_display.SetMaterial(
                    Graphic3d_MaterialAspect(Graphic3d_NOM_NEON_GNC))
        if color:
            if isinstance(color, str):
                color = get_color_from_name(color)
            elif isinstance(color, int):
                color = Quantity_Color(color)
            for shp in ais_shapes:
                self.Context.SetColor(shp, color, False)
        if transparency:
            for shape_to_display in ais_shapes:
                shape_to_display.SetTransparency(transparency)
        # display the shapes
        for shape_to_display in ais_shapes:
            self.Context.Display(shape_to_display, False)
        if update:
            # especially this call takes up a lot of time...
            self.FitAll()
            self.Repaint()

        return ais_shapes
Exemple #17
0
def make_face(shape):
    tol_degen = 1e-6
    face = BRepBuilderAPI_MakeFace(shape, tol_degen)
    face.Build()
    return face.Shape()
Exemple #18
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()
Exemple #19
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        """ display one or a set of displayable objects
        """
        SOLO = False  # assume multiple instances by default
        # if a gp_Pnt is passed, first convert to vertex
        if issubclass(shapes.__class__, gp_Pnt):
            vertex = BRepBuilderAPI_MakeVertex(shapes)
            shapes = [vertex.Shape()]
            SOLO = True
        elif isinstance(shapes, gp_Pnt2d):
            vertex = BRepBuilderAPI_MakeVertex(
                gp_Pnt(shapes.X(), shapes.Y(), 0))
            shapes = [vertex.Shape()]
            SOLO = True
        # if a Geom_Curve is passed
        elif callable(getattr(shapes, "GetHandle", None)):
            handle = shapes.GetHandle()
            if issubclass(handle.__class__, Handle_Geom_Curve):
                edge = BRepBuilderAPI_MakeEdge(handle)
                shapes = [edge.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom2d_Curve):
                edge2d = BRepBuilderAPI_MakeEdge2d(handle)
                shapes = [edge2d.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom_Surface):
                bounds = True
                toldegen = 1e-6
                face = BRepBuilderAPI_MakeFace()
                face.Init(handle, bounds, toldegen)
                face.Build()
                shapes = [face.Shape()]
                SOLO = True
        elif isinstance(shapes, Handle_Geom_Surface):
            bounds = True
            toldegen = 1e-6
            face = BRepBuilderAPI_MakeFace()
            face.Init(shapes, bounds, toldegen)
            face.Build()
            shapes = [face.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom_Curve):
            edge = BRepBuilderAPI_MakeEdge(shapes)
            shapes = [edge.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom2d_Curve):
            edge2d = BRepBuilderAPI_MakeEdge2d(shapes)
            shapes = [edge2d.Shape()]
            SOLO = True
        elif issubclass(shapes.__class__, TopoDS_Shape):
            shapes = [shapes]
            SOLO = True

        ais_shapes = []

        for shape in shapes:
            if material or texture:
                if texture:
                    self.View.SetSurfaceDetail(V3d_TEX_ALL)
                    shape_to_display = AIS_TexturedShape(shape)
                    filename, toScaleU, toScaleV, toRepeatU, toRepeatV, originU, originV = texture.GetProperties(
                    )
                    shape_to_display.SetTextureFileName(
                        TCollection_AsciiString(filename))
                    shape_to_display.SetTextureMapOn()
                    shape_to_display.SetTextureScale(True, toScaleU, toScaleV)
                    shape_to_display.SetTextureRepeat(True, toRepeatU,
                                                      toRepeatV)
                    shape_to_display.SetTextureOrigin(True, originU, originV)
                    shape_to_display.SetDisplayMode(3)
                elif material:
                    shape_to_display = AIS_Shape(shape)
                    shape_to_display.SetMaterial(material)
            else:
                # TODO: can we use .Set to attach all TopoDS_Shapes
                # to this AIS_Shape instance?
                shape_to_display = AIS_Shape(shape)

            ais_shapes.append(shape_to_display.GetHandle())

        if not SOLO:
            # computing graphic properties is expensive
            # if an iterable is found, so cluster all TopoDS_Shape under
            # an AIS_MultipleConnectedInteractive
            #shape_to_display = AIS_MultipleConnectedInteractive()
            for ais_shp in ais_shapes:
                # TODO : following line crashes with oce-0.18
                # why ? fix ?
                #shape_to_display.Connect(i)
                self.Context.Display(ais_shp, False)
            shape_to_display = ais_shapes
            return shape_to_display
        # set the graphic properties
        if material is None:
            #The default material is too shiny to show the object
            #color well, so I set it to something less reflective
            shape_to_display.SetMaterial(Graphic3d_NOM_NEON_GNC)
        if color:
            if isinstance(color, str):
                color = get_color_from_name(color)
            for shp in ais_shapes:
                self.Context.SetColor(shp, color, False)
        if transparency:
            shape_to_display.SetTransparency(transparency)
        if update:
            # only update when explicitely told to do so
            self.Context.Display(shape_to_display.GetHandle(), False)
            # especially this call takes up a lot of time...
            self.FitAll()
            self.Repaint()
        else:
            self.Context.Display(shape_to_display.GetHandle(), False)

        if SOLO:
            return ais_shapes[0]
        else:
            return shape_to_display