Example #1
0
    def WindowContour(self, WinCenter):
        """Creates and returns the contour of the window at WinCenter
        
        Parameters
        ----------
        WinCenter : list or array, length 2
            The [X, Z] coordinate of the center of the window
        
        Returns
        -------
        W_wire : TopoDS_Wire
            The wire of the B-spline contour
        """
        raise NotImplementedError(
            "This function is in development, and its output is untested")
        P1 = gp_Pnt(WinCenter[0], 0, WinCenter[1] + 0.468/2.)
        P2 = gp_Pnt(WinCenter[0] + 0.272/2., 0, WinCenter[1])
        P3 = gp_Pnt(WinCenter[0], 0, WinCenter[1] - 0.468/2.)
        P4 = gp_Pnt(WinCenter[0] - 0.272/2., 0, WinCenter[1])
    
        tangents = np.array([[0,    0,  2.5],
                            [0,    0, -2.5]])
    
        WCurveU = act.points_to_bspline([P4, P1, P2], tangents=tangents)
        # Need to reverse the tangents for the following shape:
        WCurveL =  act.points_to_bspline([P2, P3, P4], tangents=tangents[::-1])
        
        edgeU = act.make_edge(WCurveU)
        edgeL = act.make_edge(WCurveL)
        
#        W_face= act.make_face(act.make_wire([edgeU, edgeL]))
        W_wire = act.make_wire([edgeU, edgeL])
        return W_wire
Example #2
0
def get_mesh_precision(shape, quality_factor):
    bbox = Bnd_Box()
    BRepBndLib_Add(shape, bbox)
    x_min,y_min,z_min,x_max,y_max,z_max = bbox.Get()
    diagonal_length = gp_Vec(gp_Pnt(x_min, y_min, z_min),
                             gp_Pnt(x_max, y_max, z_max)).Magnitude()
    return (diagonal_length / 20.) / quality_factor
Example #3
0
    def copyToZ(self, z, layerNo):
        "makes a copy of this slice, transformed to the specified z height"

        theCopy = Slice()
        theCopy.zLevel = z
        theCopy.fillAngle = self.fillAngle
        theCopy.layerNo = layerNo
        theCopy.thickness = self.thickness

        # make transformation
        p1 = gp.gp_Pnt(0, 0, 0)
        p2 = gp.gp_Pnt(0, 0, z)
        xform = gp.gp_Trsf()
        xform.SetTranslation(p1, p2)
        bt = BRepBuilderAPI.BRepBuilderAPI_Transform(xform)

        # copy all of the faces
        for f in self.faces:

            bt.Perform(f.face, True)
            newFace = Face(OCCUtil.cast(bt.Shape()))

            # copy shells
            for shell in f.shellWires:
                # print shell
                bt.Perform(shell, True)
                newFace.shellWires.append(OCCUtil.cast(bt.Shape()))

            # copy fillWires
            for fill in f.fillWires:
                bt.Perform(fill, True)
                newFace.shellWires.append(OCCUtil.cast(bt.Shape()))
            theCopy.addFace(newFace)

        return theCopy
Example #4
0
def pipe(event=None):
  CurvePoles = TColgp_Array1OfPnt(1,6)
  pt1 = gp_Pnt(0.,0.,0.);
  pt2 = gp_Pnt(20.,50.,0.);
  pt3 = gp_Pnt(60.,100.,0.);
  pt4 = gp_Pnt(150.,0.,0.);
  CurvePoles.SetValue(1, pt1)
  CurvePoles.SetValue(2, pt2)
  CurvePoles.SetValue(3, pt3)
  CurvePoles.SetValue(4, pt4)

  curve = Geom_BezierCurve(CurvePoles)
  print type(curve)
  E = BRepBuilderAPI_MakeEdge(curve.GetHandle()).Edge()
  W = BRepBuilderAPI_MakeWire(E).Wire()
   
  #ais1 = AIS_Shape(W)
  #self.interactive_context.Display(ais1,1)
   
  c = gp_Circ(gp_Ax2(gp_Pnt(0.,0.,0.),gp_Dir(0.,1.,0.)),10.)
  Ec = BRepBuilderAPI_MakeEdge(c).Edge()
  Wc = BRepBuilderAPI_MakeWire(Ec).Wire()

  #ais3 = AIS_Shape(Wc)
  #self.interactive_context.Display(ais3,1)
   
  F = BRepBuilderAPI_MakeFace(gp_Pln(gp_Ax3(gp.gp().ZOX())),Wc,1).Face()
  MKPipe = BRepOffsetAPI_MakePipe(W,F)
  MKPipe.Build()
  display.DisplayShape(MKPipe.Shape())
def make_face_to_contour_from():
    v1 = make_vertex(gp_Pnt(0, 0, 0))
    v2 = make_vertex(gp_Pnt(10, 0, 0))
    v3 = make_vertex(gp_Pnt(7, 10, 0))
    v4 = make_vertex(gp_Pnt(10, 20, 0))
    v5 = make_vertex(gp_Pnt(0, 20, 0))
    v6 = make_vertex(gp_Pnt(3, 10, 0))
    e1 = make_edge(v1, v2)
    e2 = make_edge(v2, v3)
    e3 = make_edge(v3, v4)
    e4 = make_edge(v4, v5)
    e5 = make_edge(v5, v6)
    e6 = make_edge(v6, v1)
    v7 = make_vertex(gp_Pnt(2, 2, 0))
    v8 = make_vertex(gp_Pnt(8, 2, 0))
    v9 = make_vertex(gp_Pnt(7, 3, 0))
    v10 = make_vertex(gp_Pnt(3, 3, 0))
    e7 = make_edge(v7, v8)
    e8 = make_edge(v8, v9)
    e9 = make_edge(v9, v10)
    e10 = make_edge(v10, v7)
    w1 = make_wire([e1, e2, e3, e4, e5, e6])
    f = make_face(w1)
    w2 = make_wire(e7, e8, e9, e10)
    f2 = make_face(w2)
    f3 = boolean_cut(f, f2)
    return f3
Example #6
0
def move(orig_pypt, location_pypt, occtopology):
    """
    This function moves an OCCtopology from the orig_pypt to the location_pypt.
 
    Parameters
    ----------        
    orig_pypt : tuple of floats
        The OCCtopology will move in reference to this point.
        A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z)
        
    location_pypt : tuple of floats
        The destination of where the OCCtopology will be moved in relation to the orig_pypt.
        A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z)
        
    occtopology : OCCtopology
        The OCCtopology to be moved.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 

    Returns
    -------
    moved topology : OCCtopology (OCCshape)
        The moved OCCtopology.
    """
    gp_ax31 = gp_Ax3(gp_Pnt(orig_pypt[0], orig_pypt[1], orig_pypt[2]), gp_DZ())
    gp_ax32 = gp_Ax3(gp_Pnt(location_pypt[0], location_pypt[1], location_pypt[2]), gp_DZ())
    aTrsf = gp_Trsf()
    aTrsf.SetTransformation(gp_ax32,gp_ax31)
    trsf_brep = BRepBuilderAPI_Transform(aTrsf)
    trsf_brep.Perform(occtopology, True)
    trsf_shp = trsf_brep.Shape()
    return trsf_shp
