示例#1
0
def main(argv):
  step_reader = STEPControl_Reader()
  status = step_reader.ReadFile(argv[0])

  if status == IFSelect_RetDone:  # check status
      failsonly = False
      step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
      step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

      number_of_roots = step_reader.NbRootsForTransfer()

      ok = False
      i = 1

      while not ok and i <= number_of_roots:
        ok = step_reader.TransferRoot(i)
        i += 1

      _nbs = step_reader.NbShapes()
      aResShape = step_reader.Shape(1)
  else:
      print("Error: can't read file.")
      sys.exit(0)

  display, start_display, add_menu, add_function_to_menu = init_display()
  display.DisplayShape(aResShape, update=True)
  start_display()
 def display_terrain(self):
     """
     Try to display terrain
     """
     display, start_display, add_menu, add_function_to_menu = init_display()
     display.EraseAll()
     display.DisplayShape(self.surface, update=True)
     for river in self.rivers.values():
         display.DisplayShape(river, update=True)
     start_display()
  def update_display(self):
    if self.display_list == None:
      # returns: display, start_display, add_menu, add_function_to_menu
      from OCC.Display.SimpleGui import init_display
      self.display_list = init_display(self.display_driver)

    # ask all modules to add shapes to display
    display = self.display_list[0]
    display.EraseAll()
    for m in self.modules:
      self.modules[m].add_shapes(display = display)
示例#4
0
def display_configuration(tigl_handle):
    """
    This is an example how to use the internal tigl/pyocc API
    to display all wing and fuselage segments
    """

    from OCC.Display.SimpleGui import init_display

    # get the configuration manager
    mgr = tigl.configuration.CCPACSConfigurationManager_get_instance()

    # get the CPACS configuration, defined by the tigl handle
    # we need to access the underlying tigl handle (that is used in the C/C++ API)
    config = mgr.get_configuration(tigl_handle._handle.value)

    display, start_display, add_menu, add_function_to_menu = init_display()

    for ifuse in range(1, config.get_fuselage_count() + 1):
        fuselage = config.get_fuselage(ifuse)
        for isegment in range(1, fuselage.get_segment_count() + 1):
            segment = fuselage.get_segment(isegment)
            display.DisplayShape(segment.get_loft().shape(), update=True)

            mirrored_shape = segment.get_mirrored_loft()
            if mirrored_shape is not None:
                display.DisplayShape(mirrored_shape.shape(), update=True)

    for iwing in range(1, config.get_wing_count() + 1):
        wing = config.get_wing(iwing)

        for isegment in range(1, wing.get_segment_count() + 1):
            segment = wing.get_segment(isegment)

            display.DisplayShape(segment.get_loft().shape(), update=True)

            mirrored_shape = segment.get_mirrored_loft()
            if mirrored_shape is not None:
                display.DisplayShape(mirrored_shape.shape(), update=True)

    for iobj in range(1, config.get_external_object_count()+1):
        obj = config.get_external_object(iobj)
        shape = obj.get_loft()

        if shape is not None:
            display.DisplayShape(shape.shape(), update=True)

        mirrored_shape = obj.get_mirrored_loft()

        if mirrored_shape is not None:
            display.DisplayShape(mirrored_shape.shape(), update=True)

    display.FitAll()

    start_display()
def solid_compound(filename=None):
    """
    Generate and display solid object created from bspline surface.
    """

    # Create Builder first
    builder = BRep_Builder()

    # Base box
    points_1 = [
        gp_Pnt(0.0, 0.0, 0.0),
        gp_Pnt(1.0, 0.0, 0.0),
        gp_Pnt(1.0, 1.0, 0.0),
        gp_Pnt(0.0, 1.0, 0.0),
        gp_Pnt(0.0, 0.0, 1.0),
        gp_Pnt(1.0, 0.0, 1.0),
        gp_Pnt(1.0, 1.0, 1.0),
        gp_Pnt(0.0, 1.0, 1.0)
    ]
    
    solid_box1 = make_box(builder, points_1)
  
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    builder.Add(compound, solid_box1)

    base_primitives = brep_explorer.shape_disassembly(solid_box1)

    # Get some testing elements
    face = base_primitives[4].values()[0]
    wire = wires_of_face(face)[0]
    edges = edges_of_wire(wire)
    for ed_id, edge in enumerate(edges):
        print('edge', ed_id, edge.Orientation())
        verts = verts_of_edge(edge)
        for vert in verts:
            coo = coords_from_vert(vert)
            print(coo, vert.Orientation())

    print('Final compound')
    stat = brep_explorer.create_shape_stat(compound)
    brep_explorer.print_stat(stat)

    if filename is not None:
         breptools_Write(compound, filename)

    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()

    display.DisplayShape(solid_box1, color='red', update=True)

    start_display()
示例#6
0
 def test_with_viewer_after():
     # create parameters
     p = Parameters()
     c = ParametricModelingContext(p)
     # create simple box
     p.X1, p.Y1, p.Z1, p.X2, p.Y2, p.Z2, p.RADIUS = 12,70,12,30,30,30,4  
     my_pnt1 = c.basic_operations.MakePointXYZ(p.X1,p.Y1,p.Z1, name="Pnt1", show=True)
     my_pnt2 = c.basic_operations.MakePointXYZ(p.X2,p.Y2,p.Z2, name="Pnt2", show=True)   # Create the second point
     my_box = c.prim_operations.MakeBoxTwoPnt(my_pnt1,my_pnt2,name="Box1", show=True)
     #Init display after geometry is created
     from OCC.Display.SimpleGui import init_display
     display, start_display, add_menu, add_function_to_menu = init_display()
     c.set_display(display)
     start_display()
def display_result(shapes):
    """
    Display results
    """
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()

    # Display results
    colors = ['red', 'green', 'blue', 'yellow', 'orange']
    col_len = len(colors)
    for color_id, shape in enumerate(shapes):
        _color_id = color_id % col_len
        ais_shell = display.DisplayShape(shape, color=colors[_color_id], update=True)
        # display.Context.SetTransparency(ais_shell, 0.7)
    start_display()
示例#8
0
 def test_with_viewer():
      # init viewer
     from OCC.Display.SimpleGui import init_display
     display, start_display, add_menu, add_function_to_menu = init_display()
     # create parameters
     p = Parameters()
     # create parametric modeling context
     c = ParametricModelingContext(p)
     # set graphics
     c.set_display(display)
     # create simple box
     p.X1, p.Y1, p.Z1, p.X2, p.Y2, p.Z2, p.RADIUS = 12, 70, 12, 30, 30, 30, 4  
     my_pnt1 = c.basic_operations.MakePointXYZ(p.X1, p.Y1, p.Z1, name="Pnt1", show=True)
     my_pnt2 = c.basic_operations.MakePointXYZ(p.X2, p.Y2, p.Z2, name="Pnt2", show=True)
     my_box = c.prim_operations.MakeBoxTwoPnt(my_pnt1, my_pnt2, name="Box1", show=True)
