예제 #1
0
    def makeSection2(self, cuttingPlane, shapeToSection, zLevel):
        """
            Uses BrepSection Algo. this generally returns a list of wires, not a face      
        """
        # section is certainly faster, but produces only edges.
        # those have to be re-organized into wires, probably
        # using ShapeAnalysis_WireOrder

        face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(cuttingPlane).Shape()
        # Computes Shape/Plane intersection
        section = BRepAlgoAPI.BRepAlgoAPI_Section(self.solid.shape, face)
        # section = BRepAlgo.BRepAlgo_Section(self.solid.shape,face);
        section.Build()
        if section.IsDone():
            # Topology.dumpTopology(section.Shape());

            # what we got back was a compound of edges
            t = Topo(section.Shape())
            wb = OCCUtil.MultiWireBuilder()
            for e in t.edges():
                wb.addEdge(e)
            wires = wb.getWires()
            print wires
            for w in wires:
                Topology.dumpTopology(w)
            return wires
        else:
            raise Exception("Could not compute Section!")
예제 #2
0
def makeOffsets(wire,d=True):

    numOffsets = 0;

    if d: display.DisplayColoredShape(startWire,'YELLOW');
    STEP = 0.5;
    for offset in Util.frange6(0.5,4.0,STEP):
        #print "offsetting by %0.3f" % offset
        o = OCCUtil.offsetWire(startWire,offset*(-1.0));
        numOffsets+=1;
        if d: display.DisplayColoredShape(o, 'RED');
        
        o2 = OCCUtil.offsetWire(startWire,offset*(-1.0) + (STEP/2.0) );
        numOffsets+=1;
        #create a naive centerline  by setting in( which could conflict with others )
        #if d: display.DisplayColoredShape(o2,'GREEN');
        
        #now offset back out to create centerline. if the result is a compound, then we must offset each member wire
        if o.ShapeType() == TopAbs.TopAbs_COMPOUND:
            t = Topo(o);
            for w in t.wires():
                w2 = OCCUtil.offsetWire(w,STEP*(0.5));
                numOffsets+=1;
                if d: display.DisplayColoredShape(w2, 'BLUE');
        else: #wire
            o2 = OCCUtil.offsetWire(OCCUtil.cast(o),STEP*(0.5));
            numOffsets+=1;
            if d: display.DisplayColoredShape(o2, 'WHITE');

    return numOffsets;
예제 #3
0
 def on_change_selection(self):
     new_id = self.edge_id
     input = self.input
     label = self.label
     
     if not all((input, label)): return
     
     input_shape = input.shape
     
     sel_label = self.label.FindChild(4)
     selector = TNaming.TNaming_Selector(sel_label)
     
     self.selector = selector
     
     topo = Topo(input_shape)
     self._n_edges = topo.number_of_edges()
     for i,edge in enumerate(topo.edges()):
         if i==new_id:
             selector.Select(edge, input_shape)
             print "got selection!"
             break
     else:
         print "no selection"
         
     self.modified = False
     self.modified = True
예제 #4
0
    def test_brepfeat_prism(self):
        print 'Test: brepfeat prism'
        box = BRepPrimAPI_MakeBox(400, 250, 300).Shape()
        faces = Topo(box).faces()

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

        srf = BRep_Tool_Surface(face)

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

        circle = Geom2d_Circle(c).GetHandle()

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

        mkf = BRepBuilderAPI_MakeFace()
        mkf.Init(srf, False)
        mkf.Add(wire.Wire())
        mkf.Build()
        self.assertTrue(mkf.IsDone())
        prism = BRepFeat_MakeDPrism(
            box,
            mkf.Face(),
            face,
            #gp_Dir(10,0,0),
            100,
            True,
            True)

        prism.Perform(400)
        self.assertTrue(prism.IsDone())
def offset_cube(event=None):
    # smoothed
#    S1 = BRepPrimAPI_MakeBox(150,200,110).Shape()    
#    offsetA = BRepOffsetAPI_MakeOffsetShape(S1,60,0.01)    
#    display.EraseAll()
#    display.Context
#    display.DisplayColoredShape(S1, 'BLUE')
#    offA = display.DisplayColoredShape(offsetA.Shape(), 'GREEN')
#    display.Context.SetTransparency( offA, 0.3 )

    # sharp
    S2 = BRepPrimAPI_MakeBox(gp_Pnt(300,0,0),220,140,180).Shape()    
    offsetB = BRepOffsetAPI_MakeOffsetShape(S2,-20,0.01,BRepOffset_Skin,False,False,GeomAbs_Arc)    
    offB = display.DisplayColoredShape(S2, 'BLUE')
    display.Context.SetTransparency( offB, 0.3 )
    display.DisplayColoredShape(offsetB.Shape(), 'GREEN')
    
    from OCC.TCollection import TCollection_ExtendedString
    topo = Topo(S2)
    faces = topo.faces()
#    faceA, faceB = topo.faces_from_edge(topo.edges().next())
    faceA = faces.next()
    faces.next();faces.next(); faces.next()
    faceB = faces.next()
    
    dim = AIS_LengthDimension(faceA, faceB, 120, TCollection_ExtendedString('jelle'))
    dim.SetValue(30)
    display.Context.Display(dim.GetHandle())
    
    display.FitAll()
예제 #6
0
def testOffsetReferences():

    #f = TestObjects.makeHeartFace();
    #f must be a face with one outer and one inner wire
    f = TestObjects.makeSquareWithRoundHole()

    wires = OCCUtil.wireListFromFace(f)
    outer = wires[0]
    inner = wires[1]
    display.DisplayColoredShape(outer, 'GREEN')
    display.DisplayColoredShape(inner, 'WHITE')

    #add wires to offset.
    bo = BRepOffsetAPI.BRepOffsetAPI_MakeOffset()
    bo.AddWire(outer)
    bo.AddWire(inner)

    bo.Perform(-0.2, 0.0)
    #do an offset

    shape = bo.Shape()
    for w in Topo(shape).wires():
        display.DisplayColoredShape(OCCUtil.cast(shape), 'YELLOW')

    for e in Topo(outer).edges():
        print "Outer Edge %d has %d generated shapes" % (
            e.__hash__(),
            len(OCCUtil.listFromTopToolsListOfShape(bo.Generated(e))))

    for e in Topo(inner).edges():
        print "Inner Edge %d has %d generated shapes" % (
            e.__hash__(),
            len(OCCUtil.listFromTopToolsListOfShape(bo.Generated(e))))

    display.FitAll()
    def test_brepfeat_prism(self):
        print 'Test: brepfeat prism'
        box = BRepPrimAPI_MakeBox(400, 250, 300).Shape()
        faces = Topo(box).faces()

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

        c = gp_Circ2d(gp_Ax2d(gp_Pnt2d(200, 130),
                              gp_Dir2d(1, 0)), 75)
        circle = Geom2d_Circle(c).GetHandle()
        wire = BRepBuilderAPI_MakeWire()
        wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, 0., pi).Edge())
        wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, pi, 2.*pi).Edge())
        wire.Build()

        mkf = BRepBuilderAPI_MakeFace()
        mkf.Init(srf, False, TolDegen)
        mkf.Add(wire.Wire())
        mkf.Build()
        self.assertTrue(mkf.IsDone())
        prism = BRepFeat_MakeDPrism(box, mkf.Face(), face, 100, True, True)
        prism.Perform(400)
        self.assertTrue(prism.IsDone())
