def points_from_intersection(event=None):
    '''
    @param display:
    '''
    plane = gp_Pln(gp_Ax3(gp_XOY()))
    minor_radius, major_radius = 5., 8.
    ellips = gp_Elips(gp_YOZ(), major_radius, minor_radius)
    intersection = IntAna_IntConicQuad(ellips,
                                       plane,
                                       precision_Angular(),
                                       precision_Confusion())
    a_plane = GC_MakePlane(plane).Value()
    a_surface = Geom_RectangularTrimmedSurface(a_plane, - 8., 8., - 12., 12.,
                                               True, True)
    display.DisplayShape(a_surface, update=True)

    anEllips = GC_MakeEllipse(ellips).Value()
    display.DisplayShape(anEllips)

    if intersection.IsDone():
        nb_results = intersection.NbPoints()
        if nb_results > 0:
            for i in range(1, nb_results + 1):
                P = intersection.Point(i)
                pstring = "P%i" % i
                display.DisplayShape(P)
                display.DisplayMessage(P, pstring)
def slicer(event=None):
    # Param
    Zmin, Zmax, deltaZ = -100, 100, 5
    # Note: the shape can also come from a shape selected from InteractiveViewer
    if 'display' in dir():
        shape = display.GetSelectedShape()
    else:
        # Create the shape to slice
        shape = BRepPrimAPI_MakeSphere(60.).Shape()
    # Define the direction
    D = gp_Dir(0., 0., 1.)  # the z direction
    # Perform slice
    sections = []
    init_time = time.time()  # for total time computation
    for z in range(Zmin, Zmax, deltaZ):
        # Create Plane defined by a point and the perpendicular direction
        P = gp_Pnt(0, 0, z)
        Pln = gp_Pln(P, D)
        face = BRepBuilderAPI_MakeFace(Pln).Shape()
        # Computes Shape/Plane intersection
        section = BRepAlgoAPI_Section(shape, face)
        if section.IsDone():
            sections.append(section)
    total_time = time.time() - init_time
    print("%.3fs necessary to perform slice." % total_time)

    display.EraseAll()
    display.DisplayShape(shape)
    for section in sections:
        display.DisplayShape(section.Shape())
    display.FitAll()
Beispiel #3
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 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
Beispiel #5
0
def get2dCurveFrom3dEdge(edge):
    """
		returns a curve given an edge.
		here, we want to get a curve from a 3dEdge, since with this approach we'll only be getting existing
		curves from a 3d source
	"""
    # first, convert the curve to a 2d curve
    btool = BRep.BRep_Tool()
    handleCurve = btool.Curve(edge)[0]
    return GeomAPI.GeomAPI().To2d(handleCurve, gp.gp_Pln(gp.gp_Pnt(0, 0, 0), gp.gp().DZ()))
Beispiel #6
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 test_deprecation_warning(self):
     """ since pythonocc-0.18.2. import OCC.* changed to import OCC.Core.*
     Such deprecated import raises a DeprecatedWarning
     """
     with assert_warns_deprecated():
         from OCC.gp import gp_Pln
         # create a gp_Pln object to avoid
         # codacy and other static analysis tools
         # to report the gp_Pln class is unused
         # though it's not very elegant !
         self.assertIsInstance(gp_Pln(), gp_Pln)
Beispiel #8
0
    def _computeSlice(self, zLevel, layerNo, fillAngle):

        cSlice = Slice()
        cSlice.zLevel = zLevel
        cSlice.layerNo = layerNo
        cSlice.fillAngle = fillAngle
        cSlice.thickness = self.options.layerHeight

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

        csys = gp.gp_Ax3(p, gp.gp().DZ())
        cuttingPlane = gp.gp_Pln(csys)

        # makeSection will use the old reliable way that will get a face from each cut.
        # makeSection2 will use BRepAlgoaPI_Section, but has problems ordering the edges correctly.
        newFaces = self.makeSection(cuttingPlane, self.solid.shape, zLevel)
        for f in newFaces:
            cSlice.addFace(Face(f))
        # 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(self.solid.shape,halfspace);
        # cutShape = bc.Shape();

        # for face in Topo(cutShape).faces():
        #    if OCCUtil.isFaceAtZLevel(zLevel,face):
        #        cSlice.addFace(Face(face));
        #        break;

        mySum = cSlice.computeFingerPrint()

        #
        # uncomment to enable layer copying.
        #
        # check for identical slices. return matching ones if found.
        if self.sliceMap.has_key(mySum):
            # print "i can copy this layer!"
            return self.sliceMap[mySum].copyToZ(zLevel, layerNo)

        self.sliceMap[mySum] = cSlice
        # print "This slice has %d faces." % len(cSlice.faces)

        if self.options.fillingEnabled:
            self._fillSlice(cSlice)

        return cSlice