示例#9
0
	def show(self, show_file=None):
		"""
		Method to show a file. If `show_file` is not given it plots `self.shape`.

		:param string show_file: the filename you want to show.
		"""
		if show_file is None:
			shape = self.shape
		else:
			shape = self.load_shape_from_file(show_file)

		display, start_display, __, __ = init_display()
		display.FitAll()
		display.DisplayShape(shape, update=True)

		# Show the plot to the screen
		start_display()
示例#10
0
def display_results(occ_bspline, points):
    """
    Try to display OCC
    :param occ_bspline:
    :param points:
    :return:
    """

    # Initialize displaying
    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()

    # Draw b-spline surfaces
    display.DisplayShape(occ_bspline.GetHandle(), update=True)

    # # Draw points of B-Spline
    import OCC.Prs3d
    import OCC.Quantity
    import OCC.Graphic3d
    import OCC.Aspect
    import OCC.gp

    a_presentation = OCC.Prs3d.Prs3d_Presentation(display._struc_mgr)
    group = OCC.Prs3d.Prs3d_Root_CurrentGroup(a_presentation.GetHandle()).GetObject()
    black = OCC.Quantity.Quantity_Color(OCC.Quantity.Quantity_NOC_BLACK)
    asp = OCC.Graphic3d.Graphic3d_AspectLine3d(black, OCC.Aspect.Aspect_TOL_SOLID, 1)

    gg = OCC.Graphic3d.Graphic3d_ArrayOfPoints(len(points),
                                               False,  # hasVColors
                                               )

    for point in points:
        pnt = OCC.gp.gp_Pnt(point[0], point[1], point[2])
        gg.AddVertex(pnt)

    group.SetPrimitivesAspect(asp.GetHandle())
    group.AddPrimitiveArray(gg.GetHandle())
    a_presentation.Display()

    start_display()
示例#11
0
def visualise(occtopo_2dlist, colour_list = None, backend = "qt-pyqt5"):
    """
    This function visualise a 3D model using the PythonOCC viewer.
 
    Parameters
    ----------
    occtopo_2dlist : 2d list of OCCtopologies
        Geometries to be visualised together with the results.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
        
    colour_list : list of str, optional
        The colours of the occtopo_2dlist, Default = None. If None all the geometries are displayed in white.
        The colour strings include: "WHITE", "BLUE", "RED", "GREEN", "YELLOW", "CYAN", "BLACK", "ORANGE". 
        The number of colours must correspond to the number of list in the other_topo2dlist. 
        
    backend : str, optional
        The graphic interface to use for visualisation, Default = qt-pyqt5. Other options include:"qt-pyqt4", "qt-pyside", "wx"
        
    Returns
    -------
    None : None
        A qt window pops up displaying the geometries.
    """       
    display, start_display, add_menu, add_function_to_menu = init_display(backend_str = backend)
    
    if colour_list == None:
        colour_list = []
        for _ in range(len(occtopo_2dlist)):
            colour_list.append("WHITE")
            
    sc_cnt = 0
    for shape_list in occtopo_2dlist:
        compound = construct.make_compound(shape_list)
        colour = colour_list[sc_cnt]
        display.DisplayColoredShape(compound, color = colour, update=True)
        sc_cnt+=1
        
    display.set_bg_gradient_color(250, 250, 250, 250, 250, 250)
    display.View_Iso()
    display.FitAll()
    start_display()
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")
示例#13
0
	def show(self, show_file=None):
		"""
		Method to show an iges file. If `show_file` is not given it plots `self.infile`.

		:param string show_file: the iges filename you want to show.
		"""
		if show_file is None:
			show_file = self.infile
		else:
			self._check_filename_type(show_file)

		# read in the IGES file
		reader = IGESControl_Reader()
		reader.ReadFile(show_file)
		reader.TransferRoots()
		shape = reader.Shape()

		display, start_display, __, __ = init_display()
		display.FitAll()
		display.DisplayShape(shape, update=True)

		# Show the plot to the screen
		start_display()
def solid_compound(filename=None):
    """
    Generate and display solid object created from b-spline surface.
    """

    # Create Builder first
    builder = BRep_Builder()

    # Base box
    points_1 = [
        gp_Pnt(0.0, 0.0, 0.0),
        gp_Pnt(1.0, 0.0, 0.0),
        gp_Pnt(1.0, 1.0, 0.0),
        gp_Pnt(0.0, 1.0, 0.0),
        gp_Pnt(0.0, 0.0, 1.0),
        gp_Pnt(1.0, 0.0, 1.0),
        gp_Pnt(1.0, 1.0, 1.0),
        gp_Pnt(0.0, 1.0, 1.0)
    ]

    # Definition of boxes used for splitting base box
    dx = 0.5
    dy = 0.01
    dz = 0.01
    points_2 = [
        gp_Pnt(0.0+dx, 0.0-dy, 0.0-dz),
        gp_Pnt(1.0+dx, 0.0-dy, 0.0-dz),
        gp_Pnt(1.0+dx, 1.0+dy, 0.0-dz),
        gp_Pnt(0.0+dx, 1.0+dy, 0.0-dz),
        gp_Pnt(0.0+dx, 0.0-dy, 1.0+dz),
        gp_Pnt(1.0+dx, 0.0-dy, 1.0+dz),
        gp_Pnt(1.0+dx, 1.0+dy, 1.0+dz),
        gp_Pnt(0.0+dx, 1.0+dy, 1.0+dz)
    ]
    
    solids = make_two_boxes(builder, points_1, points_2)

    solids, dup_faces = remove_duple_face_shapes(solids[0], (solids[1],))

    # It would be logical to create "compsolid". Composition of solids sharing
    # one common face, but I did find any Python nor C++ example creating such
    # object.
    #
    # Following code does not work, because builder.Add(compsolid, solids[0])
    # raises error:
    # RuntimeError: TopoDS_UnCompatibleShapes
    # ... it also does not accept shells. OCC is simply horrible library!
    #
    # compsolid = TopoDS_CompSolid()
    # builder.MakeCompSolid(compsolid)
    # builder.Add(compsolid, solids[0])
    # builder.Add(compsolid, solids[1])

    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    # builder.Add(compound, compsolid)
    builder.Add(compound, solids[0])
    builder.Add(compound, solids[1])

    print('Final compound')
    stat = brep_explorer.create_shape_stat(compound)
    brep_explorer.print_stat(stat)

    if filename is not None:
         breptools_Write(compound, filename)

    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()

    display.DisplayShape(solids[0], color='red', update=True)
    display.DisplayShape(solids[1], color='blue', update=True)

    start_display()
示例#15
0
from OCC.Display.SimpleGui import init_display
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.GC import GC_MakeSegment
from OCC.BRepBuilderAPI import BRepBuilderAPI_Transform, BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeEdge
from OCC.gp import gp, gp_Pnt, gp_Vec, gp_Dir, gp_Trsf, gp_Ax1
from PyQt5.QtCore import QTimer
from OCC.GC import GC_MakeLine

display, start_display, add_menu, add_function_to_menu = init_display(
    'qt-pyqt5', (1024, 768))
my_box = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pnt1 = gp_Pnt(-1, -1, 40)
pnt2 = gp_Pnt(-1, -10, 40)