예제 #8
0
def makeOffsets(wire, d=True):

    numOffsets = 0

    if d: display.DisplayColoredShape(startWire, 'YELLOW')
    STEP = 0.5
    for offset in Util.frange6(0.5, 4.0, STEP):
        #print "offsetting by %0.3f" % offset
        o = OCCUtil.offsetWire(startWire, offset * (-1.0))
        numOffsets += 1
        if d: display.DisplayColoredShape(o, 'RED')

        o2 = OCCUtil.offsetWire(startWire,
                                offset * (-1.0) + (STEP / 2.0))
        numOffsets += 1
        #create a naive centerline  by setting in( which could conflict with others )
        #if d: display.DisplayColoredShape(o2,'GREEN');

        #now offset back out to create centerline. if the result is a compound, then we must offset each member wire
        if o.ShapeType() == TopAbs.TopAbs_COMPOUND:
            t = Topo(o)
            for w in t.wires():
                w2 = OCCUtil.offsetWire(w, STEP * (0.5))
                numOffsets += 1
                if d: display.DisplayColoredShape(w2, 'BLUE')
        else:  #wire
            o2 = OCCUtil.offsetWire(OCCUtil.cast(o), STEP * (0.5))
            numOffsets += 1
            if d: display.DisplayColoredShape(o2, 'WHITE')

    return numOffsets
예제 #9
0
 def on_change_selection(self):
     new_id = self.edge_id
     input = self.input
     label = self.label
     
     if not all((input, label)): return
     
     input_shape = input.shape
     
     sel_label = self.label.FindChild(4)
     selector = TNaming.TNaming_Selector(sel_label)
     
     self.selector = selector
     
     topo = Topo(input_shape)
     self._n_edges = topo.number_of_edges()
     for i,edge in enumerate(topo.edges()):
         if i==new_id:
             selector.Select(edge, input_shape)
             print "got selection!"
             break
     else:
         print "no selection"
         
     self.modified = False
     self.modified = True
예제 #10
0
    def makeSection2(self, cuttingPlane, shapeToSection, zLevel):
        """
            Uses BrepSection Algo. this generally returns a list of wires, not a face      
        """
        #section is certainly faster, but produces only edges.
        #those have to be re-organized into wires, probably
        #using ShapeAnalysis_WireOrder

        face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(cuttingPlane).Shape()
        # Computes Shape/Plane intersection
        section = BRepAlgoAPI.BRepAlgoAPI_Section(self.solid.shape, face)
        #section = BRepAlgo.BRepAlgo_Section(self.solid.shape,face);
        section.Build()
        if section.IsDone():
            #Topology.dumpTopology(section.Shape());

            #what we got back was a compound of edges
            t = Topo(section.Shape())
            wb = OCCUtil.MultiWireBuilder()
            for e in t.edges():
                wb.addEdge(e)
            wires = wb.getWires()
            print wires
            for w in wires:
                Topology.dumpTopology(w)
            return wires
        else:
            raise Exception("Could not compute Section!")
예제 #11
0
def build_curve_network(event=None):
    '''
    mimic the curve network surfacing command from rhino
    '''
    print 'Importing IGES file...',
    pth = os.path.dirname(os.path.abspath(__file__))
    pth = os.path.abspath(
        os.path.join(pth, '../data/IGES/curve_geom_plate.igs'))
    import ipdb
    ipdb.set_trace()
    iges = IGESImporter(pth)
    iges.read_file()
    print 'done.'
    # GetShapes returns 36 TopoDS_Shape, while the TopoDS_Compound contains
    # just the 6 curves I made in rhino... hmmm...
    print 'Building geomplate...',
    topo = Topo(iges.get_compound())
    edges_list = list(topo.edges())
    face = build_geom_plate(edges_list)
    print 'done.'

    print 'Cutting out of edges...',
    # Make a wire from outer edges
    _edges = [edges_list[2], edges_list[3], edges_list[4], edges_list[5]]
    outer_wire = make_wire(_edges)
예제 #12
0
    def update_naming(self, make_shape):
        label = self.label
        shape = make_shape.Shape()

        input_shape = make_shape.Shape1()
        tool_shape = make_shape.Shape2()

        builder = TNaming.TNaming_Builder(label)
        builder.Generated(input_shape, shape)
        builder.Generated(tool_shape, shape)

        gen_label = label.FindChild(1)
        mod_label = label.FindChild(2)
        del_label = label.FindChild(3)

        gen_builder = TNaming.TNaming_Builder(gen_label)
        mod_builder = TNaming.TNaming_Builder(mod_label)
        del_builder = TNaming.TNaming_Builder(del_label)

        if make_shape.HasGenerated():
            for in_shape in [input_shape, tool_shape]:
                for face in Topo(in_shape).faces():
                    gen_shapes = make_shape.Generated(face)
                    itr = TopTools.TopTools_ListIteratorOfListOfShape(
                        gen_shapes)
                    while itr.More():
                        this = itr.Value()
                        gen_builder.Generated(face, this)
                        print "generated", face, this
                        itr.Next()

        if make_shape.HasModified():
            for face in Topo(input_shape).faces():
                mod_shapes = make_shape.Modified(face)
                itr = TopTools.TopTools_ListIteratorOfListOfShape(mod_shapes)
                while itr.More():
                    this = itr.Value()
                    mod_builder.Modify(face, this)
                    print "modified", face, this
                    itr.Next()

            for face in Topo(tool_shape).faces():
                mod_shapes = make_shape.Modified2(face)
                itr = TopTools.TopTools_ListIteratorOfListOfShape(mod_shapes)
                while itr.More():
                    this = itr.Value()
                    mod_builder.Modify(face, this)
                    print "modified2", face, this
                    itr.Next()

        if make_shape.HasDeleted():
            for face in Topo(input_shape).faces():
                if make_shape.IsDeleted(face):
                    del_builder.Delete(face)
            for face in Topo(tool_shape).faces():
                if make_shape.IsDeleted(face):
                    del_builder.Delete(face)
 def test_thick_solid(self):
     print 'Test: thick solid'
     S = BRepPrimAPI_MakeBox(150, 200, 110).Shape()
     topo = Topo(S)
     vert = topo.vertices().next()
     shapes = TopTools_ListOfShape()
     for f in topo.faces_from_vertex(vert):
         shapes.Append(f)
     _thick_solid = BRepOffsetAPI_MakeThickSolid(S, shapes, 15, 0.01)
     self.assertTrue(_thick_solid.IsDone())
예제 #14
0
    def test_thick_solid(self):
        print 'Test: thick solid'
        S = BRepPrimAPI_MakeBox(150, 200, 110).Shape()

        topo = Topo(S)
        vert = topo.vertices().next()

        shapes = TopTools_ListOfShape()
        for f in topo.faces_from_vertex(vert):
            shapes.Append(f)

        _thick_solid = BRepOffsetAPI_MakeThickSolid(S, shapes, 15, 0.01)
        self.assertTrue(_thick_solid.IsDone())
def thick_solid(event=None):
    S = BRepPrimAPI_MakeBox(150,200,110).Shape()
    
    topo = Topo(S)
    vert = topo.vertices().next()
    
    shapes = TopTools_ListOfShape()
    for f in topo.faces_from_vertex(vert):
        shapes.Append(f)
    
    _thick_solid = BRepOffsetAPI_MakeThickSolid(S,shapes, 15,0.01)
    display.EraseAll()
    display.DisplayShape(_thick_solid.Shape())