def faircurve(event=None):
    pt1 = gp_Pnt2d(0.0, 0.0)
    pt2 = gp_Pnt2d(0.0, 120.0)
    height = 100.0
    pl = Geom_Plane(gp_Pln())
    for i in range(0, 40):
        # TODO: the parameter slope needs to be visualized
        slope = i / 100.0
        bc = batten_curve(pt1, pt2, height, slope, math.radians(i), math.radians(-i))
        display.EraseAll()
        edge = BRepBuilderAPI_MakeEdge(bc, pl.GetHandle()).Edge()
        display.DisplayShape(edge, update=True)
        time.sleep(0.21)
Beispiel #10
0
def faircurve(event=None):
    pt1 = gp_Pnt2d(0., 0.)
    pt2 = gp_Pnt2d(0., 120.)
    height = 100.
    slope = 0.3
    pl = Geom_Plane(gp_Pln())
    for i in range(0, 40):
        # TODO: the parameter slope needs to be visualized
        bc = batten_curve(pt1, pt2, height, i/100.,
                          math.radians(i), math.radians(-i))
        display.EraseAll()
        display.DisplayShape(make_edge(bc, pl.GetHandle()), update=True)
        time.sleep(0.21)
def draft_angle(event=None):
    S = BRepPrimAPI_MakeBox(200., 300., 150.).Shape()
    adraft = BRepOffsetAPI_DraftAngle(S)
    topExp = TopExp_Explorer()
    topExp.Init(S, TopAbs_FACE)
    while topExp.More():
        face = topods_Face(topExp.Current())
        surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(face)).GetObject()
        dirf = surf.Pln().Axis().Direction()
        ddd = gp_Dir(0, 0, 1)
        if dirf.IsNormal(ddd, precision_Angular()):
            adraft.Add(face, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY())))
        topExp.Next()
    adraft.Build()
    display.DisplayShape(adraft.Shape(), update=True)
def vectorized_slicer(li):
    # Create Plane defined by a point and the perpendicular direction
    z_values, shape = li
    _slices = []
    for z in z_values:
        #print 'slicing index:', z, 'sliced by process:', os.getpid()
        plane = gp_Pln(gp_Pnt(0., 0., z), gp_Dir(0., 0., 1.))
        face = BRepBuilderAPI_MakeFace(plane).Shape()
        # Computes Shape/Plane intersection
        section = BRepAlgoAPI_Section(shape, face)
        section.Build()
        if section.IsDone():
            _slices.append(section.Shape())
        section.Destroy()
    return _slices
Beispiel #13
0
	def _makeSlice(self,shapeToSlice,zLevel):
		s = Slice();
		
		#change if layers are variable thickness
		s.sliceHeight = self.sliceHeight;		
		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();
		
		#search the shape for faces at the specified zlevel
		texp = TopExp.TopExp_Explorer();
		texp.Init(cutShape,TopAbs.TopAbs_FACE);
		foundFace = False;
		while ( texp.More() ):
			face = ts.Face(texp.Current());
			if self._isAtZLevel(zLevel,face):
				foundFace = True;
				logging.debug( "Face is at zlevel" + str(zLevel) );
				s.addFace(face,self.saveSliceFaces);
			texp.Next();
		
		#free memory
		face.Nullify();
		bc.Destroy();
		texp.Clear();
		texp.Destroy();
			
		if not foundFace:
			logging.warn("No faces found after slicing at zLevel " + str(zLevel) + " !. Skipping This layer completely");
			return None;
		else:				
			return s;		