Example #7
0
def create_AirconicsShape():
    """Populates a basic airconics shape with a unit cube striding by 1 in x y 
    and z from the origin, and a unit sphere centered at the origin"""
    cube = BRepPrimAPI_MakeBox(gp_Pnt(0,0,0), 1, 1, 1).Shape()
    sphere = BRepPrimAPI_MakeSphere(gp_Pnt(0,0,0), 1).Shape()
    shape = AirconicsShape(components={'cube': cube, 'sphere': sphere})
    return shape
def fillet(event=None):
    Box = BRepPrimAPI_MakeBox(gp_Pnt(-400, 0, 0), 200, 230, 180).Shape()
    fillet = BRepFilletAPI_MakeFillet(Box)
    # Add fillet on each edge
    for e in Topo(Box).edges():
        fillet.Add(20, e)

    blendedBox = fillet.Shape()

    P1 = gp_Pnt(250, 150, 75)
    S1 = BRepPrimAPI_MakeBox(300, 200, 200).Shape()
    S2 = BRepPrimAPI_MakeBox(P1, 120, 180, 70).Shape()
    Fuse = BRepAlgoAPI_Fuse(S1, S2)
    FusedShape = Fuse.Shape()

    fill = BRepFilletAPI_MakeFillet(FusedShape)
    for e in Topo(FusedShape).edges():
        fill.Add(e)

    for i in range(1, fill.NbContours() + 1):
        length = fill.Length(i)
        Rad = 0.15 * length
        fill.SetRadius(Rad, i, 1)

    blendedFusedSolids = fill.Shape()

    display.EraseAll()
    display.DisplayShape(blendedBox)
    display.DisplayShape(blendedFusedSolids)
    display.FitAll()
def test_CalculateSurfaceArea():
    """Use a few simple shapes to test the surface area function.

    Notes
    -----
    This isnt testing the area building algorithm, just that my setup of the
    function works for a variety of different OCC objects - PChambers
    """
    # A flat square edge lengths 1
    from OCC.BRepBuilderAPI import BRepBuilderAPI_MakePolygon
    p1 = gp_Pnt(0, 0, 0)
    p2 = gp_Pnt(1, 0, 0)
    p3 = gp_Pnt(1, 1, 0)
    p4 = gp_Pnt(0, 1, 0)
    surf1 = act.make_face(
        BRepBuilderAPI_MakePolygon(p1, p2, p3, p4, True).Wire())
    # The tolerance for difference between output and expected area
    tol = 1e-12
    assert(np.abs(act.CalculateSurfaceArea(surf1) - 1) < tol)

    # A sphere with radius 1
    from OCC.BRepPrimAPI import BRepPrimAPI_MakeSphere
    r = 1
    # The tolerance need to be relaxed a bit for this case
    tol = 1e-04
    sphere = BRepPrimAPI_MakeSphere(r).Shape()
    assert(np.abs(act.CalculateSurfaceArea(sphere) - 4 * np.pi * (r**2)) < tol)
def test_project_curve_to_plane():
    # Projects a line of length 1 from above the XOY plane, and tests points
    # on the resulting line
    from OCC.Geom import Geom_Plane, Geom_TrimmedCurve
    from OCC.GC import GC_MakeSegment
    from OCC.gp import gp_Ax3, gp_XOY, gp_Pnt, gp_Dir
    XOY = Geom_Plane(gp_Ax3(gp_XOY()))
    curve = GC_MakeSegment(gp_Pnt(0, 0, 5),
                           gp_Pnt(1, 0, 5)).Value()
    direction = gp_Dir(0, 0, 1)

    Hproj_curve = act.project_curve_to_plane(curve, XOY.GetHandle(),
                                            direction)

    proj_curve = Hproj_curve.GetObject()

    # The start and end points of the curve
    p1 = proj_curve.Value(0)
    p2 = proj_curve.Value(1)

    p1_array = np.array([p1.X(), p1.Y(), p1.Z()])
    p2_array = np.array([p2.X(), p2.Y(), p2.Z()])

    # The expected start and end points
    start = np.array([0, 0, 0])
    end = np.array([1, 0, 0])

    # Assert that neither points have a Y or Z component, and that
    assert((np.all(p1_array == start) and np.all(p2_array == end)) or
           (np.all(p1_array == end) and np.all(p2_array == start)))
Example #11
0
 def get_transform(self):
     d = self.declaration
     t = gp_Trsf()
     #: TODO: Order matters... how to configure it???
     if d.mirror:
         try:
             p,v = d.mirror
         except ValueError:
             raise ValueError("You must specify a tuple containing a (point,direction)")
         t.SetMirror(gp_Ax1(gp_Pnt(*p),
                            gp_Dir(*v)))
     if d.scale:
         try:
             p,s = d.scale
         except ValueError:
             raise ValueError("You must specify a tuple containing a (point,scale)")
         t.SetScale(gp_Pnt(*p),s)
     
     if d.translate:
         t.SetTranslation(gp_Vec(*d.translate))
     
     if d.rotate:
         try:
             p,v,a = d.rotate
         except ValueError:
             raise ValueError("You must specify a tuple containing a (point,direction,angle)")
         t.SetRotation(gp_Ax1(gp_Pnt(*p),
                            gp_Dir(*v)),a)
         
     return t
 def test_list(self):
     '''
     Test python lists features
     '''
     P1 = gp_Pnt(1, 2, 3)
     P2 = gp_Pnt(2, 3, 4)
     P3 = gp_Pnt(5, 7, 8)
     l = [P1, P2]
     self.assertEqual(P1 in l, True)
     self.assertNotEqual(P3 in l, True)
     self.assertEqual(l.index(P1), 0)
     self.assertEqual(l.index(P2), 1)
     # Do the same for Vertices (TopoDS_Shape has
     # a HashCode() method overloaded
     V1 = BRepBuilderAPI_MakeVertex(P1).Vertex()
     V2 = BRepBuilderAPI_MakeVertex(P2).Vertex()
     V3 = BRepBuilderAPI_MakeVertex(P3) .Vertex()
     vl = [V1, V2]
     self.assertEqual(V1 in vl, True)
     self.assertNotEqual(V3 in vl, True)
     # index test()
     self.assertEqual(vl.index(V1), 0)
     self.assertEqual(vl.index(V2), 1)
     # reverse() test
     vl.reverse()
     self.assertEqual(vl.index(V1), 1)
     self.assertEqual(vl.index(V2), 0)
 def DisplayG01Line(coor1,coor2):
         array=TColgp_Array1OfPnt(1,2)
         array.SetValue(1,gp_Pnt(coor1[0],coor1[1],coor1[2]))
         array.SetValue(2,gp_Pnt(coor2[0],coor2[1],coor2[2]))
         bspline2 = GeomAPI_PointsToBSpline(array).Curve()
         path_edge = BRepBuilderAPI_MakeEdge(bspline2).Edge()
         display.DisplayColoredShape(path_edge,'GREEN')