예제 #16
0
def nearestVertices(wireList,point,tolerance=9999999.0):

    points = [];
    for w in wireList:
        tw = Topo(w);
        for v in tw.vertices():                    
            p = brepTool.Pnt(v);
            d = point.Distance(p)
            if d < tolerance:
                points.append((w,v,p,d));                        
   
    #sort       
    return sorted(points,key=lambda v: v[3])
예제 #17
0
def nearestVertices(wireList, point, tolerance=9999999.0):

    points = []
    for w in wireList:
        tw = Topo(w)
        for v in tw.vertices():
            p = brepTool.Pnt(v)
            d = point.Distance(p)
            if d < tolerance:
                points.append((w, v, p, d))

    #sort
    return sorted(points, key=lambda v: v[3])
예제 #18
0
class LoopWirePairs(object):
    '''
    for looping through consequtive wires
    assures that the returned edge pairs are ordered
    '''
    def __init__(self, wireA, wireB):
        self.wireA = wireA
        self.wireB = wireB
        self.we_A  = WireExplorer(self.wireA)
        self.we_B  = WireExplorer(self.wireB)
        self.tp_A  = Topo(self.wireA)
        self.tp_B  = Topo(self.wireB)
        
        self.bt = BRep_Tool
        self.vertsA = [v for v in self.we_A.ordered_vertices()]
        self.vertsB = [v for v in self.we_B.ordered_vertices()]
        
        self.edgesA = [v for v in WireExplorer(wireA).ordered_edges()]
        self.edgesB = [v for v in WireExplorer(wireB).ordered_edges()]
        
        self.pntsB  = [self.bt.Pnt(v) for v in self.vertsB]
        self.number_of_vertices = len(self.vertsA)
        self.index = 0
        
    def closest_point(self, vertexFromWireA):
        pt = self.bt.Pnt(vertexFromWireA)
        distances = [pt.Distance(i) for i in self.pntsB]
        indx_max_dist = distances.index(min(distances))
        return self.vertsB[indx_max_dist]
        
    def next(self):
        if self.index == self.number_of_vertices:
            raise StopIteration
        
        vert = self.vertsA[self.index]
        closest = self.closest_point(vert)
        edges_a = self.tp_A.edges_from_vertex(vert)
        edges_b = self.tp_B.edges_from_vertex(closest)
        a1, a2 = Edge(edges_a.next()),Edge(edges_a.next())
        b1, b2 = Edge(edges_b.next()),Edge(edges_b.next())
        mpA = a1.mid_point()
        self.index +=1
        
        if mpA.Distance(b1.mid_point()) < mpA.Distance(b2.mid_point()):
            return iter([a1, a2]), iter([b1,b2])
        else:
            return iter([a1, a2]), iter([b2,b1])
         
    
    def __iter__(self):
        return self
def glue_solids(event=None):
    # Without common edges 
    S1 = BRepPrimAPI_MakeBox(gp_Pnt(500.,500.,0.),gp_Pnt(100.,250.,300.)).Shape()
    facesA = Topo(S1).faces()
    F1 = [facesA.next() for i in range(5)][-1]
    
    S2 = BRepPrimAPI_MakeBox(gp_Pnt(400.,400.,300.),gp_Pnt(200.,300.,500.)).Shape()
    facesB = Topo(S2).faces()
    F2 = [facesB.next() for i in range(4)][-1]
    
    glue1 = BRepFeat_Gluer(S2,S1)
    glue1.Bind(F2,F1)
    display.EraseAll()
    display.DisplayShape(glue1.Shape())
예제 #20
0
class LoopWirePairs(object):
    '''
    for looping through consequtive wires
    assures that the returned edge pairs are ordered
    '''
    def __init__(self, wireA, wireB):
        self.wireA = wireA
        self.wireB = wireB
        self.we_A = WireExplorer(self.wireA)
        self.we_B = WireExplorer(self.wireB)
        self.tp_A = Topo(self.wireA)
        self.tp_B = Topo(self.wireB)

        self.bt = BRep_Tool()
        self.vertsA = [v for v in self.we_A.ordered_vertices()]
        self.vertsB = [v for v in self.we_B.ordered_vertices()]

        self.edgesA = [v for v in WireExplorer(wireA).ordered_edges()]
        self.edgesB = [v for v in WireExplorer(wireB).ordered_edges()]

        self.pntsB = [self.bt.Pnt(v) for v in self.vertsB]
        self.number_of_vertices = len(self.vertsA)
        self.index = 0

    def closest_point(self, vertexFromWireA):
        pt = self.bt.Pnt(vertexFromWireA)
        distances = [pt.Distance(i) for i in self.pntsB]
        indx_max_dist = distances.index(min(distances))
        return self.vertsB[indx_max_dist]

    def next(self):
        if self.index == self.number_of_vertices:
            raise StopIteration

        vert = self.vertsA[self.index]
        closest = self.closest_point(vert)
        edges_a = self.tp_A.edges_from_vertex(vert)
        edges_b = self.tp_B.edges_from_vertex(closest)
        a1, a2 = Edge(edges_a.next()), Edge(edges_a.next())
        b1, b2 = Edge(edges_b.next()), Edge(edges_b.next())
        mpA = a1.mid_point()
        self.index += 1

        if mpA.Distance(b1.mid_point()) < mpA.Distance(b2.mid_point()):
            return iter([a1, a2]), iter([b1, b2])
        else:
            return iter([a1, a2]), iter([b2, b1])

    def __iter__(self):
        return self
예제 #21
0
def display(topo):
    #http://www.opencascade.org/org/forum/thread_18374/
    #http://adl.serveftp.org/lab/opencascade/pdf/visu.pdf
    #shape = displays[curr_tab].DisplayShape(topo, update=False).GetObject()
    #shape.SetDisplayMode(0)
    #displays[curr_tab].DisplayColoredShape(topo, 'BLUE', False)
    mat = Graphic3d_MaterialAspect(Graphic3d_NOM_SILVER)
    displays[curr_tab].DisplayShape(topo, material=mat, update=False)

    t = Topo(topo)
    wires = t.wires()
    for w in wires:
        #print w
        #displays[curr_tab].DisplayColoredShape(w, 'BLACK', False)
        edges.append(w)
 def test_draft_angle(self):
     print 'Test: draft angle'
     S = BRepPrimAPI_MakeBox(200.,300.,150.).Shape()
     adraft = BRepOffsetAPI_DraftAngle(S)
     
     topo = Topo(S)
     for f in topo.faces():
         surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(f)).GetObject()
         dirf = surf.Pln().Axis().Direction()
         print 'direction',dirf.Coord()
         ddd = gp_Dir(0,0,1)
         if dirf.IsNormal(ddd, Precision_Angular()):
             adraft.Add(f, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))         
     adraft.Build()
     self.assertTrue(adraft.IsDone())