Beispiel #14
0
def make_plane(center=gp_Pnt(0, 0, 0),
               vec_normal=gp_Vec(0, 0, 1),
               extent_x_min=-100.,
               extent_x_max=100.,
               extent_y_min=-100.,
               extent_y_max=100.,
               depth=0.):
    if depth != 0:
        center = center.add_vec(gp_Vec(0, 0, depth))
    PL = gp_Pln(center, vec_normal.as_dir())
    face = make_face(PL,
                     extent_x_min,
                     extent_x_max,
                     extent_y_min,
                     extent_y_max)
    return face
def split_shape(event=None):
    S = BRepPrimAPI_MakeBox(gp_Pnt(-100, -60, -80), 150, 200, 170).Shape()
    asect = BRepAlgoAPI_Section(S, gp_Pln(1, 2, 1, -15), False)
    asect.ComputePCurveOn1(True)
    asect.Approximation(True)
    asect.Build()
    R = asect.Shape()

    asplit = BRepFeat_SplitShape(S)

    for edg in Topo(R).edges():
        face = TopoDS_Face()
        if asect.HasAncestorFaceOn1(edg, face):
            asplit.Add(edg, face)

    asplit.Build()
    display.EraseAll()
    display.DisplayShape(asplit.Shape())
    display.FitAll()
Beispiel #16
0
    def make_shape(self):
        # 1 - retrieve the data from the UIUC airfoil data page
        foil_dat_url = 'http://www.ae.illinois.edu/m-selig/ads/coord_seligFmt/%s.dat' % self.profile
        f = urllib2.urlopen(foil_dat_url)
 
        plan = gp_Pln(gp_Pnt(0,0,0), gp_Dir(0,0,1)) # Z=0 plan / XY plan
        section_pts_2d=[]
 
        for line in f.readlines()[1:]: # The first line contains info only
            # 2 - do some cleanup on the data (mostly dealing with spaces)
            line = line.lstrip().rstrip().replace('    ',' ').replace('   ',' ').replace('  ',' ')
            data = line.split(' ') # data[0] = x coord.    data[1] = y coord.
 
            # 3 - create an array of points
            if len(data)==2: # two coordinates for each point
                section_pts_2d.append(gp_Pnt2d(float(data[0])*self.chord,
                                               float(data[1])*self.chord))
 
        # 4 - use the array to create a spline describing the airfoil section
        spline_2d = Geom2dAPI_PointsToBSpline(point2d_list_to_TColgp_Array1OfPnt2d(section_pts_2d),
                                              len(section_pts_2d)-1, # order min
                                              len(section_pts_2d))   # order max
        spline = GeomAPI_To3d(spline_2d.Curve(),plan)
 
        # 5 - figure out if the trailing edge has a thickness or not, and create a Face
        try:
            #first and last point of spline -> trailing edge
            trailing_edge = make_edge(gp_Pnt(section_pts_2d[0].X(),  section_pts_2d[0].Y() ,0.0),
                                      gp_Pnt(section_pts_2d[-1].X(), section_pts_2d[-1].Y(),0.0))
 
            face = BRepBuilderAPI_MakeFace(make_wire([make_edge(spline),trailing_edge]))
 
        except AssertionError:
            # the trailing edge segment could not be created, probably because the points are too close
            # No need to build a trailing edge
            face = BRepBuilderAPI_MakeFace(make_wire(make_edge(spline)))
 
        # 6 - extrude the Face to create a Solid
        return BRepPrimAPI_MakePrism(face.Face(),
                                     gp_Vec(gp_Pnt(0,0,0),
                                     gp_Pnt(0,0,self.span))).Shape()
 def create_section_plane(self, section_distance):
     crv = self.canvas.get_path_curve()[0]
     display = self.canvas.get_display()
     if crv is not None:
         self.is_show_plane = True
         div_crv_param = divide_curve(crv, section_distance)
         self.clear_crv_sections()
         for i in div_crv_param:
             pt = crv.Value(i)
             pt_vec = crv.DN(i, 1)
             pt_sec_plane = gp_Pln(pt, gp_Dir(pt_vec))
             size = self.section_plane_size
             section_face = BRepBuilderAPI_MakeFace(pt_sec_plane, -size, size, -size, size).Face()
             section_face_display = display.DisplayShape(section_face, transparency=0.99, color=255)
             bounding_box = Bnd_Box()
             brepbndlib_Add(section_face, bounding_box)
             self.section_planes.append((i, section_face, section_face_display, pt_sec_plane, bounding_box))
         display.Repaint()
         return True
     else:
         return False