Example #14
0
    def copyToZ(self, z):
        "makes a copy of this slice, transformed to the specified z height"
        theCopy = Slice()
        theCopy.zLevel = z
        theCopy.zHeight = self.zHeight
        theCopy.sliceHeight = self.sliceHeight
        theCopy.fillWidth = self.fillWidth
        theCopy.hatchDir = self.hatchDir
        theCopy.checkSum = self.checkSum

        # make transformation
        p1 = gp.gp_Pnt(0, 0, 0)
        p2 = gp.gp_Pnt(0, 0, z)
        xform = gp.gp_Trsf()
        xform.SetTranslation(p1, p2)
        bt = BRepBuilderAPI.BRepBuilderAPI_Transform(xform)

        # copy all of the faces
        for f in hSeqIterator(self.faces):
            bt.Perform(f, True)
            theCopy.addFace(Wrappers.cast(bt.Shape()))

            # copy all of the fillWires
        for w in hSeqIterator(self.fillWires):
            bt.Perform(w, True)
            # TestDisplay.display.showShape(bt.Shape() );
            theCopy.fillWires.Append(Wrappers.cast(bt.Shape()))

            # copy all of the fillEdges
        for e in hSeqIterator(self.fillEdges):
            bt.Perform(e, True)
            # TestDisplay.display.showShape(bt.Shape() );
            theCopy.fillEdges.Append(Wrappers.cast(bt.Shape()))

        return theCopy
Example #15
0
def TestDivideEdge():
    #lines are parameterized between 0 and line length
    edge = edgeFromTwoPoints ( gp.gp_Pnt(0,0,0), gp.gp_Pnt(2,2,0));
    (handleCurve, p1, p2  ) = brepTool.Curve(edge); #p1=0, #p2=2.828
    print p1,p2
    totalLen = (p2 - p1);
    display.DisplayColoredShape(edge, 'BLUE');
    #divide the edge into two edges, split at 0.25 units from param=1.414, with a gap of 0.1 between them
    edges = divideEdgeAtParam(edge, 1.414, 0.25,0.1); #divide the edge into two edges
    assert(len(edges)== 2);
    (e1,e2) = ( edges[0],edges[1]);
    (hc,q1,q2) = brepTool.Curve(e1);
    print q1,q2;

    (hc,q1,q2) = brepTool.Curve(e2);
    print q1,q2;
    print Wrappers.Edge(e1).distanceBetweenEnds();
    assert (abs(Wrappers.Edge(e1).distanceBetweenEnds()- (1.414 + 0.25)) < 0.000001);
    assert (abs(Wrappers.Edge(e2).distanceBetweenEnds() - (totalLen - 1.414 - 0.25 - 0.1)) < 0.0000001 ); 
    display.DisplayColoredShape(edges,'RED');
    
    edges = divideEdgeAtParam(edge, 1.414, 2.5,0.1); #should return one edge of length 0.1 less than total
    assert ( len(edges) ==1);
    assert ( abs(Wrappers.Edge(edges[0]).distanceBetweenEnds() - (totalLen - 0.1)) < 0.0000001 );
    display.DisplayColoredShape(edges,'GREEN');
Example #16
0
def center_boundingbox(shape):
    '''
    compute the center point of a TopoDS_Shape, based on its bounding box
    @param shape: TopoDS_* instance
    returns a gp_Pnt instance
    '''
    xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(shape, 1e-6)
    return midpoint(gp_Pnt(xmin, ymin, zmin), gp_Pnt(xmax, ymax, zmax))
def BBox_FromExtents(xmin, ymin, zmin, xmax, ymax, zmax):
    """Generates the Wire Edges defining the Bounding Box defined in the input
    arguments: Can be used to display the bounding box"""
    s = BRepPrimAPI_MakeBox(gp_Pnt(xmin, ymin, zmin),
                            gp_Pnt(xmax, ymax, zmax)).Shape()
    ais_bbox = AIS_Shape(s)
    ais_bbox.SetDisplayMode(AIS_WireFrame)
    return ais_bbox.GetHandle()
def CutSect(Shape, SpanStation):
    """
    Parameters
    ----------
    Shape : TopoDS_Shape
        The Shape to find planar cut section (parallel to xz plane)

    SpanStation : scalar in range (0, 1)
        y-direction location at which to cut Shape

    Returns
    -------
    Section : result of OCC.BRepAlgoAPI.BRepAlgoAPI_Section (TopoDS_Shape)
        The cut section of shape given a cut plane parallel to xz at input
        Spanstation.

    Chord : result of OCC.GC.GC_MakeSegment.Value (Geom_TrimmedCurve)
        The Chord line between x direction extremeties
    """
    (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) = ObjectsExtents([Shape])

    YStation = Ymin + (Ymax - Ymin) * SpanStation
    OriginX = Xmin - 1
    OriginZ = Zmin - 1

    P = gp_Pln(gp_Pnt(OriginX, YStation, OriginZ), gp_Dir(gp_Vec(0, 1, 0)))
    # Note: using 2*extents here as previous +1 trimmed plane too short
    CutPlaneSrf = make_face(P, 0, Zmax + 2, 0, Xmax +2)

    I = BRepAlgoAPI_Section(Shape, CutPlaneSrf)
    I.ComputePCurveOn1(True)
    I.Approximation(True)
    I.Build()
    Section = I.Shape()

    (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) = ObjectsExtents([Section])

#     Currently assume only one edge exists in the intersection:
    exp = TopExp_Explorer(Section, TopAbs_EDGE)
    edge = topods_Edge(exp.Current())

#    Find the apparent chord of the section (that is, the line connecting the
#    fore most and aftmost points on the curve
    DivPoints = Uniform_Points_on_Curve(edge, 200)

    Xs = np.array([pt.X() for pt in DivPoints])

    min_idx = np.argmin(Xs)
    LeadingPoint = gp_Pnt(Xs[min_idx], DivPoints[min_idx].Y(),
                          DivPoints[min_idx].Z())

    max_idx = np.argmax(Xs)
    TrailingPoint = gp_Pnt(Xs[max_idx], DivPoints[max_idx].Y(),
                           DivPoints[max_idx].Z())

    HChord = GC_MakeSegment(TrailingPoint, LeadingPoint).Value()
#    Chord = HChord.GetObject()
    return Section, HChord
Example #19
0
def scanlinesFromBoundingBox(boundingBox,interval):
	(xMin,yMin,zMin,xMax,yMax,zMax) = boundingBox;
	print boundingBox;
	edges = [];
	for y in Wrappers.frange6(yMin,yMax,interval):
		e = Wrappers.edgeFromTwoPoints(gp.gp_Pnt(xMin,y,0),gp.gp_Pnt(xMax,y,0));
		#TestDisplay.display.showShape(e);
		edges.append((y,Wrappers.wireFromEdges([e])));
	return edges;
Example #20
0
def makeHeartWire():
	"make a heart wire"
	e1 = Wrappers.edgeFromTwoPoints(gp.gp_Pnt(0,0,0), gp.gp_Pnt(4.0,4.0,0));
	circle = gp.gp_Circ(gp.gp_Ax2(gp.gp_Pnt(2,4,0),gp.gp().DZ()),2);
	e2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(circle, gp.gp_Pnt(4,4,0),gp.gp_Pnt(0,4,0)).Edge();
	circle = gp.gp_Circ(gp.gp_Ax2(gp.gp_Pnt(-2,4,0),gp.gp().DZ()),2);
	e3 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(circle, gp.gp_Pnt(0,4,0),gp.gp_Pnt(-4,4,0)).Edge();
	e4 = Wrappers.edgeFromTwoPoints(gp.gp_Pnt(-4,4,0), gp.gp_Pnt(0,0,0));
	return Wrappers.wireFromEdges([e1,e2,e3,e4]);