예제 #23
0
파일: nspace.py 프로젝트: julienbld/pycado
def display(topo):
    # http://www.opencascade.org/org/forum/thread_18374/
    # http://adl.serveftp.org/lab/opencascade/pdf/visu.pdf
    # shape = displays[curr_tab].DisplayShape(topo, update=False).GetObject()
    # shape.SetDisplayMode(0)
    # displays[curr_tab].DisplayColoredShape(topo, 'BLUE', False)
    mat = Graphic3d_MaterialAspect(Graphic3d_NOM_SILVER)
    displays[curr_tab].DisplayShape(topo, material=mat, update=False)

    t = Topo(topo)
    wires = t.wires()
    for w in wires:
        # print w
        # displays[curr_tab].DisplayColoredShape(w, 'BLACK', False)
        edges.append(w)
 def test_glue_solids(self):
     print 'Test: glue solids'
     # Without common edges
     S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.),
                              gp_Pnt(100., 250., 300.)).Shape()
     facesA = Topo(S1).faces()
     F1 = [facesA.next() for i in range(5)][-1]
     S2 = BRepPrimAPI_MakeBox(gp_Pnt(400., 400., 300.),
                              gp_Pnt(200., 300., 500.)).Shape()
     facesB = Topo(S2).faces()
     F2 = [facesB.next() for i in range(4)][-1]
     glue1 = BRepFeat_Gluer(S2, S1)
     glue1.Bind(F2, F1)
     glue1.Build()
     self.assertTrue(glue1.IsDone())
 def test_draft_angle(self):
     print 'Test: draft angle'
     S = BRepPrimAPI_MakeBox(200.,300.,150.).Shape()
     adraft = BRepOffsetAPI_DraftAngle(S)
     
     topo = Topo(S)
     for f in topo.faces():
         surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(f)).GetObject()
         dirf = surf.Pln().Axis().Direction()
         print 'direction',dirf.Coord()
         ddd = gp_Dir(0,0,1)
         if dirf.IsNormal(ddd, Precision_Angular()):
             adraft.Add(f, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))         
     adraft.Build()
     self.assertTrue(adraft.IsDone())
예제 #26
0
    def read_file(self):
        h_doc = TDocStd.Handle_TDocStd_Document()
        # print "Empty Doc?", h_doc.IsNull()

        # Create the application
        app = XCAFApp.GetApplication().GetObject()
        app.NewDocument(TCollection.TCollection_ExtendedString("MDTV-CAF"), h_doc)

        # Get root assembly
        doc = h_doc.GetObject()
        h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_shapetool(doc.Main())
        l_Colors = XCAFDoc.XCAFDoc_DocumentTool_colortool(doc.Main())
        l_Layers = XCAFDoc.XCAFDoc_DocumentTool_layertool(doc.Main())
        l_materials = XCAFDoc.XCAFDoc_DocumentTool_materialtool(doc.Main())

        STEPReader = STEPCAFControl_Reader()
        STEPReader.SetColorMode(True)
        STEPReader.SetLayerMode(True)
        STEPReader.SetNameMode(True)
        STEPReader.SetMatMode(True)

        status = STEPReader.ReadFile(str(self.filename))
        if status == IFSelect_RetDone:
            STEPReader.Transfer(doc.GetHandle())
        Labels = TDF_LabelSequence()
        ColorLabels = TDF_LabelSequence()
        # TopoDS_Shape aShape;
        shape_tool = h_shape_tool.GetObject()
        h_shape_tool.GetObject().GetFreeShapes(Labels)
        print "Number of shapes at root :%i" % Labels.Length()
        for i in range(Labels.Length()):
            sub_shapes_labels = TDF_LabelSequence()
            print "Is Assembly?", shape_tool.isassembly(Labels.Value(i + 1))
            sub_shapes = shape_tool.getsubshapes(Labels.Value(i + 1), sub_shapes_labels)
            print "Number of subshapes in the assemly :%i" % sub_shapes_labels.Length()
        l_Colors.GetObject().GetColors(ColorLabels)
        print "Number of colors=%i" % ColorLabels.Length()
        # if(CL_Len>0):
        #       ColorTool->GetColor(ColorLabels.Value(1),DefaultColor);
        for i in range(Labels.Length()):
            print Labels.Value(i + 1)
            aShape = h_shape_tool.GetObject().getshape(Labels.Value(i + 1))
            m = l_Layers.GetObject().GetLayers(aShape)
            if aShape.ShapeType() == TopAbs_COMPOUND:
                t = Topo(aShape)
                for t in t.solids():
                    self._shapes.append(t)
        return True
def brepfeat_prism(event=None):
    box = BRepPrimAPI_MakeBox(400,250,300).Shape()
    faces = Topo(box).faces()
    
    for i in range(5):
        face = faces.next()
    
    srf = BRep_Tool_Surface(face)
    
    c = gp_Circ2d(gp_Ax2d(gp_Pnt2d(200,130),
                          gp_Dir2d(1,0)),
                  75
                  )
    
    circle = Geom2d_Circle(c).GetHandle()
    
    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()
    
    # bit obscure why this is nessecary...
    # segfaults without...
    new_face = mkf.Face()
    BRepLib_BuildCurves3d(new_face)
    
    display.DisplayShape(new_face)
    
    prism = BRepFeat_MakeDPrism(box,
                                mkf.Face(),
                                 face,
                                 #gp_Dir(10,0,0),
                                 100,
                                  True,
                                   True
                               )
    
    prism.Perform(400)
    display.EraseAll()
    display.DisplayShape(prism.Shape())
    display.DisplayColoredShape(wire.Wire(), 'RED')
예제 #28
0
def draft_angle(event=None):
    S = BRepPrimAPI_MakeBox(200.,300.,150.).Shape()
    adraft = BRepOffsetAPI_DraftAngle(S)
    
    topo = Topo(S)
    for f in topo.faces():
        surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(f)).GetObject()
        dirf = surf.Pln().Axis().Direction()
        print 'direction',dirf.Coord()
        ddd = gp_Dir(0,0,1)
        if dirf.IsNormal(ddd, Precision_Angular()):
            adraft.Add(f, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))
            
    adraft.Build()
    display.EraseAll()
    display.DisplayShape(adraft.Shape())
예제 #29
0
def fit_plane_through_face_vertices(_face):
    """
    :param _face:   OCC.KBE.face.Face instance
    :return:        Geom_Plane
    """
    from OCC.GeomPlate import GeomPlate_BuildAveragePlane
    from OCC.Utils.Topology import Topo

    uvs_from_vertices = [
        _face.project_vertex(vertex2pnt(i)) for i in Topo(_face).vertices()
    ]
    normals = [
        gp_Vec(_face.DiffGeom.normal(*uv[0])) for uv in uvs_from_vertices
    ]
    points = [i[1] for i in uvs_from_vertices]

    NORMALS = TColgp_SequenceOfVec()
    [NORMALS.Append(i) for i in normals]
    POINTS = to_tcol_(points, TColgp_HArray1OfPnt)

    pl = GeomPlate_BuildAveragePlane(NORMALS, POINTS).Plane().GetObject()
    vec = gp_Vec(pl.Location(), _face.GlobalProperties.centre())
    pt = (pl.Location().as_vec() + vec).as_pnt()
    pl.SetLocation(pt)
    return pl
예제 #30
0
def geom_plate(event=None):
    p1,p2,p3,p4,p5 = gp_Pnt(0,0,0),gp_Pnt(0,100,0),gp_Pnt(0,100,100),gp_Pnt(0,0,100),gp_Pnt(50,50,50)
    poly = make_closed_polygon([p1,p2,p3,p4])
    edges = [i for i in Topo(poly).edges()]
    face = make_n_sided(edges, [p5])
    my_renderer = webgl_renderer.WebGlRenderer()
    my_renderer.DisplayShape(face)