def split_shape(event=None):
    """
    Example of spliting shape
    """
    display, start_display, add_menu, add_function_to_menu = init_display()

    S = BRepPrimAPI_MakeBox(gp_Pnt(-100, -60, -80), 150, 200, 170).Shape()
    asect = BRepAlgoAPI_Section(S, gp_Pln(1, 2, 1, -15), False)
    asect.ComputePCurveOn1(True)
    asect.Approximation(True)
    asect.Build()
    R = asect.Shape()

    asplit = BRepFeat_SplitShape(S)

    wire1 = BRepBuilderAPI_MakeWire()

    i = 0
    for edg in Topo(R).edges():
        print(edg)
        face = TopoDS_Face()
        if asect.HasAncestorFaceOn1(edg, face):
            print('Adding edge on face and wire: ', face, i)
            asplit.Add(edg, face)
            # Add edge to wire
            if i > 0:
                wire1.Add(edg)
        i += 1
    asplit.Build()
    wire1.Build()

    display.EraseAll()
    display.DisplayShape(asplit.Shape())
    display.DisplayShape(wire1.Shape(), color='blue')
    # display.FitAll()

    start_display()

    breptools_Write(asplit.Shape(), "split1.brep")
    def BuildFuselageOML(self, Max_attempt=5):
        """Builds the Fuselage outer mould line
        Notes
        -----
        It is not expected that users will interact with this directly. Use
        the Fuslage class initialisation fuction instead
        """
        NetworkSrfSettings = np.array([[35, 20, 15, 15, 20],
                                       [35, 30, 15, 5, 20],
                                       [35, 20, 15, 2, 20],
                                       [30, 30, 15, 2, 20],
                                       [30, 20, 15, 2, 20],
                                       [25, 20, 15, 2, 20],
                                       [20, 20, 15, 2, 20],
                                       [15, 20, 15, 2, 20]])
        HStarboardCurve, HPortCurve, FSVUCurve, FSVLCurve, FSVMeanCurve, \
            NoseEndX, TailStartX, EndX =                               \
            self.FuselageLongitudinalGuideCurves(self.NoseLengthRatio,
                                                  self.TailLengthRatio)
        
        # Returning the PortCurve and StarboardCurve as Geom_BSplineCurve
        # makes kernel freeze in pythonocc 0.16.5, so needed to carry around a
        # handle instead - very strange bug!
        PortCurve = HPortCurve .GetObject()
        StarboardCurve = HStarboardCurve.GetObject()
        
        # Compute the stern point coordinates of the fuselage
        Pu = FSVUCurve.EndPoint()
        Pl = FSVLCurve.EndPoint()
        self.SternPoint = gp_Pnt(Pu.X(), Pu.Y(), 0.5*(Pu.Z()+Pl.Z()))
        Pu = FSVUCurve.StartPoint()
        Pl = FSVLCurve.StartPoint()
        self.BowPoint = gp_Pnt(Pu.X(), Pu.Y(), 0.5*(Pu.Z()+Pl.Z()))

        i_attempt = 0
        while i_attempt < Max_attempt:
            i_attempt = i_attempt + 1
            print("Surface fit attempt {}".format(i_attempt))

            # Construct array of cross section definition frames
            SX0 = 0
            SX1 = 0.04 * NoseEndX
            SX2 = SX1 + 0.25 * NoseEndX
            SX3 = NoseEndX
            SX4 = TailStartX
            SX5 = EndX

            Step01, Step12, Step23, Step34, Step45 = \
                NetworkSrfSettings[i_attempt - 1]

            print("""Attempting loft surface fit with network density
                setup {}""".format(NetworkSrfSettings[i_attempt][:]))
            Stations01 = np.linspace(SX0, SX1, max([Step01, 2]))
            Stations12 = np.linspace(SX1, SX2, max([Step12, 2]))
            Stations23 = np.linspace(SX2, SX3, max([Step23, 2]))
            Stations34 = np.linspace(SX3, SX4, max([Step34, 2]))
            Stations45 = np.linspace(SX4, SX5, max([Step45, 2]))

            StationRange = np.hstack([Stations01[:-1], Stations12[:-1],
                                     Stations23[:-1], Stations34[:-1],
                                     Stations45])
            C = []
            FirstTime = True

            for i, XStation in enumerate(StationRange[1:]):
                # Create plane normal to x direction
                P = Geom_Plane(gp_Pln(gp_Pnt(XStation, 0, 0),
                                      gp_Dir(gp_Vec(1, 0, 0))))
                # Make into a face for visualisation/debugging
                try:
                    IPoint2 = act.points_from_intersection(P, FSVUCurve)
                    IPoint3 = act.points_from_intersection(P, PortCurve)
                    IPoint4 = act.points_from_intersection(P, FSVLCurve)
                    IPoint1 = act.points_from_intersection(P, StarboardCurve)