def make_circle3pt(pt1, pt2, pt3):
    """Makes a circle allowing python lists as input points"""
    try:
        pt1 = gp_Pnt(*pt1)
        pt2 = gp_Pnt(*pt2)
        pt3 = gp_Pnt(*pt3)
    except:
        pass
    return GC_MakeCircle(pt1, pt2, pt3).Value()
Example #22
0
	def move(self, x = None, y = None, z = None,  feed=None, cmd="G01"):
		
		
		if x == None: x = self.currentX
		if y == None: y = self.currentY
		if z == None: z = self.currentZ
		if feed == None: feed = self.currentFeed;
		
		#rapids reset naive move tracking
		if cmd != 'G01':
			self.lastMove = None;
	
		#if there is no move at all, return immediately
		if ( close(x , self.currentX ) and close(y ,self.currentY)  and close(z , self.currentZ) ):
			log.debug(  "No move required" );
			return "";

		#compute direction of the move, to filter out naive moves
		if  self.currentX != None and self.currentY != None and self.currentZ != None and self.currentFeed != None:
			#ok we are doing a move, and we know what our current location and feed is
			#so we can compute a direction
			currentPoint = gp.gp_Pnt(self.currentX, self.currentY, self.currentZ);
			newPoint = gp.gp_Pnt(x,y,z);
			proposedMove = gp.gp_Vec(currentPoint,newPoint);
			
			if self.lastMove:
				#we have a last move. compare this one to see if they are the same direction
				if ( proposedMove.IsParallel(self.lastMove,TOLERANCE )) and ( self.currentFeed == feed) :
					#caught a naive move
					log.debug("Caught a naive move. Adjusting to remove the extra");
					#TODO this approach only works with absolute coordinates
					#in incremental coordinates, we have to adjust the new vector to move the same
					#as all of the previous moves!
					self.removeLastNonCommentMove();
					#self.comment("Removed Move");
					#remove last non-comment move
					
			#store this one as the last move
			self.lastMove = proposedMove;
		
		#compare the direction of this move to the previous move.
		cmds=[]
		cmds.append(cmd);
		if not close(x, self.currentX):
			cmds.append( ("X" + self.numberFormat)  % (x) );
			self.currentX = x
		if not close(y , self.currentY):
			cmds.append( ("Y" + self.numberFormat)  % (y) );
			self.currentY = y
		if not close( z, self.currentZ):
			cmds.append( ("Z" + self.numberFormat)  % (z) );
			self.currentZ = z
		if feed != self.currentFeed:
			cmds.append(("F" + self.numberFormat) % (feed) );
			self.currentFeed = feed;	
			
		self.addCommand( " ".join(cmds));
 def DisplayG00Line(coor1,coor2):
         coors=[coor1,[coor2[0],coor1[1],coor1[2]],[coor2[0],coor2[1],coor1[2]],coor2]
         for i in range(3):
             array=TColgp_Array1OfPnt(1,2)
             array.SetValue(1,gp_Pnt(coors[i][0],coors[i][1],coors[i][2]))
             array.SetValue(2,gp_Pnt(coors[i+1][0],coors[i+1][1],coors[i+1][2]))
             bspline2 = GeomAPI_PointsToBSpline(array).Curve()
             path_edge = BRepBuilderAPI_MakeEdge(bspline2).Edge()
             display.DisplayColoredShape(path_edge,'YELLOW')
 def test_dict(self):
     '''
     Test python dict features
     '''
     P1 = gp_Pnt(1, 2, 3)
     P2 = gp_Pnt(2, 3, 4)
     d = {P1: 'P1', P2: 'P2'}
     self.assertEqual(d[P1] == 'P1', True)
     self.assertEqual(d[P2] == 'P2', True)
    def __init__(
        self,
        ApexPoint=gp_Pnt(0, 0, 0),
        SweepFunct=False,
        DihedralFunct=False,
        TwistFunct=False,
        ChordFunct=False,
        AirfoilFunct=False,
        ChordFactor=1,
        ScaleFactor=1,
        OptimizeChordScale=0,
        LooseSurf=1,
        SegmentNo=11,
        TipRequired=False,
        max_degree=8,
        continuity=GeomAbs_C2,
        construct_geometry=True,
    ):
        # convert ApexPoint from list if necessary
        try:
            ApexPoint = gp_Pnt(*ApexPoint)
        except:
            pass

        if not (SweepFunct or DihedralFunct or TwistFunct or ChordFunct or AirfoilFunct):
            print("Lifting Surface functional parameters not defined:")
            print("Initialising without geometry construction")
            construct_geometry = False

        self.CreateConstructionGeometry()

        #        Initialise the components using base class:
        super(LiftingSurface, self).__init__(
            components={},
            _ApexPoint=ApexPoint,
            _SweepFunct=SweepFunct,
            _DihedralFunct=DihedralFunct,
            _TwistFunct=TwistFunct,
            _ChordFunct=ChordFunct,
            _AirfoilFunct=AirfoilFunct,
            _ChordFactor=ChordFactor,
            _ScaleFactor=ScaleFactor,
            _Sections=[],
            LSP_area=None,
            AR=None,
            ActualSemiSpan=None,
            RootChord=None,
            SA=None,
            OptimizeChordScale=OptimizeChordScale,
            LooseSurf=LooseSurf,
            _NSegments=SegmentNo,
            TipRequired=TipRequired,
            max_degree=max_degree,
            Cont=continuity,
            construct_geometry=construct_geometry,
        )
 def testDict(self):
     """
     Test python dict features
     """
     print "Test: python dicts"
     P1 = gp_Pnt(1, 2, 3)
     P2 = gp_Pnt(2, 3, 4)
     d = {P1: "P1", P2: "P2"}
     self.assertEqual(d[P1] == "P1", True)
     self.assertEqual(d[P2] == "P2", True)
Example #27
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;		
def draw_lines(pnt_list, nr_of_points, display):
    """

    rendering a large number of points through the usual way of:

        display.DisplayShape( make_vertex( gp_Pnt() ) )

    is fine for TopoDS_Shapes but certainly not for large number of points.
    in comparison, drawing all the voxel samples takes 18sec using the approach above, but negigable when using this function
    its about 2 orders of Magnitude faster, so worth the extra hassle

    here we use a more close-to-the-metal approach of drawing directly in OpenGL

    see [1] for a more detailed / elegant way to perform this task

    [1] http://www.opencascade.org/org/forum/thread_21732/?forum=3

    Parameters
    ----------

    pnt_list: list of (x,y,z) tuples
        vertex list

    display: qtViewer3d

    """

    a_presentation, group = create_ogl_group(display)
    black = Quantity_Color(Quantity_NOC_BLACK)
    asp = Graphic3d_AspectLine3d(black, Aspect_TOL_SOLID, 1)

    gg = Graphic3d_ArrayOfPolylines(
        nr_of_points * 2,
        nr_of_points * 2,
        0,  # maxEdges
        False,  # hasVColors
        True,  # hasBColors
        False,  # hasEdgeInfos
    )

    try:
        while 1:
            pnt = gp_Pnt(*next(pnt_list))
            gg.AddVertex(pnt)
            pnt = gp_Pnt(*next(pnt_list))
            gg.AddVertex(pnt)
            # create the line, with a random color
            gg.AddBound(2, random.random(), random.random(), random.random())

    except StopIteration:
        pass

    group.SetPrimitivesAspect(asp.GetHandle())
    group.AddPrimitiveArray(gg.GetHandle())
    a_presentation.Display()