def brep_feat_local_revolution(event=None):
    S = BRepPrimAPI_MakeBox(400.,250.,300.).Shape()
    faces = list(Topo(S).faces())
    F1 = faces[2]
    surf = BRep_Tool_Surface(F1)
    Pl = Handle_Geom_Plane_DownCast(surf)
    
    D = gp.gp_OX()
    
    MW1 = BRepBuilderAPI_MakeWire() 
    p1 = gp_Pnt2d(100.,100.)
    p2 = gp_Pnt2d(200.,100.)
    aline = GCE2d_MakeLine(p1,p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline,surf,0.,p1.Distance(p2)).Edge())
    
    p1 = gp_Pnt2d(200.,100.)
    p2 = gp_Pnt2d(150.,200.)
    aline = GCE2d_MakeLine(p1,p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline,surf,0.,p1.Distance(p2)).Edge())
    
    p1 = gp_Pnt2d(150.,200.)
    p2 = gp_Pnt2d(100.,100.)
    aline = GCE2d_MakeLine(p1,p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline,surf,0.,p1.Distance(p2)).Edge())
    
    MKF1 = BRepBuilderAPI_MakeFace() 
    MKF1.Init(surf,False,1e-6)
    MKF1.Add(MW1.Wire())
    FP = MKF1.Face()
    BRepLib_BuildCurves3d(FP)
    MKrev = BRepFeat_MakeRevol(S,FP,F1,D,1,True)
    F2 = faces[4]
    MKrev.Perform(F2)
    display.EraseAll()
    display.DisplayShape(MKrev.Shape())
예제 #32
0
 def test_edges_out_of_scope(self):
     face = self.topo.faces().next()
     _edges = []
     for edg in Topo(face).edges():
         _edges.append(edg)
     for edg in _edges:
         self.assert_(edg.IsNull() == False)
예제 #33
0
    def test_brep_feat_local_pipe(self):
        print 'Test: brep_feat local pipe'
        S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape()
        faces = Topo(S).faces()
        faces.next()
        F1 = faces.next()
        surf = BRep_Tool_Surface(F1)

        MW1 = BRepBuilderAPI_MakeWire()
        p1 = gp_Pnt2d(100., 100.)
        p2 = gp_Pnt2d(200., 100.)
        aline = GCE2d_MakeLine(p1, p2).Value()
        MW1.Add(
            BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)).Edge())

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

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

        MKF1 = BRepBuilderAPI_MakeFace()
        MKF1.Init(surf, False)
        MKF1.Add(MW1.Wire())

        FP = MKF1.Face()
        BRepLib_BuildCurves3d(FP)

        CurvePoles = TColgp_Array1OfPnt(1, 3)
        CurvePoles.SetValue(1, gp_Pnt(150., 0., 150.))
        CurvePoles.SetValue(2, gp_Pnt(200., -100., 150.))
        CurvePoles.SetValue(3, gp_Pnt(150., -200., 150.))

        curve = Geom_BezierCurve(CurvePoles)

        E = BRepBuilderAPI_MakeEdge(curve.GetHandle()).Edge()
        W = BRepBuilderAPI_MakeWire(E).Wire()
        MKPipe = BRepFeat_MakePipe(S, FP, F1, W, 1, True)

        MKPipe.Perform()
        self.assertTrue(MKPipe.IsDone())
예제 #34
0
    def __init__(self, wireA, wireB):
        self.wireA = wireA
        self.wireB = wireB
        self.we_A = WireExplorer(self.wireA)
        self.we_B = WireExplorer(self.wireB)
        self.tp_A = Topo(self.wireA)
        self.tp_B = Topo(self.wireB)
        self.bt = BRep_Tool()
        self.vertsA = [v for v in self.we_A.ordered_vertices()]
        self.vertsB = [v for v in self.we_B.ordered_vertices()]

        self.edgesA = [v for v in WireExplorer(wireA).ordered_edges()]
        self.edgesB = [v for v in WireExplorer(wireB).ordered_edges()]

        self.pntsB = [self.bt.Pnt(v) for v in self.vertsB]
        self.number_of_vertices = len(self.vertsA)
        self.index = 0
예제 #35
0
    def _makeSlice(self, shapeToSlice, zLevel):

        s = Slice()

        #used to determine if a slice is identical to others.
        s.hatchDir = self.hatchReversed
        s.fillWidth = self.options.filling.fillWidth

        #change if layers are variable thickness
        s.sliceHeight = self.options.layerHeight
        s.zLevel = zLevel

        #make a cutting plane
        p = gp.gp_Pnt(0, 0, zLevel)

        origin = gp.gp_Pnt(0, 0, zLevel - 1)
        csys = gp.gp_Ax3(p, gp.gp().DZ())
        cuttingPlane = gp.gp_Pln(csys)
        bff = BRepBuilderAPI.BRepBuilderAPI_MakeFace(cuttingPlane)
        face = bff.Face()

        #odd, a halfspace is faster than a box?
        hs = BRepPrimAPI.BRepPrimAPI_MakeHalfSpace(face, origin)
        hs.Build()
        halfspace = hs.Solid()

        #make the cut
        bc = BRepAlgoAPI.BRepAlgoAPI_Cut(shapeToSlice, halfspace)
        cutShape = bc.Shape()

        foundFace = False
        for face in Topo(cutShape).faces():
            if self._isAtZLevel(zLevel, face):
                foundFace = True
                log.debug("Face is at zlevel" + str(zLevel))
                s.addFace(face)
                #TestDisplay.display.showShape(face);

                log.debug("Face" + str(face))

        if self.options.useSliceFactoring:
            mySum = s.getCheckSum()
            #print 'Slice Created, Checksum is',mySum;
            for otherSlice in self.slices:
                #print "Slice Checksum=",otherSlice.getCheckSum();
                if mySum == otherSlice.getCheckSum():
                    log.info(
                        "This slice matches another one exactly. using that so we can save time."
                    )
                    return otherSlice.copyToZ(zLevel)

        if not foundFace:
            log.warn("No faces found after slicing at zLevel " + str(zLevel) +
                     " !. Skipping This layer completely")
            return None
        else:
            return s
예제 #36
0
    def analyse(self):
        """

        :return:
        """
        from OCC.ShapeAnalysis import ShapeAnalysis_Shell
        ss = ShapeAnalysis_Shell(self.topo)
        if ss.HasFreeEdges():
            bad_edges = [e for e in Topo(ss.BadEdges()).edges()]
예제 #37
0
def geom_plate(event=None):
    display.EraseAll()
    p1,p2,p3,p4,p5 = gp_Pnt(0,0,0),gp_Pnt(0,10,0),gp_Pnt(0,10,10),gp_Pnt(0,0,10),gp_Pnt(5,5,5)
    poly = make_closed_polygon([p1,p2,p3,p4])
    edges = [i for i in Topo(poly).edges()]
    face = make_n_sided(edges, [p5])
    display.DisplayShape(edges)
    display.DisplayShape(make_vertex(p5))
    display.DisplayShape(face, update=True)
예제 #38
0
    def __init__(self, wireA, wireB):
        self.wireA = wireA
        self.wireB = wireB
        self.we_A = WireExplorer(self.wireA)
        self.we_B = WireExplorer(self.wireB)
        self.tp_A = Topo(self.wireA)
        self.tp_B = Topo(self.wireB)

        self.bt = BRep_Tool()
        self.vertsA = [v for v in self.we_A.ordered_vertices()]
        self.vertsB = [v for v in self.we_B.ordered_vertices()]

        self.edgesA = [v for v in WireExplorer(wireA).ordered_edges()]
        self.edgesB = [v for v in WireExplorer(wireB).ordered_edges()]

        self.pntsB = [self.bt.Pnt(v) for v in self.vertsB]
        self.number_of_vertices = len(self.vertsA)
        self.index = 0