origin = gp_Pnt(0, 0, 0)
xdirection = gp_Dir(1, 0, 0)
xaxis = gp.OX()
t = gp_Trsf()
t.SetMirror(xaxis)
xline = GC_MakeLine(gp.OX()).Value()

geom_curve = GC_MakeSegment(pnt1, pnt2).Value()
bt = BRepBuilderAPI_Transform(my_box, t)
# what about a geom line!?
# ok what about something rotated?
#edge = BRepBuilderAPI_MakeEdge(10)
#my_box2 = BRepPrimAPI_MakeBox(5., 5., 5.).Shape()
#wire = BRepBuilderAPI_MakeWire(10, 10).Shape()


def f():
def run(n_procs, compare_by_number_of_processors=False):
    shape = get_brep()
    x_min, y_min, z_min, x_max, y_max, z_max = get_boundingbox(shape)
    z_delta = abs(z_min - z_max)

    init_time = time.time()  # for total time computation

    def get_z_coords_for_n_procs(n_slices, n_procs):
        z_slices = drange(z_min, z_max, z_delta/n_slices)

        slices = []
        n = len(z_slices) // n_procs

        _str_slices = []
        for i in range(1, n_procs+1):
            if i == 1:
                slices.append(z_slices[:i*n])
                _str_slices.append(':'+str(i*n)+' ')
            elif i == n_procs:
                # does a little extra work if the number of slices
                # isnt divisible by n_procs
                slices.append(z_slices[(i-1)*n:])
                _str_slices.append(str((i-1)*n)+': ')
                print('last slice', len(z_slices[(i-1)*n:]))
            else:
                slices.append(z_slices[(i-1)*n:i*n])
                _str_slices.append(' %s:%s ' % ((i-1)*n, i*n))
        print('the z-index array is sliced over %s processors like this: \n %s' % (n_procs, _str_slices))
        print('number of slices:', z_slices[-1])
        return slices

    def arguments(n_slices, n_procs):
        _tmp = []
        slices = get_z_coords_for_n_procs(n_slices, n_procs)
        for i in slices:
            _tmp.append([i, shape])
        return _tmp

    n_slice = 50

    if not compare_by_number_of_processors:
        _results = []
        P = processing.Pool(n_procs)
        _results = P.map(vectorized_slicer, arguments(n_slice, n_procs))

    else:
        arr = [[i, shape] for i in drange(z_min, z_max, z_delta/n_slice)]
        for i in range(1, 9):
            tA = time.time()
            _results = []
            if i == 1:
                _results = vectorized_slicer([drange(z_min, z_max, z_delta/n_slice), shape])
            else:
                P = processing.Pool(n_procs)
                _results = P.map(vectorized_slicer, arguments(n_slice, i))
            print('slicing took %s seconds for %s processors' % (time.time() - tA, i))
        sys.exit()

    print('\n\n\n DONE SLICING ON %i CORES \n\n\n' % nprocs)

    # Display result
    display, start_display, add_menu, add_function_to_menu = init_display()
    print('displaying original shape')
    display.DisplayShape(shape)
    for n, result_shp in enumerate(_results):
        print('displaying results from process {0}'.format(n))
        display.DisplayShape(result_shp, update=True)

    # update viewer when all is added:
    display.Repaint()
    total_time = time.time() - init_time
    print("%s necessary to perform slice with %s processor(s)." % (total_time, n_procs))
    start_display()
示例#17
0
 def __init__(self, url):
     self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display(
     )
     self.url = url
示例#18
0
def displayShapes(shapes):
    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display("qt-pyqt5")
    for shape in shapes:
        display.DisplayShape(shape)
    start_display()
def bezier_surfaces(event=None):
    """
    Create bezier surface, then create bspline surface from import
    it and search, what is inside created bspline surface.
    """
    array = TColgp_Array2OfPnt(1, 3, 1, 3)

    array.SetValue(1, 1, gp_Pnt(1, 1, 1))
    array.SetValue(1, 2, gp_Pnt(2, 1, 2))
    array.SetValue(1, 3, gp_Pnt(3, 1, 1))
    array.SetValue(2, 1, gp_Pnt(1, 2, 1))
    array.SetValue(2, 2, gp_Pnt(2, 2, 2))
    array.SetValue(2, 3, gp_Pnt(3, 2, 0))
    array.SetValue(3, 1, gp_Pnt(1, 3, 2))
    array.SetValue(3, 2, gp_Pnt(2, 3, 1))
    array.SetValue(3, 3, gp_Pnt(3, 3, 0))

    BZ1 = Geom_BezierSurface(array)

    bezierarray = TColGeom_Array2OfBezierSurface(1, 1, 1, 1)
    bezierarray.SetValue(1, 1, BZ1.GetHandle())
    BB = GeomConvert_CompBezierSurfacesToBSplineSurface(bezierarray)

    if BB.IsDone():
        # Poles
        poles = BB.Poles().GetObject().Array2()
        # print "poles: ", poles, poles.LowerCol(), poles.ColLength(), poles.LowerRow(), poles.RowLength()
        for pole_i in range(poles.LowerCol(), poles.ColLength() + 1, 1):
            for pole_j in range(poles.LowerRow(), poles.RowLength() + 1, 1):
                point = poles.Value(pole_i, pole_j)
                print(pole_i, pole_j, ": (", point.X(), point.Y(), point.Z(), ")")
        print()

        # Knots U and V
        uknots = BB.UKnots().GetObject().Array1()
        vknots = BB.VKnots().GetObject().Array1()
        print("uknots: ", uknots)
        for i in range(uknots.Lower(), uknots.Length() + 1, 1):
            print(uknots.Value(i))
        print("vknots: ", vknots)
        for j in range(vknots.Lower(), vknots.Length() + 1, 1):
            print(vknots.Value(j))
        print()

        # Multi U and V
        umult = BB.UMultiplicities().GetObject().Array1()
        vmult = BB.VMultiplicities().GetObject().Array1()
        print("umult: ", umult)
        for i in range(umult.Lower(), umult.Length() + 1, 1):
            print(umult.Value(i))
        print("vmult: ", vmult)
        for j in range(vmult.Lower(), vmult.Length() + 1, 1):
            print(vmult.Value(i))
        print()

        udeg = BB.UDegree()
        vdeg = BB.VDegree()
        print("udeg, vdeg: ", udeg, vdeg)

        BSPLSURF = Geom_BSplineSurface(poles, uknots, vknots, umult, vmult, udeg, vdeg, 0, 0)

    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()
    display.DisplayShape(BSPLSURF.GetHandle(), update=True)
    start_display()