Example #29
0
def TestShortenEdge():
    #test trimming and such
    e1 = edgeFromTwoPoints ( gp.gp_Pnt(0,0,0), gp.gp_Pnt(1,1,0));
    display.DisplayColoredShape(e1,'BLUE');
    
    #just for testing, get the parameters of the new edge.
    (handleCurve, p1, p2  ) = BRep.BRep_Tool().Curve(e1);
    p = (p1 + p2) / 2 
    display.DisplayColoredShape( splitEdge(e1,p,0.1), 'RED');
    #display.DisplayColoredShape( shortenEdge(e1,p1,0.1), 'WHITE');
    display.DisplayColoredShape( shortenEdge(e1,p2,0.1), 'WHITE');    
def bisect_pnt(event=None):
    display.EraseAll()
    p1 = gp_Pnt2d(1, 0.5)
    p2 = gp_Pnt2d(0, 1e5)
    bi = GccAna_Pnt2dBisec(p1, p2)
    bisec = bi.ThisSolution()
    # enum GccInt_Lin, GccInt_Cir, GccInt_Ell, GccInt_Par, GccInt_Hpr, GccInt_Pnt
    p1_ = make_vertex(gp_Pnt(p1.X(), p1.Y(), 0))
    p2_ = make_vertex(gp_Pnt(p2.X(), p2.Y(), 0))
    display.DisplayShape([p1_, p2_])
    display.DisplayColoredShape(make_edge2d(bisec), 'BLUE')
    display.FitAll()
Example #31
0
def makeCircleWire():
    circle = gp.gp_Circ(gp.gp_Ax2(gp.gp_Pnt(0, 2, 0),
                                  gp.gp().DZ()), .75)
    e2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(circle, gp.gp_Pnt(0, 1.25, 0),
                                                gp.gp_Pnt(0, 1.25, 0)).Edge()
    return Wrappers.wireFromEdges([e2])
Example #32
0
def surface_from_curves():
    '''
    @param display:
    '''
    # First spline
    array = []
    array.append(gp_Pnt(-4, 0, 2))
    array.append(gp_Pnt(-7, 2, 2))
    array.append(gp_Pnt(-6, 3, 1))
    array.append(gp_Pnt(-4, 3, -1))
    array.append(gp_Pnt(-3, 5, -2))

    pt_list1 = point_list_to_TColgp_Array1OfPnt(array)
    SPL1 = GeomAPI_PointsToBSpline(pt_list1).Curve()
    SPL1_c = SPL1.GetObject()

    # Second spline
    a2 = []
    a2.append(gp_Pnt(-4, 0, 2))
    a2.append(gp_Pnt(-2, 2, 0))
    a2.append(gp_Pnt(2, 3, -1))
    a2.append(gp_Pnt(3, 7, -2))
    a2.append(gp_Pnt(4, 9, -1))
    pt_list2 = point_list_to_TColgp_Array1OfPnt(a2)
    SPL2 = GeomAPI_PointsToBSpline(pt_list2).Curve()
    SPL2_c = SPL2.GetObject()

    # Fill with StretchStyle
    display.DisplayShape(SPL1, color='WHITE')
    display.DisplayShape(SPL2, color='WHITE')
    aGeomFill1 = GeomFill_BSplineCurves(SPL1,
                                        SPL2,
                                        GeomFill_StretchStyle)

    SPL3 = Handle_Geom_BSplineCurve_DownCast(SPL1_c.Translated(gp_Vec(10, 0, 0)))
    SPL4 = Handle_Geom_BSplineCurve_DownCast(SPL2_c.Translated(gp_Vec(10, 0, 0)))

    # Fill with CoonsStyle
    display.DisplayShape(SPL3, color='WHITE')
    display.DisplayShape(SPL4, color='WHITE')
    aGeomFill2 = GeomFill_BSplineCurves(SPL3,
                                        SPL4,
                                        GeomFill_CoonsStyle)

    SPL5 = Handle_Geom_BSplineCurve_DownCast(SPL1_c.Translated(gp_Vec(20, 0, 0)))
    SPL6 = Handle_Geom_BSplineCurve_DownCast(SPL2_c.Translated(gp_Vec(20, 0, 0)))

    # Fill with CurvedStyle
    display.DisplayShape(SPL5, color='WHITE')
    display.DisplayShape(SPL6, color='WHITE')
    aGeomFill3 = GeomFill_BSplineCurves(SPL5,
                                        SPL6,
                                        GeomFill_CurvedStyle)

    aBSplineSurface1 = aGeomFill1.Surface()
    aBSplineSurface2 = aGeomFill2.Surface()
    aBSplineSurface3 = aGeomFill3.Surface()

    display.DisplayShape(make_face(aBSplineSurface1, 1e-6))
    display.DisplayShape(make_face(aBSplineSurface2, 1e-6), color='RED')
    display.DisplayShape(make_face(aBSplineSurface3, 1e-6), color='BLUE', update=True)
Example #33
0
def cut_out(base):
    outer = gp_Circ2d(gp_OX2d(), top_radius - 1.75 * roller_diameter)
    inner = gp_Circ2d(gp_OX2d(), center_radius + 0.75 * roller_diameter)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return result
Example #34
0
#
# Example of a bouncing ball with OpenCascade contactors and occ distance
#

from siconos.mechanics.collision.tools import Volume, Contactor
from siconos.io.mechanics_run import MechanicsHdf5Runner
from siconos import numerics
import siconos.io.mechanics_run
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeSphere
from OCC.gp import gp_Pnt

siconos.io.mechanics_run.set_backend('occ')

sphere = BRepPrimAPI_MakeSphere(1.).Shape()
ground = BRepPrimAPI_MakeBox(gp_Pnt(-50, -50, 0), 100., 100., .5).Shape()

# Creation of the hdf5 file for input/output
with MechanicsHdf5Runner() as io:

    io.add_occ_shape('Sphere', sphere)
    io.add_occ_shape('Ground', ground)

    io.add_object('sphere',
                  [Volume('Sphere'),
                   Contactor('Sphere', contact_type='Face', contact_index=0)],
                  mass=1, translation=[0, 0, 10], velocity=[0, 0, 0, 0, 0, 0])

    io.add_object('ground',
                  [Contactor('Ground', contact_type='Face', contact_index=5)],
                  mass=0, translation=[0, 0, 0])