예제 #39
0
def brep_feat_local_pipe(event=None):
    S = BRepPrimAPI_MakeBox(400.0, 250.0, 300.0).Shape()
    faces = Topo(S).faces()
    faces.next()
    F1 = faces.next()
    surf = BRep_Tool_Surface(F1)

    MW1 = BRepBuilderAPI_MakeWire()
    p1 = gp_Pnt2d(100.0, 100.0)
    p2 = gp_Pnt2d(200.0, 100.0)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0.0, p1.Distance(p2)).Edge())

    p1 = gp_Pnt2d(200.0, 100.0)
    p2 = gp_Pnt2d(150.0, 200.0)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0.0, p1.Distance(p2)).Edge())

    p1 = gp_Pnt2d(150.0, 200.0)
    p2 = gp_Pnt2d(100.0, 100.0)
    aline = GCE2d_MakeLine(p1, p2).Value()
    MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0.0, p1.Distance(p2)).Edge())

    MKF1 = BRepBuilderAPI_MakeFace()
    MKF1.Init(surf, False)
    MKF1.Add(MW1.Wire())

    FP = MKF1.Face()
    BRepLib_BuildCurves3d(FP)

    CurvePoles = TColgp_Array1OfPnt(1, 3)
    CurvePoles.SetValue(1, gp_Pnt(150.0, 0.0, 150.0))
    CurvePoles.SetValue(2, gp_Pnt(200.0, -100.0, 150.0))
    CurvePoles.SetValue(3, gp_Pnt(150.0, -200.0, 150.0))

    curve = Geom_BezierCurve(CurvePoles)

    E = BRepBuilderAPI_MakeEdge(curve.GetHandle()).Edge()
    W = BRepBuilderAPI_MakeWire(E).Wire()
    MKPipe = BRepFeat_MakePipe(S, FP, F1, W, 1, True)

    MKPipe.Perform()
    display.EraseAll()
    display.DisplayShape(MKPipe.Shape())
    def test_brep_feat_local_pipe(self):
        print 'Test: brep_feat local pipe'
        S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape()
        faces = Topo(S).faces()
        faces.next()
        F1 = faces.next()
        surf = BRep_Tool_Surface(F1)

        MW1 = BRepBuilderAPI_MakeWire()
        p1 = gp_Pnt2d(100., 100.)
        p2 = gp_Pnt2d(200., 100.)
        aline = GCE2d_MakeLine(p1, p2).Value()
        MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)).Edge())

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

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

        MKF1 = BRepBuilderAPI_MakeFace()
        MKF1.Init(surf, False, TolDegen)
        MKF1.Add(MW1.Wire())

        FP = MKF1.Face()
        BRepLib_BuildCurves3d(FP)

        CurvePoles = TColgp_Array1OfPnt(1, 3)
        CurvePoles.SetValue(1, gp_Pnt(150., 0., 150.))
        CurvePoles.SetValue(2, gp_Pnt(200., -100., 150.))
        CurvePoles.SetValue(3, gp_Pnt(150., -200., 150.))

        curve = Geom_BezierCurve(CurvePoles)

        E = BRepBuilderAPI_MakeEdge(curve.GetHandle()).Edge()
        W = BRepBuilderAPI_MakeWire(E).Wire()
        MKPipe = BRepFeat_MakePipe(S, FP, F1, W, 1, True)

        MKPipe.Perform()
        self.assertTrue(MKPipe.IsDone())
예제 #41
0
def wireListFromFace(face):
    rW = []
    ow = brt.OuterWire(face)
    rW.append(ow)

    for w in Topo(face).wires():
        if not w.IsSame(ow):
            rW.append(w)

    return rW
예제 #42
0
 def update_naming(self, make_shape):
     label = self.label
     shape = make_shape.Shape()
     
     input_shape = make_shape.Shape()
     
     builder = TNaming.TNaming_Builder(label)
     builder.Generated(input_shape, shape)
     
     #FindChild creates a new label, if one doesn't exist.
     #Label entry numbers are not necessarily incremental.
     #They are more like dictionary keys.
     gen_label = label.FindChild(1)
     mod_label = label.FindChild(2)
     del_label = label.FindChild(3)
     
     gen_builder = TNaming.TNaming_Builder(gen_label)
     mod_builder = TNaming.TNaming_Builder(mod_label)
     del_builder = TNaming.TNaming_Builder(del_label)
     
     topo = Topo(input_shape)
     
     for face in topo.faces():
         gen_shapes = make_shape.Generated(face)
         itr = TopTools.TopTools_ListIteratorOfListOfShape(gen_shapes)
         while itr.More():
             this = itr.Value()
             gen_builder.Generated(face, this)
             print "generated", face, this
             itr.Next()
                     
     for face in topo.faces():
         mod_shapes = make_shape.Modified(face)
         itr = TopTools.TopTools_ListIteratorOfListOfShape(mod_shapes)
         while itr.More():
             this = itr.Value()
             mod_builder.Modified(face, this)
             print "modified", face, this
             itr.Next()
                     
     for face in topo.faces():
         if make_shape.IsDeleted(face):
             del_builder.Delete(face)
예제 #43
0
 def update_naming(self, make_shape):
     label = self.label
     shape = make_shape.Shape()
     
     input_shape = make_shape.Shape()
     
     builder = TNaming.TNaming_Builder(label)
     builder.Generated(input_shape, shape)
     
     #FindChild creates a new label, if one doesn't exist.
     #Label entry numbers are not necessarily incremental.
     #They are more like dictionary keys.
     gen_label = label.FindChild(1)
     mod_label = label.FindChild(2)
     del_label = label.FindChild(3)
     
     gen_builder = TNaming.TNaming_Builder(gen_label)
     mod_builder = TNaming.TNaming_Builder(mod_label)
     del_builder = TNaming.TNaming_Builder(del_label)
     
     topo = Topo(input_shape)
     
     for face in topo.faces():
         gen_shapes = make_shape.Generated(face)
         itr = TopTools.TopTools_ListIteratorOfListOfShape(gen_shapes)
         while itr.More():
             this = itr.Value()
             gen_builder.Generated(face, this)
             print "generated", face, this
             itr.Next()
                     
     for face in topo.faces():
         mod_shapes = make_shape.Modified(face)
         itr = TopTools.TopTools_ListIteratorOfListOfShape(mod_shapes)
         while itr.More():
             this = itr.Value()
             mod_builder.Modified(face, this)
             print "modified", face, this
             itr.Next()
                     
     for face in topo.faces():
         if make_shape.IsDeleted(face):
             del_builder.Delete(face)
예제 #44
0
    def __init__(self, face):
        self.face = face
        self.shellWires = []
        self.fillWires = []

        self.otherWires = []
        #compute inner and other wires
        self.outerWire = brt.OuterWire(face)
        for w in Topo(face).wires():
            if not w.IsSame(self.outerWire):
                self.otherWires.append(w)
예제 #45
0
    def offsetOnceSimple(self,distance):
        
        bo = BRepOffsetAPI.BRepOffsetAPI_MakeOffset();           
        map(bo.AddWire, self.lastWires);
        print "%d wires to offset at step 1, distance = %0.3f" % ( len(self.lastWires),distance);
        bo.Perform(distance*(0.5),0.0);
        result1 = Topo(bo.Shape());

        returnList= [];
        #compound result can be a compound of edges and/or wires. weird weird
        for c in OCCUtil.childShapes(bo.Shape() ):
            display.DisplayColoredShape(c,'BLUE')
            if c.ShapeType() == TopAbs.TopAbs_WIRE:
                returnList.append(c);  #these are actually the wires we want to keep          
            elif c.ShapeType() == TopAbs.TopAbs_EDGE:
                w = OCCUtil.wireFromEdges([c])
                returnList.append(w);
            else:
                print "Warning: compound resulting from offset i am confused about-- not an edge or a wire."
            
        #for each original edge, compute its descendant edges
        #self.edgeMap will contain entries with the original edges, pointing to the generated
        #edges and the corresponding wire:
        #      e1 --> [ (e2, w2 ), (e3 , w3 ) ];
        for w in self.lastWires:
            originalWire = Topo(w);
            for oe in originalWire.edges():
                self.edgeMap[oe.__hash__()] = [];
                
                #find generated values from first transformation
                generatedStep1 = OCCUtil.listFromTopToolsListOfShape(bo.Generated(oe));
                for ne in generatedStep1:
                    #get wire this belongs to this returns a list but how could there ever be more than one?
                    gwires = []
                    for g in result1.wires_from_edge(ne):
                        gwires.append(g);
                    self.edgeMap[oe.__hash__()].append ( (ne,gwires[0]   ));
        
        self.lastWires = returnList;
        self.otherWires.extend(returnList);
        return returnList;