示例#20
0
    def display_terrain(self):
        """
        Try to display terrain
        """

        # Initialize displaying
        from OCC.Display.SimpleGui import init_display
        display, start_display, add_menu, add_function_to_menu = init_display()
        display.EraseAll()

        diffs = self.conf['terrain']['approximation']['differences']
        display_surf = self.conf['display']['surface']
        display_terr = self.conf['display']['terrain']
        display_rivers = self.conf['display']['rivers']
        display_fractures = self.conf['display']['fractures']

        if display_surf is True:
            if self.volume is not None:
                # Display IDs of points at are border
                self.approximate_2d_borders()
                for point_id, point in enumerate(self.area_borders_3d[0]):
                    occ_point = OCC.gp.gp_Pnt(point[0], point[1], point[2] + 10.0)
                    display.DisplayMessage(occ_point, str(point_id));
                # Display volume
                display.DisplayShape(self.volume, update=True)
                # Display original terrain with transparency
                if self.shell is not None:
                    ais_shell = display.DisplayShape(self.shell, update=True)
                    display.Context.SetTransparency(ais_shell, 0.8)
                else:
                    ais_sewing = display.DisplayShape(self.sewing_shape, update=True)
                    display.Context.SetTransparency(ais_sewing, 0.8)
            elif self.shell is not None:
                display.DisplayShape(self.shell, update=True)
            else:
                # Draw all bspline surfaces
                for bspline in self.bspline_surfaces.values():
                    display.DisplayShape(bspline.GetHandle(), update=True)

        if display_terr is True:
            # Draw points of terrain
            a_presentation, group = self.create_ogl_group(display)
            black = OCC.Quantity.Quantity_Color(OCC.Quantity.Quantity_NOC_BLACK)
            asp = OCC.Graphic3d.Graphic3d_AspectLine3d(black, OCC.Aspect.Aspect_TOL_SOLID, 1)

            if diffs is True:
                pnt_array = OCC.Graphic3d.Graphic3d_ArrayOfPoints(self.point_count,
                                                                  True,  # hasVColors
                                                                  )
            else:
                pnt_array = OCC.Graphic3d.Graphic3d_ArrayOfPoints(self.point_count,
                                                                  False,  # hasVColors
                                                                  )
            if diffs is True:
                idx = 1
            # Default RGB color of point (white)
            for point in self.terrain_data:
                pnt = OCC.gp.gp_Pnt(point[0], point[1], point[2])
                pnt_array.AddVertex(pnt)
                if diffs is True:
                    # create the point, with a diff color
                    if self.max_diff > 0.0:
                        diff = self.tW[idx - 1] / self.max_diff
                    else:
                        diff = 0.0
                    rgb = colorsys.hsv_to_rgb(diff, 1.0, 1.0)
                    pnt_array.SetVertexColor(idx, rgb[0], rgb[1], rgb[2])
                    idx += 1

            group.SetPrimitivesAspect(asp.GetHandle())
            group.AddPrimitiveArray(pnt_array.GetHandle())
            a_presentation.Display()

        if display_rivers is True:
            a_presentation, group = self.create_ogl_group(display)
            black = OCC.Quantity.Quantity_Color(OCC.Quantity.Quantity_NOC_BLACK)
            asp = OCC.Graphic3d.Graphic3d_AspectLine3d(black, OCC.Aspect.Aspect_TOL_SOLID, 1)
            count = 0
            for river in self.rivers_data_3d.values():
                count += len(river)
            pnt_array = OCC.Graphic3d.Graphic3d_ArrayOfPoints(count,
                                                              False,  # hasVColors
                                                              )
            for river in self.rivers_data_3d.values():
                for point in river:
                    pnt = OCC.gp.gp_Pnt(point[0], point[1], point[2])
                    pnt_array.AddVertex(pnt)
            group.SetPrimitivesAspect(asp.GetHandle())
            group.AddPrimitiveArray(pnt_array.GetHandle())
            a_presentation.Display()

            # for river in self.rivers_curves_3d.values():
            #     display.DisplayShape(river, update=True)

        if display_fractures is True and 'input' in self.conf['fractures']:
            display.DisplayShape(self.fractures_shape, update=True)

        start_display()
示例#21
0
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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 __future__ import print_function
import sys

from OCC.Display.backend import load_pyqt4
from OCC.Display.SimpleGui import init_display
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyqt4
if not load_pyqt4():
    print("pyqt4 required to run this test")
    sys.exit()

print('pyqt4 test')
pyqt4_display, start_display, add_menu, add_function_to_menu = init_display(
    'qt-pyqt4')
my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyqt4_display.DisplayShape(my_box_1, update=True)
示例#22
0
    shape_name = feat_name + '-' + wire_name

    fid = 0
    fset = occ_utils.list_face(shape)
    id_map = {}
    for shape_face in fset:
        id_map[shape_face] = fid
        fid += 1

    return shape, name_map, id_map, shape_name