Example #35
0
    shape = reader.OneShape()

    # Get bounding box
    xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(shape)

    # Build section plane
    XYZ = (1, 1, 0)
    lim_coord1 = (xmin, xmax)
    lim_coord2 = (ymin, ymax)

    section_height = zmin + 1e-3
    #    section_height = zmax-1e-3

    # A horizontal plane is created from which a face is constructed to intersect with
    # the building. The face is transparently displayed along with the building.
    section_plane = gp_Pln(gp_Pnt(0, 0, section_height), gp_Dir(0, 0, 1))
    section_face = BRepBuilderAPI_MakeFace(section_plane, xmin, xmax, ymin,
                                           ymax).Face()

    plt.figure()
    plt.xlim(lim_coord1)
    plt.ylim(lim_coord2)

    objects = set()

    # Explore the faces of the shape (these are known to be named)
    exp = TopExp_Explorer(shape, TopAbs_FACE)
    while exp.More():
        s = exp.Current()

        tp = Topo(s)
Example #36
0
    def write(self, mesh_points, filename, tolerance=None):
        """
		Writes a output file, called filename, copying all the structures from self.filename but
		the coordinates. mesh_points is a matrix that contains the new coordinates to
		write in the output file.

		:param numpy.ndarray mesh_points: it is a `n_points`-by-3 matrix containing
			the coordinates of the points of the mesh
		:param string filename: name of the output file.
		:param float tolerance: tolerance for the construction of the faces and wires
			in the write function. If not given it uses `self.tolerance`.
		"""
        self._check_filename_type(filename)
        self._check_extension(filename)
        self._check_infile_instantiation()

        self.outfile = filename

        if tolerance is not None:
            self.tolerance = tolerance

        # cycle on the faces to update the control points position
        # init some quantities
        faces_explorer = TopExp_Explorer(self.shape, TopAbs_FACE)
        n_faces = 0
        control_point_position = self._control_point_position

        compound_builder = BRep_Builder()
        compound = OCC.TopoDS.TopoDS_Compound()
        compound_builder.MakeCompound(compound)

        while faces_explorer.More():
            # similar to the parser method
            face = OCC.TopoDS.topods_Face(faces_explorer.Current())
            nurbs_converter = BRepBuilderAPI_NurbsConvert(face)
            nurbs_converter.Perform(face)
            nurbs_face = nurbs_converter.Shape()
            face_aux = OCC.TopoDS.topods_Face(nurbs_face)
            brep_face = BRep_Tool.Surface(OCC.TopoDS.topods_Face(nurbs_face))
            bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face)
            occ_face = bspline_face.GetObject()

            n_poles_u = occ_face.NbUPoles()
            n_poles_v = occ_face.NbVPoles()

            i = 0
            for pole_u_direction in range(n_poles_u):
                for pole_v_direction in range(n_poles_v):
                    control_point_coordinates = mesh_points[
                        i + control_point_position[n_faces], :]
                    point_xyz = gp_XYZ(*control_point_coordinates)

                    gp_point = gp_Pnt(point_xyz)
                    occ_face.SetPole(pole_u_direction + 1,
                                     pole_v_direction + 1, gp_point)
                    i += 1

            # construct the deformed wire for the trimmed surfaces
            wire_maker = BRepBuilderAPI_MakeWire()
            tol = ShapeFix_ShapeTolerance()
            brep = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                           self.tolerance).Face()
            brep_face = BRep_Tool.Surface(brep)

            # cycle on the edges
            edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE)
            while edge_explorer.More():
                edge = OCC.TopoDS.topods_Edge(edge_explorer.Current())
                # edge in the (u,v) coordinates
                edge_uv_coordinates = BRep_Tool.CurveOnSurface(edge, face_aux)
                # evaluating the new edge: same (u,v) coordinates, but different (x,y,x) ones
                edge_phis_coordinates_aux = BRepBuilderAPI_MakeEdge(\
                 edge_uv_coordinates[0], brep_face)
                edge_phis_coordinates = edge_phis_coordinates_aux.Edge()
                tol.SetTolerance(edge_phis_coordinates, self.tolerance)
                wire_maker.Add(edge_phis_coordinates)
                edge_explorer.Next()

            # grouping the edges in a wire
            wire = wire_maker.Wire()

            # trimming the surfaces
            brep_surf = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
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
Example #38
0
def vector_to_point(self):
    return gp_Pnt(self.XYZ())
Example #39
0
        job_file = arg
job = read_yaml(job_file)

#work item is in bound by box [-1000, -1000, -1000[, [1000, 2000, 1000]
blocks = job['blocks']

for b in blocks:
    print("blockid: %s" % b['blockid'])
    settings = job['job_settings']
    for i in b.keys():
        settings[i] = b[i]
        sweeper = ut.surface_sweeper(settings)
    vp_bf = b['view_port_bottom_left']
    vp_tr = b['view_port_top_right']
    front_face = get_front_surface(job['object_file'],
                                   gp_Pnt(vp_bf[0], vp_bf[1], vp_bf[2]),
                                   gp_Pnt(vp_tr[0], vp_tr[1], vp_tr[2]))
    long_slice = get_longest_slice(front_face, sweeper.sweep_width)
    sweep_wires_downside = sweeper.sweep_face(front_face, long_slice, 'down')
    sweep_wires_upside = sweeper.sweep_face(front_face, long_slice, 'up')
    del sweep_wires_downside[0]
    sweep_wires = sweep_wires_upside + sweep_wires_downside
    xmin, ymin, Zmin, xmax, ymax, Zmax = sweeper.get_shape_boundary(
        sweep_wires)
    wires_roboDK = {
        'wires': [],
        'boundary': [[xmin, ymin, Zmin], [xmax, ymax, Zmax]],
        'base_position': b['base_position']
    }
    ais_front = display.DisplayShape(front_face)
    display.Context.SetTransparency(ais_front, 0.8)
Example #40
0
def _apply(pnt, other, _operator):
    if isinstance(other, gp_Pnt):
        return gp_Pnt(
            *map(lambda x: _operator(*x), zip(pnt.Coord(), other.Coord())))
    else:
        return gp_Pnt(*map(lambda x: _operator(x, other), pnt.Coord()))
Example #41
0
def make_pnt(args):
    if isinstance(args, gp_Pnt):
        return args
    elif isinstance(args, (list, tuple)):
        return gp_Pnt(*args)
Example #42
0
    def _make_ellipse(self):

        ellipse = gp_Elips(gp_Ax2(gp_Pnt(1, 2, 3), gp_DZ()), 4.0, 2.0)
        return Shape.cast(BRepBuilderAPI_MakeEdge(ellipse).Edge())