#
                    IPointCentre = act.points_from_intersection(P,
                                                                FSVMeanCurve)
                except RuntimeError:
                    print("Intersection Points at Section X={} Not Found"
                          .format(XStation))
                    print("Skipping this plane location")
                    continue

                PseudoDiameter = abs(IPoint4.Z()-IPoint2.Z())
                if self.CylindricalMidSection and\
                        NoseEndX < XStation < TailStartX:
                    print("Enforcing circularity in the central section...")
                    if FirstTime:
                        PseudoRadius = PseudoDiameter / 2.
                        FirstTime = False
                    PseudoRadius = PseudoDiameter / 2.
                    # Note: Add Circle with radius PseudoRadius at Pc
                    from OCC.GC import GC_MakeCircle
                    c = GC_MakeCircle(gp_Ax2(IPointCentre, gp_Dir(1, 0, 0)),
                                      PseudoRadius).Value()

                else:
                    # Set the tangents at each point for interpolation:
                    # assume that these are solely in 1 axis as points lie
                    # extremities of an elliptical shape
                    tangents = np.array([[0, -1,  0],
                                         [0,  0, -1],
                                         [0,  1,  0],
                                         [0,  0,  1]])
                    c = act.points_to_bspline(
                        [IPoint2, IPoint3, IPoint4, IPoint1],
                        periodic=True, scale=False,
                        tangents=tangents)

                C.append(c)

#             Fit fuselage external surface
            sections = [act.make_wire(act.make_edge(curve)) for curve in C]
            guides = ([FSVUCurve.GetHandle(), PortCurve.GetHandle(),
                       FSVLCurve.GetHandle(), StarboardCurve.GetHandle()])
            guides = [act.make_wire(act.make_edge(guide)) for guide in guides]
            self._Lguides = guides
            self._Csections = sections
            self._NoseVertex = act.make_vertex(self.BowPoint)
            try:
                OMLSurf = \
                    act.AddSurfaceLoft(C, first_vertex=self._NoseVertex,
                                       continuity=GeomAbs_C2, solid=False)
            except:
                OMLSurf = None

            if OMLSurf is not None:
                print("Network surface fit succesful on attempt {}\n"
                      .format(i_attempt))
                self.AddComponent(OMLSurf, 'OML')
                return None

#         If all attempts at fitting a network surface failed, we attempt a
#            Pipe Shell:
        if OMLSurf is None:
            print("""Failed to fit network surface to the external shape of the
                fuselage""")
            print("""Attempting alternative fitting method, quality likely to
                be low...""")

            try:
                OMLSurf = act.make_pipe_shell(C)
                self.AddComponent(OMLSurf, 'OML')
            except:
                raise(RuntimeError, "Could not produce a valid OML surface")

#    Note: The following is the last resort surface fit from Rhino Airconics
#                And currently is not available in OCC Airconics:

#            SimplificationReqd = True # Enforce simplification
#            if not(FuselageOMLSurf):
#                print "Alternative fitting method failed too. Out of ideas."
#
#        if FuselageOMLSurf and SimplificationReqd:
#            rs.UnselectAllObjects()
#            rs.SelectObject(FuselageOMLSurf)
#            ToleranceStr = str(0.0005*EndX)
#            print "Smoothing..."
#            rs.Command("FitSrf " + ToleranceStr)
#            rs.UnselectAllObjects()
#

        # Shouldnt get here
        return None
Beispiel #20
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
Beispiel #21
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
Beispiel #22
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)
             
     exp.Next()
Beispiel #23
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:
        sys.exit(-1)

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

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

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

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

    mirror_base = 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()
from OCC.gp import gp_Pnt,gp_Dir,gp_Pln
from OCC.ChFi2d import ChFi2d_AnaFilletAlgo
from OCC.BRepBuilderAPI import BRepBuilderAPI_MakeEdge,BRepBuilderAPI_MakeWire

from OCC.Extend.ShapeFactory import make_wire

from OCC.Display.SimpleGui import init_display
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
w = make_wire([ed1, fillet2d, ed2])
display.DisplayShape(w)
start_display()
Beispiel #25
0
    shape = reader.OneShape()
#    ifcopenshell.geom.utils.display_shape(shape)
    
    # 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
    # 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()
#    ifcopenshell.geom.utils.display_shape(section_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()
        
def find_closest_normal_pair(solid_add,
                             solid_base=None,
                             negelet_parallelPair=False,
                             ang_tol=0.5,
                             xyplane_z=0.0):
    """[summary]
    # [ToDo] sort by angle difference
    Return the direction pairs with least difference of orientation of normal.
    If solid_base is not given, then take the default XY, YZ, ZX planes


    Arguments:
        solid_add {topoDS_shape} -- the solid to be assembled on solid_base
        solid_base {topoDS_shape} -- the solid which the solid_add assembled on

    Keyword Arguments:
        ang_tol [deg] {float} -- the angle between the normal of planes within ang_tol [deg] will be considered as the same pair. (default: {0.5})

    Returns:
        {dictionary} -- 'minVal': {float} [deg] minimal angle between normals of planes
                        'minDirPair': {tuple of float} direction of normal
    """
    # should consider Z axis first?
    if solid_base is None:
        normal_base_withPlanes = None
    else:
        normal_base_withPlanes = group_planes_by_axis(solid_base)
    normal_add_withPlanes = group_planes_by_axis(solid_add)

    # if normal_base_withPlanes is None:
    #     plnXY = gp_Pln(gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)))
    #     plnYZ = gp_Pln(gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(1.0, 0.0, 0.0)))
    #     plnZX = gp_Pln(gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 1.0, 0.0)))
    #     normal_base_withPlanes = {(0, 0, 1): [BRepBuilderAPI_MakeFace(plnXY).Face()],
    #                               (1, 0, 0): [BRepBuilderAPI_MakeFace(plnYZ).Face()],
    #                               (0, 1, 0): [BRepBuilderAPI_MakeFace(plnZX).Face()]}
    if normal_base_withPlanes is None:
        plnXY = gp_Pln(
            gp_Ax3(gp_Pnt(0.0, 0.0, xyplane_z), gp_Dir(0.0, 0.0, 1.0)))
        normal_base_withPlanes = {
            (0, 0, 1): [BRepBuilderAPI_MakeFace(plnXY).Face()]
        }
    normals_base = normal_base_withPlanes.keys()
    normals_add = normal_add_withPlanes.keys()
    minPair = {'minVal': 90.0, 'minGpDirPair': [], 'minAxisKeyPair': []}

    for normal_base in normals_base:
        dir_base = gp_Dir(normal_base[0], normal_base[1], normal_base[2])
        for normal_add in normals_add:
            dir_add = gp_Dir(normal_add[0], normal_add[1], normal_add[2])
            ang = degrees(dir_base.Angle(dir_add))
            complementary_angle = 180.0 - ang
            min_ang = min(ang, complementary_angle)
            if negelet_parallelPair and min_ang <= ang_tol / 10:
                logging.debug('neglet parallel planes')
                continue

            if abs(min_ang - minPair['minVal']) <= ang_tol:
                minPair['minGpDirPair'].append([dir_base, dir_add])
                minPair['minAxisKeyPair'].append([normal_base, normal_add])

            else:
                if minPair['minVal'] - min_ang >= ang_tol:
                    minPair['minGpDirPair'] = [[dir_base, dir_add]]
                    minPair['minAxisKeyPair'] = [[normal_base, normal_add]]
                    minPair['minVal'] = min_ang
    return minPair