if __name__ == '__main__':
    print('model_factory.py')

    OCC_DISPLAY, START_OCC_DISPLAY, ADD_MENU, ADD_FUNCTION_TO_MENU = init_display(
    )
    OCC_DISPLAY.EraseAll()

    COLORS = [
        rgb_color(0, 0, 0),
        rgb_color(0.75, 0.75, 0.75),
        rgb_color(1, 0, 0),
        rgb_color(1, 0.5, 0),
        rgb_color(0, 1, 1),
        rgb_color(1, 0, 1),
        rgb_color(1, 0.8, 0.8),
        rgb_color(1, 1, 0.8),
        rgb_color(0.8, 1, 1),
        rgb_color(1, 0.8, 1),
        rgb_color(0.4, 0, 0),
        rgb_color(0.4, 0.4, 0),
示例#23
0
#!/usr/bin/env python
##Copyright 2008-2015 Jelle Feringa ([email protected])
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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/>.
# A sample that shows how to generate the gear geometry according
# to knowledge
from OCC.BRepFilletAPI import BRepFilletAPI_MakeFillet
from OCC.BRep import BRep_Tool
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.TopExp import (TopExp_Explorer, topexp_MapShapesAndAncestors,
                        topexp_FirstVertex, topexp_LastVertex)
from OCC.TopAbs import TopAbs_VERTEX, TopAbs_EDGE
from OCC.TopTools import (TopTools_IndexedDataMapOfShapeListOfShape,
                          TopTools_ListIteratorOfListOfShape)
from OCC.TopoDS import topods_Vertex, topods_Edge
from OCC.Display.SimpleGui import init_display
display, start_display, add_menu, add_function_to_menu = init_display()
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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 __future__ import print_function
import sys

from OCC.Display.backend import have_pyqt4
from OCC.Display.SimpleGui import init_display
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyqt4
if not have_pyqt4():
    print("pyqt4 required to run this test")
    sys.exit()

print('pyqt4 test')
pyqt4_display, start_display, add_menu, add_function_to_menu = init_display('qt-pyqt4')
my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyqt4_display.DisplayShape(my_box_1, update=True)
示例#25
0
 def __init__(self):
     super().__init__()
     self.display, self.start_display, add_menu, add_function_to_menu = init_display(
         None, (700, 500), True, [128, 128, 128], [128, 128, 128])
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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 __future__ import print_function
import sys

from OCC.Display.backend import load_pyside
from OCC.Display.SimpleGui import init_display
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyside
if not load_pyside():
    print("pyside required to run this test")
    sys.exit()

print('pyside test')
pyside_display, start_display, add_menu, add_function_to_menu = init_display(
    'qt-pyside')
my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyside_display.DisplayShape(my_box_1, update=True)
示例#27
0
文件: blade.py 项目: ztotal/BladeX
    def generate_iges(self,
                      upper_face=None,
                      lower_face=None,
                      tip=None,
                      maxDeg=1,
                      display=False,
                      errors=None):
        """
        Generate and export the .iges CAD for the blade upper face, lower face,
        and tip. This method requires PythonOCC to be installed.

        :param string upper_face: if string is passed then the method generates
            the blade upper surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <upper_face_string>.iges. Default value is None
        :param string lower_face: if string is passed then the method generates
            the blade lower surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <lower_face_string>.iges. Default value is None
        :param string tip: if string is passed then the method generates
            the blade tip using the BRepOffsetAPI_ThruSections algorithm
            in order to close the blade, then exports the generated CAD into
            .iges file holding the name <tip_string>.iges. Default value is None
        :param int maxDeg: Define the maximal U degree of generated surface.
            Default value is 1
        :param bool display: if True, then display the generated CAD. Default
            value is False
        :param string errors: if string is passed then the method writes out
            the distances between each discrete point used to construct the
            blade and the nearest point on the CAD that is perpendicular to
            that point. Default value is None

        We note that the blade object must have its radial sections be arranged
        in order from the blade root to the blade tip, so that generate_iges
        method can build the CAD surface that passes through the corresponding
        airfoils. Also to be able to identify and close the blade tip.
        """

        from OCC.IGESControl import IGESControl_Writer
        from OCC.Display.SimpleGui import init_display

        if maxDeg <= 0:
            raise ValueError('maxDeg argument must be a positive integer.')

        if upper_face:
            self._check_string(filename=upper_face)
            self._generate_upper_face(maxDeg=maxDeg)
            # Write IGES
            iges_writer = IGESControl_Writer()
            iges_writer.AddShape(self.generated_upper_face)
            iges_writer.Write(upper_face + '.iges')

        if lower_face:
            self._check_string(filename=lower_face)
            self._generate_lower_face(maxDeg=maxDeg)
            # Write IGES
            iges_writer = IGESControl_Writer()
            iges_writer.AddShape(self.generated_lower_face)
            iges_writer.Write(lower_face + '.iges')

        if tip:
            self._check_string(filename=tip)
            self._generate_tip(maxDeg=maxDeg)
            iges_writer = IGESControl_Writer()
            iges_writer.AddShape(self.generated_tip)
            iges_writer.Write(tip + '.iges')

        if errors:
            # Write out errors between discrete points and constructed faces
            self._check_string(filename=errors)
            self._check_errors(upper_face=upper_face, lower_face=lower_face)

            self._write_blade_errors(upper_face=upper_face,
                                     lower_face=lower_face,
                                     errors=errors)

        if display:
            display, start_display, add_menu, add_function_to_menu = init_display(
            )

            ## DISPLAY FACES
            if upper_face:
                display.DisplayShape(generated_upper_face, update=True)
            if lower_face:
                display.DisplayShape(generated_lower_face, update=True)
            if tip:
                display.DisplayShape(generated_tip, update=True)
            start_display()
##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

import sys
print(sys.path)
# required by travis to find SimpleGui module
# both on py2 and py3
sys.path.append('/home/travis/virtualenv/python2.7.8/lib/python2.7/site-packages')
sys.path.append('/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages')
from OCC.Display.SimpleGui import init_display
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

# pyside test
print('pyside test')
pyside_display, start_display, add_menu, add_function_to_menu = init_display('qt-pyside')
my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyside_display.DisplayShape(my_box_1, update=True)

# pyqt4 test
print('pyqt4 test')
pyqt4_display, start_display, add_menu, add_function_to_menu = init_display('qt-pyqt4')
my_box_2 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyqt4_display.DisplayShape(my_box_2, update=True)

# wx test
print('wx test')
wx_display, start_display, add_menu, add_function_to_menu = init_display('wx')
my_box_3 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
wx_display.DisplayShape(my_box_3, update=True)
示例#29
0
def visualise_falsecolour_topo(results,
                               occtopo_list,
                               other_topo2dlist=None,
                               other_colourlist=None,
                               minval_range=None,
                               maxval_range=None,
                               backend="qt-pyqt5"):

    display, start_display, add_menu, add_function_to_menu = init_display(
        backend_str=backend)

    if minval_range == None:
        minval = min(results)
    elif minval_range != None:
        minval = minval_range

    if maxval_range == None:
        maxval = max(results)
    elif maxval_range != None:
        maxval = maxval_range

    res_colours = falsecolour(results, minval, maxval)

    colour_list = []
    c_srf_list = []
    for r_cnt in range(len(res_colours)):
        fcolour = res_colours[r_cnt]
        rf = occtopo_list[r_cnt]
        if fcolour not in colour_list:
            colour_list.append(fcolour)
            c_srf_list.append([rf])

        elif fcolour in colour_list:
            c_index = colour_list.index(fcolour)
            c_srf_list[c_index].append(rf)

    for c_cnt in range(len(c_srf_list)):
        c_srfs = c_srf_list[c_cnt]
        colour = colour_list[c_cnt]
        compound = make_compound(c_srfs)
        display.DisplayColoredShape(compound, color=colour, update=True)

    #display the edges of the grid
    tedges = []
    for t in occtopo_list:
        edge = list(Topology.Topo(t).edges())
        tedges.extend(edge)

    edgecompound = make_compound(tedges)
    display.DisplayColoredShape(edgecompound, color="BLACK", update=True)

    if other_topo2dlist != None:
        tc_cnt = 0
        for other_topolist in other_topo2dlist:
            other_compound = make_compound(other_topolist)
            other_colour = other_colourlist[tc_cnt]
            display.DisplayColoredShape(other_compound,
                                        color=other_colour,
                                        update=True)
            tc_cnt += 1

    display.set_bg_gradient_color(0, 0, 0, 0, 0, 0)
    display.View_Iso()
    display.FitAll()
    start_display()
示例#30
0
def display_shapes(shapes):
  from OCC.Display.SimpleGui import init_display
  display, start_display, add_menu, add_function_to_menu = init_display()
  [display.DisplayShape(shape, update=True) for shape in shapes]
  start_display()
##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 __future__ import print_function

import sys
print(sys.path)

from OCC.Display.SimpleGui import init_display
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

# pyside test
print('pyside test')
PYSIDE_INITIALIZED = False
try:
    pyside_display, start_display, add_menu, add_function_to_menu = init_display(
        'qt-pyside')
    PYSIDE_INITIALIZED = True
except:
    print('cant load the qt-pyside backend')
if PYSIDE_INITIALIZED:
    my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
    pyside_display.DisplayShape(my_box_1, update=True)

# pyqt4 test
print('pyqt4 test')
PYQT4_INITIALIZED = False
try:
    pyqt4_display, start_display, add_menu, add_function_to_menu = init_display(
        'qt-pyqt4')
    PYQT4_INITIALIZED = True
except:
def bspline_surface():
    """
    Try to create B-spline surface directly
    """

    # Set U and V degree to 2
    udeg = 2
    vdeg = 2

    # Non-periodic surface
    uperiod = False
    vperiod = False

    # Create 2D array of poles (control points)
    poles = TColgp_Array2OfPnt(1, 3, 1, 3)
    poles.SetValue(1, 1, gp_Pnt(1, 1, 1))
    poles.SetValue(1, 2, gp_Pnt(2, 1, 2))
    poles.SetValue(1, 3, gp_Pnt(3, 1, 1))
    poles.SetValue(2, 1, gp_Pnt(1, 2, 1))
    poles.SetValue(2, 2, gp_Pnt(2, 2, 2))
    poles.SetValue(2, 3, gp_Pnt(3, 2, 0))
    poles.SetValue(3, 1, gp_Pnt(1, 3, 2))
    poles.SetValue(3, 2, gp_Pnt(2, 3, 1))
    poles.SetValue(3, 3, gp_Pnt(3, 3, 0))

    # Create 2D array of weights
    weights = TColStd_Array2OfReal(1, 3, 1, 3)
    weights.SetValue(1, 1, 1.0)
    weights.SetValue(1, 2, 1.0)
    weights.SetValue(1, 3, 1.0)
    weights.SetValue(2, 1, 1.0)
    weights.SetValue(2, 2, 1.0)
    weights.SetValue(2, 3, 1.0)
    weights.SetValue(3, 1, 1.0)
    weights.SetValue(3, 2, 1.0)
    weights.SetValue(3, 3, 1.0)

    # Length of uknots and umult has to be same
    # Same rule is for vknots and vmult
    uknot_len = umult_len = 2
    vknot_len = vmult_len = 2

    # Knots for U and V direction
    uknots = TColStd_Array1OfReal(1, uknot_len)
    vknots = TColStd_Array1OfReal(1, vknot_len)

    # Main curves begins and ends at first and last points
    uknots.SetValue(1, 0.0)
    uknots.SetValue(2, 1.0)
    vknots.SetValue(1, 0.0)
    vknots.SetValue(2, 1.0)

    # Multiplicities for U and V direction
    umult = TColStd_Array1OfInteger(1, umult_len)
    vmult = TColStd_Array1OfInteger(1, vmult_len)

    # First and last multiplicities are set to udeg + 1 (vdeg respectively),
    # because we want main curves to start and finish on the first and
    # the last points
    umult.SetValue(1, udeg + 1)
    umult.SetValue(2, udeg + 1)
    vmult.SetValue(1, vdeg + 1)
    vmult.SetValue(2, vdeg + 1)

    # Some other rules, that has to hold:
    # poles.ColLength == sum(umult(i)) - udeg - 1 (e.g.: 3 == 6 - 2 - 1)

    # Try to create surface (no weight)
    #BSPLSURF = Geom_BSplineSurface(poles, uknots, vknots, umult, vmult, udeg, vdeg, uperiod, vperiod)
    # Try to create surface (weights to default values)
    BSPLSURF = Geom_BSplineSurface(poles, weights, uknots, vknots, umult, vmult, udeg, vdeg, uperiod, vperiod)

    # Display surface
    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.EraseAll()
    display.DisplayShape(BSPLSURF.GetHandle(), update=True)
    start_display()
示例#33
0
def visualise_falsecolour_topo(occtopo_list, results, other_occtopo_2dlist = None, other_colour_list = None, 
                               minval = None, maxval = None, backend = "qt-pyqt5",
                               inverse = False):
    """
    This function visualise a falsecolour 3D model using the PythonOCC viewer.
 
    Parameters
    ----------
    occtopo_list : list of OCCtopologies
        The geometries to be visualised with the results. The list of geometries must correspond to the list of results.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
        
    results : list of floats
        The results to be visualised. The list of results must correspond to the occtopo_list.
        
    other_occtopo_2dlist : 2d list of OCCtopologies, optional
        Other geometries to be visualised together with the results, Default = None.
        
    other_colour_list : list of str, optional
        The colours of the other_topo2dlist, Default = None. The colour strings include: "WHITE", "BLUE", "RED", "GREEN", "YELLOW", "CYAN",
        "BLACK", "ORANGE". The number of colours must correspond to the number of list in the other_topo2dlist. 
        
    minval : float, optional
        The minimum value of the falsecolour rgb, Default = None. If None the maximum value is equal to the maximum value from the results.
        
    maxval : float, optional
        The maximum value of the falsecolour rgb, Default = None. If None the maximum value is equal to the minimum value from the results.
        
    backend : str, optional
        The graphic interface to use for visualisation, Default = qt-pyqt5. Other options include:"qt-pyqt4", "qt-pyside", "wx"
        
    inverse : bool
        False for red being max, True for blue being maximum.
        
    Returns
    -------
    None : None
        A qt window pops up displaying the geometries.
    """                          
    display, start_display, add_menu, add_function_to_menu = init_display(backend_str = backend)
    
    if minval == None: 
        minval1 = min(results)
    elif minval != None:
        minval1 = minval
    
    if maxval == None: 
        maxval1 = max(results)
    elif maxval != None: 
        maxval1 = maxval
        
    res_colours = falsecolour(results, minval1, maxval1, inverse=inverse)

    colour_list = []
    c_srf_list = []
    for r_cnt in range(len(res_colours)):
        fcolour = res_colours[r_cnt]
        rf = occtopo_list[r_cnt]
        if fcolour not in colour_list:
            colour_list.append(fcolour)
            c_srf_list.append([rf])
            
        elif fcolour in colour_list:
            c_index = colour_list.index(fcolour)
            c_srf_list[c_index].append(rf)
        
    for c_cnt in range(len(c_srf_list)):
        c_srfs = c_srf_list[c_cnt]
        colour = colour_list[c_cnt]
        from OCC.Quantity import Quantity_TOC_RGB, Quantity_Color
        compound = construct.make_compound(c_srfs)
        display.DisplayColoredShape(compound, color=Quantity_Color(colour[0], colour[1], colour[2], Quantity_TOC_RGB), update=True)
        
    #display the edges of the grid
    tedges = []
    for t in occtopo_list:
        edge = list(Topology.Topo(t).edges())
        tedges.extend(edge)
        
    edgecompound = construct.make_compound(tedges)
    display.DisplayColoredShape(edgecompound, color="BLACK", update=True)
            
    if other_occtopo_2dlist != None:
        tc_cnt = 0
        for other_topolist in other_occtopo_2dlist:
            other_compound = construct.make_compound(other_topolist)
            other_colour = other_colour_list[tc_cnt]
            display.DisplayColoredShape(other_compound, color=other_colour, update=True)
            tc_cnt +=1
    
    display.set_bg_gradient_color(0, 0, 0, 0, 0, 0)
    display.View_Iso()
    display.FitAll()
    start_display()
def run(n_procs, compare_by_number_of_processors=False):
    shape = get_brep()
    x_min, y_min, z_min, x_max, y_max, z_max = get_boundingbox(shape)
    z_delta = abs(z_min - z_max)

    init_time = time.time()  # for total time computation

    def get_z_coords_for_n_procs(n_slices, n_procs):
        z_slices = drange(z_min, z_max, z_delta / n_slices)

        slices = []
        n = len(z_slices) // n_procs

        _str_slices = []
        for i in range(1, n_procs + 1):
            if i == 1:
                slices.append(z_slices[:i * n])
                _str_slices.append(':' + str(i * n) + ' ')
            elif i == n_procs:
                # does a little extra work if the number of slices
                # isnt divisible by n_procs
                slices.append(z_slices[(i - 1) * n:])
                _str_slices.append(str((i - 1) * n) + ': ')
                print('last slice', len(z_slices[(i - 1) * n:]))
            else:
                slices.append(z_slices[(i - 1) * n:i * n])
                _str_slices.append(' %s:%s ' % ((i - 1) * n, i * n))
        print(
            'the z-index array is sliced over %s processors like this: \n %s' %
            (n_procs, _str_slices))
        print('number of slices:', z_slices[-1])
        return slices

    def arguments(n_slices, n_procs):
        _tmp = []
        slices = get_z_coords_for_n_procs(n_slices, n_procs)
        for i in slices:
            _tmp.append([i, shape])
        return _tmp

    n_slice = 50

    if not compare_by_number_of_processors:
        _results = []
        P = processing.Pool(n_procs)
        _results = P.map(vectorized_slicer, arguments(n_slice, n_procs))

    else:
        arr = [[i, shape] for i in drange(z_min, z_max, z_delta / n_slice)]
        for i in range(1, 9):
            tA = time.time()
            _results = []
            if i == 1:
                _results = vectorized_slicer(
                    [drange(z_min, z_max, z_delta / n_slice), shape])
            else:
                P = processing.Pool(n_procs)
                _results = P.map(vectorized_slicer, arguments(n_slice, i))
            print('slicing took %s seconds for %s processors' %
                  (time.time() - tA, i))
        sys.exit()

    print('\n\n\n DONE SLICING ON %i CORES \n\n\n' % nprocs)

    # Display result
    display, start_display, add_menu, add_function_to_menu = init_display()
    print('displaying original shape')
    display.DisplayShape(shape)
    for n, result_shp in enumerate(_results):
        print('displaying results from process {0}'.format(n))
        display.DisplayShape(result_shp, update=True)

    # update viewer when all is added:
    display.Repaint()
    total_time = time.time() - init_time
    print("%s necessary to perform slice with %s processor(s)." %
          (total_time, n_procs))
    start_display()
from __future__ import print_function
import sys

from OCC.BRepGProp import brepgprop_LinearProperties
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeSphere
from OCC.Display.SimpleGui import init_display
from OCC.Display.backend import get_qt_modules
from OCC.GProp import GProp_GProps
from OCC.TopAbs import TopAbs_SOLID, TopAbs_EDGE, TopAbs_FACE
from OCC.TopLoc import TopLoc_Location
from OCC.gp import gp_Trsf, gp_Vec

display, start_display, add_menu, add_function_to_menu = init_display("qt-pyqt5")
QtCore, QtGui, QtWidgets, QtOpenGL = get_qt_modules()

from OCC.Display.qtDisplay import qtViewer3d

print("Usage: press G to find the linear properties for volume, face, edge, vertex...")


def get_occ_viewer():
    """

    Returns
    -------

    qtViewer3d

    """
    app = QtWidgets.QApplication.instance()  # checks if QApplication already exists
    if not app:
示例#36
0
from OCC.Core.BRepFeat import BRepFeat_Gluer
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.Display.SimpleGui import init_display
from OCC.Core.LocOpe import LocOpe_FindEdges
from OCC.Core.TopAbs import TopAbs_FACE
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Core.TopLoc import TopLoc_Location
from OCC.Core.TopoDS import topods_Face
from OCC.Core.gp import gp_Pnt, gp_Trsf, gp_Vec

from OCC.Extend.ShapeFactory import center_boundingbox

display, start_display, add_menu, add_function_to_menu = init_display()


def get_faces(_shape):
    """ return the faces from `_shape`
    :param _shape: TopoDS_Shape, or a subclass like TopoDS_Solid
    :return: a list of faces found in `_shape`
    """
    topExp = TopExp_Explorer()
    topExp.Init(_shape, TopAbs_FACE)
    _faces = []

    while topExp.More():
        fc = topods_Face(topExp.Current())
        #print(fc)
        _faces.append(fc)
        topExp.Next()

    return _faces
示例#37
0
def visualise_falsecolour_topo(occtopo_list,
                               results,
                               other_occtopo_2dlist=None,
                               other_colour_list=None,
                               minval=None,
                               maxval=None,
                               backend="qt-pyqt5"):
    """
    This function visualise a falsecolour 3D model using the PythonOCC viewer.
 
    Parameters
    ----------
    occtopo_list : list of OCCtopologies
        The geometries to be visualised with the results. The list of geometries must correspond to the list of results.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
        
    results : list of floats
        The results to be visualised. The list of results must correspond to the occtopo_list.
        
    other_occtopo_2dlist : 2d list of OCCtopologies, optional
        Other geometries to be visualised together with the results, Default = None.
        
    other_colour_list : list of str, optional
        The colours of the other_topo2dlist, Default = None. The colour strings include: "WHITE", "BLUE", "RED", "GREEN", "YELLOW", "CYAN",
        "BLACK", "ORANGE". The number of colours must correspond to the number of list in the other_topo2dlist. 
        
    minval : float, optional
        The minimum value of the falsecolour rgb, Default = None. If None the maximum value is equal to the maximum value from the results.
        
    maxval : float, optional
        The maximum value of the falsecolour rgb, Default = None. If None the maximum value is equal to the minimum value from the results.
        
    backend : str, optional
        The graphic interface to use for visualisation, Default = qt-pyqt5. Other options include:"qt-pyqt4", "qt-pyside", "wx"
        
    Returns
    -------
    None : None
        A qt window pops up displaying the geometries.
    """
    display, start_display, add_menu, add_function_to_menu = init_display(
        backend_str=backend)

    if minval == None:
        minval1 = min(results)
    elif minval != None:
        minval1 = minval

    if maxval == None:
        maxval1 = max(results)
    elif maxval != None:
        maxval1 = maxval

    res_colours = falsecolour(results, minval1, maxval1)

    colour_list = []
    c_srf_list = []
    for r_cnt in range(len(res_colours)):
        fcolour = res_colours[r_cnt]
        rf = occtopo_list[r_cnt]
        if fcolour not in colour_list:
            colour_list.append(fcolour)
            c_srf_list.append([rf])

        elif fcolour in colour_list:
            c_index = colour_list.index(fcolour)
            c_srf_list[c_index].append(rf)

    for c_cnt in range(len(c_srf_list)):
        c_srfs = c_srf_list[c_cnt]
        colour = colour_list[c_cnt]
        from OCC.Quantity import Quantity_TOC_RGB, Quantity_Color
        compound = construct.make_compound(c_srfs)
        display.DisplayColoredShape(compound,
                                    color=Quantity_Color(
                                        colour[0], colour[1], colour[2],
                                        Quantity_TOC_RGB),
                                    update=True)

    #display the edges of the grid
    tedges = []
    for t in occtopo_list:
        edge = list(Topology.Topo(t).edges())
        tedges.extend(edge)

    edgecompound = construct.make_compound(tedges)
    display.DisplayColoredShape(edgecompound, color="BLACK", update=True)

    if other_occtopo_2dlist != None:
        tc_cnt = 0
        for other_topolist in other_occtopo_2dlist:
            other_compound = construct.make_compound(other_topolist)
            other_colour = other_colour_list[tc_cnt]
            display.DisplayColoredShape(other_compound,
                                        color=other_colour,
                                        update=True)
            tc_cnt += 1

    display.set_bg_gradient_color(0, 0, 0, 0, 0, 0)
    display.View_Iso()
    display.FitAll()
    start_display()
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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 __future__ import print_function
import sys

from OCC.Display.backend import have_pyside
from OCC.Display.SimpleGui import init_display
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyside
if not have_pyside():
    print("pyside required to run this test")
    sys.exit()

print('pyside test')
pyside_display, start_display, add_menu, add_function_to_menu = init_display('qt-pyside')
my_box_1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
pyside_display.DisplayShape(my_box_1, update=True)
#!/usr/bin/env python
##Copyright 2008-2015 Jelle Feringa ([email protected])
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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/>.
# A sample that shows how to generate the gear geometry according
# to knowledge
from OCC.BRepFilletAPI import BRepFilletAPI_MakeFillet
from OCC.BRep import BRep_Tool
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.TopExp import (TopExp_Explorer,
                        topexp_MapShapesAndAncestors,
                        topexp_FirstVertex,
                        topexp_LastVertex)
from OCC.TopAbs import TopAbs_VERTEX, TopAbs_EDGE
from OCC.TopTools import (TopTools_IndexedDataMapOfShapeListOfShape,
                          TopTools_ListIteratorOfListOfShape)
from OCC.TopoDS import topods_Vertex, topods_Edge
示例#40
0
prop = GpropsFromShape(TF['case'])
print('gprop', prop.volume().Mass())

prop = GProp_GProps()
brepgprop_VolumeProperties(TF['case'], prop, 1e-6)
print('case volume', prop.Mass())

prop = GProp_GProps()
brepgprop_VolumeProperties(TF['wp'], prop, 1e-6)
print('wp volume', prop.Mass())

prop = GProp_GProps()
brepgprop_VolumeProperties(TFcage['wp'], prop, 1e-6)
print('cold mass volume', prop.Mass())

display, start_display = init_display()[:2]
display.DisplayColoredShape(TFcage['case'], QC[0])
display.DisplayColoredShape(GScage, QC[1])
display.DisplayColoredShape(PFcage, QC[5])
display.FitAll()
start_display()

# Export to STEP
scale = gp_Trsf()  # to mm
scale.SetScaleFactor(1000)
TF['wp'] = BRepBuilderAPI_Transform(TF['wp'], scale).Shape()
TF['case'] = BRepBuilderAPI_Transform(TF['case'], scale).Shape()
GSstrut = BRepBuilderAPI_Transform(GSstrut, scale).Shape()

from aocxchange import step_ocaf
export = step_ocaf.StepOcafExporter('./TF_{:d}.stp'.format(nTF))
示例#41
0
 def __init__(self):
     self.display, self.start_display, self.add_menu, self.add_function = init_display(
     )
     self.base_axs = gp_Ax3()
     SetDir.__init__(self)
示例#42
0
def main():
    display, start_display, add_menu, add_functionto_menu = init_display()
    parser = Parser(display)
    parser.importStep()
    start_display()
示例#43
0
 def __init__(self):
     self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
     #wx.Frame.__init__(self, parent, -1, "Display server", style=wx.DEFAULT_FRAME_STYLE,size = (640,480))
     #self.canva = wxViewer3d(self)
     # Start thread that listen Queue
     thread.start_new_thread(self.Listen,())
示例#44
0
 def biubiu(self):
     display, start_display, add_menu, add_function_to_menu = init_display()
     self.shapes = read_step_file(r'C:\Users\lenovo\Desktop\dest1.step')
     display.DisplayShape(self.shapes, update=True)
     start_display()
示例#45
0
from OCC.Display.SimpleGui import init_display

import examples_data
import occ_utils

display, start_display, _, _ = init_display()


def bspline_example(n):
    examples = examples_data.bspline()
    p_list = examples[n].points
    u_list = examples[n].knots
    return occ_utils.bspline(p_list, u_list)


def nurbs_example(n):
    examples = examples_data.nurbs()
    p_list = examples[n].points
    u_list = examples[n].knots
    w_list = examples[n].weights
    return occ_utils.nurbs(p_list, u_list, w_list)


if __name__ == '__main__':
    # B-spline example
    spline = bspline_example(3)

    # NURBS example
    # spline = nurbs_example(0)

    # Display spline
示例#46
0
 def __init__(self):
     self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
示例#47
0
 def __init__(self):
     self.display, self.start_display, self.add_menu, self.add_functionto_menu = init_display(
     )
     SetDir.__init__(self)
示例#48
0
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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/>.

import sys

from OCC.Display.backend import load_pyside2
from OCC.Display.SimpleGui import init_display
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyside
if not load_pyside2():
    print("pyside2 required to run this test")
    sys.exit()

print("pyside2 test running ...")
pyside2_display, start_display, add_menu, add_function_to_menu = init_display(
    "qt-pyside2")
my_box = BRepPrimAPI_MakeBox(10.0, 20.0, 30.0).Shape()
pyside2_display.DisplayShape(my_box, update=True)
print("pyside2 test ok.")
示例#49
0
 def __init__(self):
     from OCC.Display.SimpleGui import init_display
     self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##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/>.

import sys

from OCC.Display.backend import load_pyqt5
from OCC.Display.SimpleGui import init_display
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox

# check for pyqt5
if not load_pyqt5():
    print("pyqt5 required to run this test")
    sys.exit()

print("pyqt5 test running ...")
pyqt5_display, start_display, add_menu, add_function_to_menu = init_display(
    "qt-pyqt5")
my_box = BRepPrimAPI_MakeBox(10.0, 20.0, 30.0).Shape()
pyqt5_display.DisplayShape(my_box, update=True)
print("pyqt5 test ok.")
示例#51
0
 def __init__(self):
     self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display(
     )
     #wx.Frame.__init__(self, parent, -1, "Display server", style=wx.DEFAULT_FRAME_STYLE,size = (640,480))
     #self.canva = wxViewer3d(self)
     # Start thread that listen Queue
     thread.start_new_thread(self.Listen, ())
示例#52
0
##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 __future__ import print_function

import time
from math import pi

from OCC.gp import gp_Ax1, gp_Pnt, gp_Dir, gp_Trsf
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.TopLoc import TopLoc_Location
from OCC.Display.SimpleGui import init_display

display, start_display, add_menu, add_function_to_menu = init_display()

ais_boxshp = None


def build_shape():
    boxshp = BRepPrimAPI_MakeBox(50., 50., 50.).Shape()
    ais_boxshp = display.DisplayShape(boxshp, update=True)
    return ais_boxshp


def rotating_cube_1_axis(event=None):
    display.EraseAll()
    ais_boxshp = build_shape()
    ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.))
    aCubeTrsf = gp_Trsf()
示例#53
0
 def showocc(self):
     display, start_display, add_menu, add_function_to_menu = init_display()
     start_display()