Example #43
0
def edge(event=None):
    # The blud edge
    BlueEdge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20),
                                       gp_Pnt(-30, -60, -60))
    V1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30))
    V2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25))
    YellowEdge = BRepBuilderAPI_MakeEdge(V1.Vertex(), V2.Vertex())

    #The white edge
    line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0)))
    WhiteEdge = BRepBuilderAPI_MakeEdge(line, -20, 10)

    #The red edge
    Elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30)
    RedEdge = BRepBuilderAPI_MakeEdge(Elips, 0, math.pi / 2)

    # The green edge and the both extreme vertex
    P1 = gp_Pnt(-15, 200, 10)
    P2 = gp_Pnt(5, 204, 0)
    P3 = gp_Pnt(15, 200, 0)
    P4 = gp_Pnt(-15, 20, 15)
    P5 = gp_Pnt(-5, 20, 0)
    P6 = gp_Pnt(15, 20, 0)
    P7 = gp_Pnt(24, 120, 0)
    P8 = gp_Pnt(-24, 120, 12.5)
    array = TColgp_Array1OfPnt(1, 8)
    array.SetValue(1, P1)
    array.SetValue(2, P2)
    array.SetValue(3, P3)
    array.SetValue(4, P4)
    array.SetValue(5, P5)
    array.SetValue(6, P6)
    array.SetValue(7, P7)
    array.SetValue(8, P8)
    curve = Geom_BezierCurve(array)
    ME = BRepBuilderAPI_MakeEdge(curve.GetHandle())
    GreenEdge = ME
    V3 = ME.Vertex1()
    V4 = ME.Vertex2()

    display.DisplayColoredShape(BlueEdge.Edge(), 'BLUE')
    display.DisplayShape(V1.Vertex())
    display.DisplayShape(V2.Vertex())
    display.DisplayColoredShape(WhiteEdge.Edge(), 'WHITE')
    display.DisplayColoredShape(YellowEdge.Edge(), 'YELLOW')
    display.DisplayColoredShape(RedEdge.Edge(), 'RED')
    display.DisplayColoredShape(GreenEdge.Edge(), 'GREEN')
    display.DisplayShape(V3)
    display.DisplayShape(V4, update=True)