예제 #46
0
def build_curve_network(event=None):
    '''
    mimic the curve network surfacing command from rhino
    '''
    print 'Importing IGES file...',
    pth = os.path.dirname(os.path.abspath(__file__))
    pth = os.path.abspath(os.path.join(pth, '../../data/IGES/curve_geom_plate.igs'))
    iges = IGESImporter(pth)
    iges.read_file()
    print 'done.'
    # GetShapes returns 36 TopoDS_Shape, while the TopoDS_Compound contains
    # just the 6 curves I made in rhino... hmmm...
    print 'Building geomplate...',
    topo = Topo(iges.get_compound())
    edges_list = list(topo.edges())
    face = build_geom_plate(edges_list)
    print 'done.'
    
    print 'Cutting out of edges...',
    # Make a wire from outer edges
    _edges = [edges_list[2], edges_list[3], edges_list[4], edges_list[5]]
    outer_wire = make_wire(_edges)
예제 #47
0
def pixmapFromFace2(face, fillpattern=None):
    """
		create a filled pixmap from a defined face.
		
		ideally, this is really really fast, based on a triangulation of the face.
		a face with 800x600 pixels took 56ms to raster with this algo. @ 0.012" that is a 6x8 " part!

		this creates a pixel map that has all the interior pixels filled
		
		This version uses the boundaries and PIL.polygon instead of 
		the triangulagion, primarily becaseu the OCC triangulation seems to suck
		
		the general approach is:
			compute a filled shape containging a bit mask
			draw borders using a value
			tile a fill pattern onto the background
	"""

    PIXEL = 0.012
    DEFLECTION = PIXEL / 2.0

    #get bounding box
    (xMin, yMin, zMin, xMax, yMax, zMax) = boundingBox([face])

    #adjust boundaries a bit
    BUFFER = PIXEL * 5
    #make pixmap
    pixmap = pixmaptest.pixmap((xMin - BUFFER, yMin - BUFFER),
                               (xMax + BUFFER, yMax + BUFFER), PIXEL)

    #we will draw the outer wire as a filled polygon, then
    #draw the inner wire as another filled polygon

    ow = brt.OuterWire(face)
    outerPoints = tuplesFromWire(ow, DEFLECTION)
    #outerPoints.pop(2);
    #print outerPoints
    pixmap.drawPolygon(outerPoints, 1, 1)
    #drawWire(outerPoints,pixmap);
    #pixmap.saveImage("c:\\temp\\heartborder-1.bmp");

    #get the other wires.
    wires = []
    wires.append(outerPoints)
    for w in Topo(face).wires():
        if not w.IsSame(ow):
            wp = tuplesFromWire(w, DEFLECTION)
            pixmap.drawPolygon(wp, 0, 0)
            wires.append(wp)

    return pixmap
예제 #48
0
    def testRemovedByRefFeature(self):
        """ test that arguments returned by ref transormation is ok
        """
        from OCC.BRepPrimAPI import BRepPrimAPI_MakeSphere
        from OCC.BRep import BRep_Tool_Surface
        from OCC.GeomLProp import GeomLProp_SLProps
        from OCC.gp import gp_Pnt

        sphere_shape = BRepPrimAPI_MakeSphere(40.0).Shape()
        # build a surface from this sphere
        from OCC.Utils.Topology import Topo

        t = Topo(sphere_shape)
        for f in t.faces():
            face = f

        surf = BRep_Tool_Surface(face)
        lprop = GeomLProp_SLProps(0, 1e-12)
        lprop.SetSurface(surf)

        # evaluate_uv_coordinates
        coords = []
        p = 0.0
        # first point
        u, v = [0, 0]
        lprop.SetParameters(u, v)
        pnt = lprop.Value()
        print "First point coords : ", pnt.Coord()
        print surf.GetObject().Value(u, v).Coord()
        # This one is [40.0,0.,0.]
        self.assertEqual(str(pnt.Coord()), "(40.0, 0.0, 0.0)")
        coords.append(pnt)
        # second point
        u, v = [0.5, 0.5]
        lprop.SetParameters(u, v)
        pnt2 = lprop.Value()
        # check then that the value has not changed (it does if returned by ref)
        self.assertEqual(str(pnt.Coord()), "(40.0, 0.0, 0.0)")
예제 #49
0
def build_curve_network(event=None):
    '''
    mimic the curve network surfacing command from rhino
    '''
    print 'Importing IGES file...',
    pth = os.path.dirname(os.path.abspath(__file__))
    pth = os.path.abspath(os.path.join(pth, '../../data/IGES/curve_geom_plate.igs'))
    iges = IGESImporter(pth)
    iges.read_file()
    print 'done.'
    
    print 'Building geomplate...',
    topo = Topo(iges.get_compound())
    edges_list = list(topo.edges())
    face = build_geom_plate(edges_list)
    print 'done.'
    display.EraseAll()
    display.DisplayShape(edges_list)
    display.FitAll()
    print 'Cutting out of edges...',
    # Make a wire from outer edges
    _edges = [edges_list[2], edges_list[3], edges_list[4], edges_list[5]]
    outer_wire = make_wire(_edges)
예제 #50
0
def testOffsetMapDecendants():
    #test that we can find the edge, vertex, and wire from a given edge

    f = TestObjects.makeSquareWithRoundHole()
    #face that will have odd offsets
    om = OffsetMap(f)
    om.offsetOnce(-0.2)

    #display each edge and its decendant edge.
    #each original edge and vertex is checked
    #in each case the result should be the edge that was created from the one in green,
    #and the blue point should be the vertex of that edge closest to the green vertex
    for w in om.originalWires:
        for e in Topo(w).edges():
            for v in Topo(e).vertices():
                display.EraseAll()
                display.DisplayColoredShape(v, 'GREEN')
                display.DisplayColoredShape(e, 'GREEN')
                (nv, ne, nw) = om.getNextEdge(e, v)
                display.DisplayColoredShape(nw, 'YELLOW')
                display.DisplayColoredShape(ne, 'RED')
                display.DisplayColoredShape(nv, 'BLUE')
                time.sleep(5)