Beispiel #27
0
    def BuildFuselageOML(self, Max_attempt=5):
        """Builds the Fuselage outer mould line
        Notes
        -----
        It is not expected that users will interact with this directly. Use
        the Fuslage class initialisation fuction instead
        """
        NetworkSrfSettings = np.array([[35, 20, 15, 15,
                                        20], [35, 30, 15, 5, 20],
                                       [35, 20, 15, 2,
                                        20], [30, 30, 15, 2, 20],
                                       [30, 20, 15, 2,
                                        20], [25, 20, 15, 2, 20],
                                       [20, 20, 15, 2, 20],
                                       [15, 20, 15, 2, 20]])
        HStarboardCurve, HPortCurve, FSVUCurve, FSVLCurve, FSVMeanCurve, \
            NoseEndX, TailStartX, EndX =                               \
            self.FuselageLongitudinalGuideCurves(self.NoseLengthRatio,
                                                  self.TailLengthRatio)

        # Returning the PortCurve and StarboardCurve as Geom_BSplineCurve
        # makes kernel freeze in pythonocc 0.16.5, so needed to carry around a
        # handle instead - very strange bug!
        PortCurve = HPortCurve.GetObject()
        StarboardCurve = HStarboardCurve.GetObject()

        # Compute the stern point coordinates of the fuselage
        Pu = FSVUCurve.EndPoint()
        Pl = FSVLCurve.EndPoint()
        self.SternPoint = gp_Pnt(Pu.X(), Pu.Y(), 0.5 * (Pu.Z() + Pl.Z()))
        Pu = FSVUCurve.StartPoint()
        Pl = FSVLCurve.StartPoint()
        self.BowPoint = gp_Pnt(Pu.X(), Pu.Y(), 0.5 * (Pu.Z() + Pl.Z()))

        i_attempt = 0
        while i_attempt < Max_attempt:
            i_attempt = i_attempt + 1
            print("Surface fit attempt {}".format(i_attempt))

            # Construct array of cross section definition frames
            SX0 = 0
            SX1 = 0.04 * NoseEndX
            SX2 = SX1 + 0.25 * NoseEndX
            SX3 = NoseEndX
            SX4 = TailStartX
            SX5 = EndX

            Step01, Step12, Step23, Step34, Step45 = \
                NetworkSrfSettings[i_attempt - 1]

            print("""Attempting loft surface fit with network density
                setup {}""".format(NetworkSrfSettings[i_attempt][:]))
            Stations01 = np.linspace(SX0, SX1, max([Step01, 2]))
            Stations12 = np.linspace(SX1, SX2, max([Step12, 2]))
            Stations23 = np.linspace(SX2, SX3, max([Step23, 2]))
            Stations34 = np.linspace(SX3, SX4, max([Step34, 2]))
            Stations45 = np.linspace(SX4, SX5, max([Step45, 2]))

            StationRange = np.hstack([
                Stations01[:-1], Stations12[:-1], Stations23[:-1],
                Stations34[:-1], Stations45
            ])
            C = []
            FirstTime = True

            for i, XStation in enumerate(StationRange[1:]):
                # Create plane normal to x direction
                P = Geom_Plane(
                    gp_Pln(gp_Pnt(XStation, 0, 0), gp_Dir(gp_Vec(1, 0, 0))))
                # Make into a face for visualisation/debugging
                try:
                    IPoint2 = act.points_from_intersection(P, FSVUCurve)
                    IPoint3 = act.points_from_intersection(P, PortCurve)
                    IPoint4 = act.points_from_intersection(P, FSVLCurve)
                    IPoint1 = act.points_from_intersection(P, StarboardCurve)
                    #
                    IPointCentre = act.points_from_intersection(
                        P, FSVMeanCurve)
                except RuntimeError:
                    print(
                        "Intersection Points at Section X={} Not Found".format(
                            XStation))
                    print("Skipping this plane location")
                    continue

                PseudoDiameter = abs(IPoint4.Z() - IPoint2.Z())
                if self.CylindricalMidSection and\
                        NoseEndX < XStation < TailStartX:
                    print("Enforcing circularity in the central section...")
                    if FirstTime:
                        PseudoRadius = PseudoDiameter / 2.
                        FirstTime = False
                    PseudoRadius = PseudoDiameter / 2.
                    # Note: Add Circle with radius PseudoRadius at Pc
                    from OCC.GC import GC_MakeCircle
                    c = GC_MakeCircle(gp_Ax2(IPointCentre, gp_Dir(1, 0, 0)),
                                      PseudoRadius).Value()

                else:
                    # Set the tangents at each point for interpolation:
                    # assume that these are solely in 1 axis as points lie
                    # extremities of an elliptical shape
                    tangents = np.array([[0, -1, 0], [0, 0, -1], [0, 1, 0],
                                         [0, 0, 1]])
                    c = act.points_to_bspline(
                        [IPoint2, IPoint3, IPoint4, IPoint1],
                        periodic=True,
                        scale=False,
                        tangents=tangents)

                C.append(c)