Example #44
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()
    Proxy(trimmed_base).Reverse()  # just a trick
    p0 = Proxy(trimmed_base).StartPoint()
    p1 = Proxy(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:
        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 = Handle_Geom2d_TrimmedCurve.DownCast(
        Proxy(trimmed_base).Copy())
    mirror_profile = Handle_Geom2d_TrimmedCurve.DownCast(
        Proxy(trimmed_profile).Copy())
    mirror_outer = Handle_Geom2d_TrimmedCurve.DownCast(
        Proxy(trimmed_outer).Copy())

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

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

    # Replace the two outer arcs with a single one
    outer_start = Proxy(trimmed_outer).StartPoint()
    outer_mid = Proxy(trimmed_outer).EndPoint()
    outer_end = Proxy(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()
    Proxy(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 = Proxy(mirror_base).EndPoint()
    p5 = Proxy(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 = Proxy(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()
Example #45
0
# siconos <this file>
#

from siconos.mechanics.collision.tools import Contactor, Shape
from siconos.io.mechanics_run import MechanicsHdf5Runner
from OCC.BRepPrimAPI import BRepPrimAPI_MakeCylinder
from OCC.gp import gp_Pnt, gp_Ax2, gp_Dir
import siconos
import siconos.numerics as sn
import siconos.kernel as sk

siconos.io.mechanics_run.set_backend('occ')

# this cylinder is defined for the visualisation of the axis edge
# it may be used for contact also.
axis = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(0, -.05, 0), gp_Dir(0, 1, 0)),
                                .001, .1).Shape()

#
# The slider crank parameters
#

l1 = 0.153  # crank length
l2 = 0.306  # connecting rod length
a = 0.05  # half length of the slider
b = 0.025  # half height of the slider
c = 0.001  # clearance between slider and guide
w10 = -150.  # initial angular speed for the crank
w20 = 75.  # initial angular speed for the connecting rod
w30 = 0.  # initial angular speed for the slider
offset = 0.024  # offset for the contacts between the slider and the chamber
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.

from OCC.gp import gp_Pnt, gp_Dir, gp_Pln
from OCC.Display.SimpleGui import init_display
from OCC.ChFi2d import ChFi2d_AnaFilletAlgo
from OCC.BRepBuilderAPI import BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeWire

from core_geometry_utils import make_wire
display, start_display, add_menu, add_functionto_menu = init_display()

# Defining the points
p1 = gp_Pnt(0, 0, 0)
p2 = gp_Pnt(5, 5, 0)
p3 = gp_Pnt(-5, 5, 0)

# Making the edges
ed1 = BRepBuilderAPI_MakeEdge(p3, p2).Edge()
ed2 = BRepBuilderAPI_MakeEdge(p2, p1).Edge()

#Making the 2dFillet
f = ChFi2d_AnaFilletAlgo()
f.Init(ed1, ed2, gp_Pln())
radius = 1.0
f.Perform(radius)
fillet2d = f.Result(ed1, ed2)

# Create and display a wire
Example #47
0
def n_sided_patch(event=None):

    # left
    pts1 = (
        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 = (
        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 = (
        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 = (
        gp_Pnt(4, 0, 0),
        gp_Pnt(4, 1, 0),
        gp_Pnt(4, 2, 0.3),
        gp_Pnt(4, 3, -0.15),
        gp_Pnt(4, 4, 1),
    )

    spl1 = points_to_bspline(pts1)
    spl2 = points_to_bspline(pts2)
    spl3 = points_to_bspline(pts3)
    spl4 = points_to_bspline(pts4)

    edges = map(make_edge, [spl1, spl2, spl3, spl4])
    verts = map(make_vertex, chain(pts1, pts2, pts3, pts4))
    f1 = make_n_sided(edges, [])

    display.DisplayShape(edges)
    display.DisplayShape(verts)
    display.DisplayShape(f1, update=True)
Example #48
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        '''
        '''
        # 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
        else:
            SOLO = False

        ais_shapes = []

        for shape in shapes:
            if material or texture:
                if texture:
                    self.View.SetSurfaceDetail(OCC.V3d.V3d_TEX_ALL)
                    shape_to_display = OCC.AIS.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 i in ais_shapes:
                shape_to_display.Connect(i)

        # 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
Example #49
0
 def MakeVertex(pt): 
     vt = BRepBuilderAPI.BRepBuilderAPI_MakeVertex(gp.gp_Pnt(*pt))
     #print "make vertex", pt, vt
     return vt
Example #50
0
def proj_vec(pln, p, v):
    p0, p1 = p, gp_Pnt((gp_Vec(p.XYZ()) + v).XYZ())
    p2 = project_point_on_plane(pln, p1)
    v2 = gp_Vec(p0, p2)
    return v2
Example #51
0
    flangePlateWeldL = FilletWeld(h=5, b=5, L=flangePlate.L)
    flangePlateWeldW = FilletWeld(h=5, b=5, L=flangePlate.W)

    innerflangePlateWeldL = FilletWeld(h=5, b=5, L=innerFlangePlate.L)
    innerflangePlateWeldW = FilletWeld(h=5, b=5, L=innerFlangePlate.W)

    webPlateWeldL = FilletWeld(h=5, b=5, L=webPlate.L)
    webPlateWeldW = FilletWeld(h=5, b=5, L=webPlate.W)

    CCSpliceCoverPlateCAD = CCSpliceCoverPlateWeldedCAD(
        column, flangePlate, innerFlangePlate, webPlate, gap, flangePlateWeldL,
        flangePlateWeldW, innerflangePlateWeldL, innerflangePlateWeldW,
        webPlateWeldL, webPlateWeldW)

    CCSpliceCoverPlateCAD.create_3DModel()
    column = CCSpliceCoverPlateCAD.get_column_models()
    plates = CCSpliceCoverPlateCAD.get_plate_models()
    welds = CCSpliceCoverPlateCAD.get_welded_modules()

    Point = gp_Pnt(0.0, 0.0, 0.0)
    display.DisplayMessage(Point, "Origin")

    # display.View.Rotate(45, 90, 45)
    display.DisplayShape(column, update=True)
    display.DisplayShape(plates, color='BLUE', update=True)
    display.DisplayShape(welds, color='RED', update=True)

    display.DisableAntiAliasing()
    start_display()
#!/usr/bin/python
# coding: utf-8
r"""test_revolve.py"
"""

from math import pi

from OCC import BRepPrimAPI, gp, BRepBuilderAPI
from viewer import view

el = gp.gp_Elips(gp.gp_Ax2(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(1, 0, 0)), 20.0, 10.0)
edge1 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(el, gp.gp_Pnt(0, 0, 20),
                                               gp.gp_Pnt(0, 0, -20))
edge2 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(gp.gp_Pnt(0, 0, -20),
                                               gp.gp_Pnt(0, 0, 20))

wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire()
wire.Add(edge1.Edge())
wire.Add(edge2.Edge())

face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire())

el = BRepPrimAPI.BRepPrimAPI_MakeRevol(
    face.Shape(), gp.gp_Ax1(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, 1)), pi * 2)

# h_curve = Geom.Handle_Geom_Ellipse(curve)
# rev = BRepPrimAPI.BRepPrimAPI_MakeRevolution(h_curve, 120.1)
# #nurbs = BRepBuilderAPI.BRepBuilderAPI_NurbsConvert(rev.Shape())
view(el.Shape())
Example #53
0
def test_iges_exporter_adding_not_a_shape(box_shape):
    r"""Adding something to the exporter that is not a TopoDS_Shape or a subclass"""
    filename = path_from_file(__file__, "./models_out/box.igs")
    exporter = IgesExporter(filename)
    with pytest.raises(ValueError):
        exporter.add_shape(gp.gp_Pnt(1, 1, 1))
Example #54
0
    def _make_circle(self):

        circle = gp_Circ(gp_Ax2(gp_Pnt(1, 2, 3), gp_DZ()), 2.)
        return Shape.cast(BRepBuilderAPI_MakeEdge(circle).Edge())
Example #55
0
#import mechanics_run
#mechanics_run.set_backend('occ')
import siconos.io.mechanics_run

siconos.io.mechanics_run.set_backend('occ')
import numpy as np
import math

# create sphere
radius = 1.0
# The sphere center
X1 = 0.0
Y1 = 0.0
Z1 = 0.0
# create OCC.gp.gp_Pnt-Point from vector
point = gp_Pnt(X1, Y1, Z1)
sphere_r1 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r1_shape = sphere_r1.Shape()

radius = 0.01
sphere_r01 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r01_shape = sphere_r01.Shape()

radius = 0.001
sphere_r001 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r001_shape = sphere_r001.Shape()

from OCC.BRep import BRep_Builder
from OCC.TopoDS import TopoDS_Compound

builder = BRep_Builder()
Example #56
0
 def testVertices(self):
     e = Shape.cast(
         BRepBuilderAPI_MakeEdge(gp_Pnt(0, 0, 0), gp_Pnt(1, 1, 0)).Edge())
     self.assertEqual(2, len(e.Vertices()))
Example #57
0
 reader.TransferRoots()
 shape = reader.OneShape()
 
 # Get bounding box
 xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(shape)
 
 # Build section plane
 XYZ = (1, 0, 1)
 lim_coord1 = (xmin, xmax)
 lim_coord2 = (zmin, zmax)
 
 section_width = ymin + 1e-3
 # A horizontal plane is created from which a face is constructed to intersect with 
 # the building. The face is transparently displayed along with the building.    
 section_plane = gp_Pln(
     gp_Pnt(xmax+xmin, section_width, 0.0),
     gp_Dir(0, 1, 0)
 )
 
 # Explore the faces of the shape (these are known to be named)
 exp = TopExp_Explorer(shape, TopAbs_FACE)
 while exp.More():
     s = exp.Current()
     
     tp = Topo(s)
     for face in tp.faces():
         for edge in list(Topo(face).edges()):
             
             obj = EdgeOnSurface(edge, section_plane, lim_coord2, lim_coord1, XYZ)
             objects.add(obj)
             
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.

from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeSphere
from OCC.Display.SimpleGui import init_display
from OCC.gp import gp_Vec, gp_Pnt

from core_geometry_utils import translate_shp

display, start_display, add_menu, add_function_to_menu = init_display()

# Create Box
box = BRepPrimAPI_MakeBox(200, 60, 60).Shape()
# Create Sphere
sphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape()
# move the sphere
moved_sphere = translate_shp(sphere, gp_Vec(0., -200., 0.))

ais_box = display.DisplayShape(box)
display.Context.SetTransparency(ais_box, 0.1)
ais_sphere = display.DisplayColoredShape(moved_sphere, color="BLUE")
display.Context.SetTransparency(ais_sphere, 0.9)
display.FitAll()
start_display()
Example #59
0
def round_tooth(wedge):
    round_x = 2.6
    round_z = 0.06 * pitch
    round_radius = pitch

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

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

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

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

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

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

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

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

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

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

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

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

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

    return cut_2
Example #60
0
if __name__ == '__main__':
    argvs = sys.argv
    parser = OptionParser()
    parser.add_option("--px", dest="px", default=0.0, type="float")
    parser.add_option("--dx", dest="dx", default=0.0, type="float")
    parser.add_option("--py", dest="py", default=0.0, type="float")
    parser.add_option("--dy", dest="dy", default=0.0, type="float")
    opt, argc = parser.parse_args(argvs)

    ax, pln = def_ax(0, 0, 0, lx=100, ly=100)
    m1_ax, m1_pln = def_ax(0, 0, 470, dx=-45)
    m2_ax, m2_pln = def_ax(0, -250, 470, dx=45, dy=180)
    wg_ax, wg_pln = def_ax(0, -250, 470 + 360, lx=100, ly=100, dy=0)

    ax0 = gp_Ax3(gp_Pnt(opt.px, opt.py, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0))
    rot_axs(ax0, gp_Ax1(ax0.Location(), ax0.XDirection()), opt.dx)
    rot_axs(ax0, gp_Ax1(ax0.Location(), ax0.YDirection()), opt.dy)
    pnt = ax0.Location()
    vec = dir_to_vec(ax0.Direction())

    m1_pnt, m1_vec = reflect(pnt, vec, m1_ax)
    m2_pnt, m2_vec = reflect(m1_pnt, m1_vec, m2_ax)
    wg_pnt, wg_vec = reflect(m2_pnt, m2_vec, wg_ax)
    wg_vec.Reverse()
    wg_p = wg_ax.Location()
    print(np.rad2deg(get_angle(wg_ax, wg_vec, dir_to_vec(wg_ax.Direction()))))
    print(wg_pnt.X() - wg_p.X(), wg_pnt.Y() - wg_p.Y())
    """
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.DisplayShape (pnt)