예제 #51
0
 def execute(self):
     input_shape = self.input.shape
     
     topo = Topo(input_shape)
     self._n_edges = topo.number_of_edges()
     
     builder = BRepFilletAPI.BRepFilletAPI_MakeChamfer(input_shape)
     
     Map = TDF.TDF_LabelMap()
     itr = TDF.TDF_ChildIterator(self.parent_label, True)
     while itr.More():
         sub_label = itr.Value()
         Map.Add(sub_label)
         itr.Next()
         
     selector = self.selector
     ret = selector.Solve(Map)
     
     if not ret:
         raise Exception("Failed to solve for edge")
         #print "Failed to solve for edge"
     
     nt = TNaming.TNaming_Tool()
     selected_shape = nt.CurrentShape(selector.NamedShape())
     
     selected_edge = TopoDS.TopoDS().Edge(selected_shape)
     
     try:
         face = Topo(input_shape).faces_from_edge(selected_edge).next()
     except RuntimeError:
         raise #not sure how to handle this
     size = self.size
     builder.Add(size, size, selected_edge, face)
     
     self.update_naming(builder)
     return builder.Shape()
    def test_brep_feat_extrusion_protrusion(self):
        print 'Test: brep_feat extrusion protusion'
        #Extrusion
        S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape()
        faces = Topo(S).faces()
        F = faces.next()
        surf1 = BRep_Tool_Surface(F)

        Pl1 = Handle_Geom_Plane_DownCast(surf1).GetObject()

        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, TolDegen)
        MKF.Add(MW.Wire())
        FP = MKF.Face()
        BRepLib_BuildCurves3d(FP)

        MKP = BRepFeat_MakePrism(S, FP, F, D1, 0, True)
        MKP.PerformThruAll()
        self.assertTrue(MKP.IsDone())
        self.assertFalse(MKP.Shape().IsNull())
        res1 = MKP.Shape()

        # Protrusion
        faces.next()
        F2 = faces.next()
        surf2 = BRep_Tool_Surface(F2)
        Pl2 = Handle_Geom_Plane_DownCast(surf2).GetObject()
        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, TolDegen)
        MKF2.Add(MW2.Wire())
        MKF2.Build()

        FP = MKF2.Face()
        BRepLib_BuildCurves3d(FP)
        MKP2 = BRepFeat_MakePrism(res1, FP, F2, D2, 0, True)
        MKP2.PerformThruAll()
        self.assertTrue(MKF2.IsDone())

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

        from OCC.BRepAlgoAPI import BRepAlgoAPI_Fuse
        fused = BRepAlgoAPI_Fuse(tr.Shape(), MKP2.Shape())
        fused.RefineEdges()
        fused.Build()
        self.assertTrue(fused.IsDone())
        self.assertFalse(fused.Shape().IsNull())
예제 #53
0
파일: FEM.py 프로젝트: NiSchultz/pythonocc
class VtkVisualizeAnalysis(VisualizeAnalysis):
    '''
    concrete visualization class, using the vtk
    '''
    raise NotImplementedError
    

#===============================================================================
# Example of usage of the future framework ---
#===============================================================================

from OCC.BRepPrimAPI import *
from OCC.gp import *

shape = BRepPrimAPI_MakeBox(1,1,1).Shape()  # stupid shape for analysis
topo = Topo(shape)                          # for traversing the topology
faces = topo.faces()                        # faces of the box  
face1 = faces.next()                        # face used for loads
face2 = faces.next()                        # face that will be locked

mesh_driver = QuadMeshDriver('nadah')       # set up the mesh driver. when geometry is updated, so will the mesh before solving it
analysis    = LinearElasticityAnalysis()    # set up the problem to be solved
solver      = AbacusSolver()                # configure the solver

FEMSimulation = FEMSimulation(shape)            
FEMSimulation.load(face1, gp_Vec())       
FEMSimulation.lock(face2, x=False, y=False, z=True)
FEMSimulation.analysis = analysis
FEMSimulation.solver = solver
FEMSimulation.mesh_driver = mesh_driver
FEMSimulation.output_dir = '/dev/null/simulation.fem'
예제 #54
0
app.NewDocument(schema, h_doc)

doc = h_doc.GetObject()

root = doc.Main()

ts = TDF.TDF_TagSource()


box = BRepPrimAPI.BRepPrimAPI_MakeBox(20.0,20.0,20.0).Shape()

box_label = ts.NewChild(root)
ns_builder = TNaming.TNaming_Builder(box_label)
ns_builder.Generated(box)

topo = Topo(box)

##
##Name all the subshape we *might* want to refer to later
##
for edge in topo.edges():
    sub_label = ts.NewChild(box_label)
    ns_builder = TNaming.TNaming_Builder(sub_label)
    ns_builder.Generated(edge)

#
#Find and Name an edge
#
an_edge = topo.edges().next()

s_label = ts.NewChild(root)
예제 #55
0
                                         aShape
                                         )

        aMesh.AddGroup( group_load.GetType(),
                        groupName,
                        group_load.GetShape()
                        )
        self.indx += 1
        return True

from OCC.KBE.Level2API import *
from OCC.Utils.Topology import Topo

# compute and sort faces by area
# use the 2 first faces on which boundary conditions will be set 
topo = Topo(aShape)
faces = [Face(i) for i in topo.faces()]

# create the groups 
# note that groups can only be created when the mesh is computed
# calling group will check if any nodes are present in the mesh
# and assumes that its computed when it finds any nodes
group =  GroupOnGeom()
group(aMesh,faces[0].face,SMDSAbs_Face,'load')
group(aMesh,faces[4].face,SMDSAbs_Face, 'lock')

#===============================================================================
# EXPORT
#===============================================================================

# Export the data
def brep_feat_extrusion_protrusion(event=None):
    #Extrusion 
    S = BRepPrimAPI_MakeBox(400.,250.,300.).Shape()
    faces = Topo(S).faces()
    F = faces.next()
    surf1 = BRep_Tool_Surface(F)
    
    Pl1 = Handle_Geom_Plane_DownCast(surf1).GetObject()
    
    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)
#    MKP = BRepFeat_MakePrism(S,FP,F,D1,0,True)
#    MKP.Perform(-200)
#    print 'depth 200'
#    res1 = MKP.Shape()
#    display.DisplayShape(res1)
#    time.sleep(1)
    
    display.EraseAll()
    MKP = BRepFeat_MakePrism(S,FP,F,D1,0,True)
    MKP.PerformThruAll()
    print 'depth thru all'
    res1 = MKP.Shape()
#    display.DisplayShape(res1)
    
    # Protrusion
    faces.next()  
    F2 = faces.next()
    surf2 = BRep_Tool_Surface(F2)
    Pl2 = Handle_Geom_Plane_DownCast(surf2).GetObject()
    D2 = Pl2.Pln().Axis().Direction().Reversed()
    MW2 = BRepBuilderAPI_MakeWire() 
    p1, p2 = gp_Pnt2d(100.,100.), gp_Pnt2d(200.,100.)
#    p1, p2 = gp_Pnt2d(100.,100.), gp_Pnt2d(150.,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()
    
#    display.DisplayShape(MW2.Wire())
    
    FP = MKF2.Face()
    BRepLib_BuildCurves3d(FP)
    MKP2 = BRepFeat_MakePrism(res1,FP,F2,D2,0,True)
    MKP2.PerformThruAll()
    display.EraseAll()
#    display.DisplayShape(MKP2.Shape())
    
    trf = gp_Trsf()
    trf.SetTranslation(gp_Vec(0,0,300))
    gtrf = gp_GTrsf()
    gtrf.SetTrsf(trf)
    tr = BRepBuilderAPI_GTransform(MKP2.Shape(), gtrf, True)
    
    
    from OCC.BRepAlgoAPI import BRepAlgoAPI_Fuse
    fused = BRepAlgoAPI_Fuse(tr.Shape(), MKP2.Shape())
    fused.RefineEdges()
    fused.Build()
    print 'boolean operation error status:', fused.ErrorStatus()
    display.DisplayShape(fused.Shape())