#             Fit fuselage external surface
            sections = [act.make_wire(act.make_edge(curve)) for curve in C]
            guides = ([
                FSVUCurve.GetHandle(),
                PortCurve.GetHandle(),
                FSVLCurve.GetHandle(),
                StarboardCurve.GetHandle()
            ])
            guides = [act.make_wire(act.make_edge(guide)) for guide in guides]
            self._Lguides = guides
            self._Csections = sections
            self._NoseVertex = act.make_vertex(self.BowPoint)
            try:
                OMLSurf = \
                    act.AddSurfaceLoft(C, first_vertex=self._NoseVertex,
                                       continuity=GeomAbs_C2, solid=False)
            except:
                OMLSurf = None

            if OMLSurf is not None:
                print("Network surface fit succesful on attempt {}\n".format(
                    i_attempt))
                self.AddComponent(OMLSurf, 'OML')
                return None

#         If all attempts at fitting a network surface failed, we attempt a
#            Pipe Shell:
        if OMLSurf is None:
            print("""Failed to fit network surface to the external shape of the
                fuselage""")
            print("""Attempting alternative fitting method, quality likely to
                be low...""")

            try:
                OMLSurf = act.make_pipe_shell(C)
                self.AddComponent(OMLSurf, 'OML')
            except:
                raise (RuntimeError, "Could not produce a valid OML surface")

#    Note: The following is the last resort surface fit from Rhino Airconics
#                And currently is not available in OCC Airconics:

#            SimplificationReqd = True # Enforce simplification
#            if not(FuselageOMLSurf):
#                print "Alternative fitting method failed too. Out of ideas."
#
#        if FuselageOMLSurf and SimplificationReqd:
#            rs.UnselectAllObjects()
#            rs.SelectObject(FuselageOMLSurf)
#            ToleranceStr = str(0.0005*EndX)
#            print "Smoothing..."
#            rs.Command("FitSrf " + ToleranceStr)
#            rs.UnselectAllObjects()
#

# Shouldnt get here
        return None
def filletEdges(ed1, ed2):
    radius = 0.3
    f = ChFi2d_AnaFilletAlgo()
    f.Init(ed1, ed2, gp_Pln())
    f.Perform(radius)
    return f.Result(ed1, ed2)
Beispiel #29
0
 reader.TransferRoots()
 shape = reader.OneShape()
 
 # Get bounding box
 xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(shape)
 
 # Build section plane
 XYZ = (0, 1, 1)
 lim_coord1 = (ymin, ymax)
 lim_coord2 = (zmin, zmax)
 
 section_width = xmin + 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(section_width, ymax+ymin, 0.0),
     gp_Dir(1, 0, 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)
             
     exp.Next()
##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
w = make_wire([ed1, fillet2d, ed2])
display.DisplayShape(w)
start_display()