class ViewController(QObject): modelUpdate = pyqtSignal(object) def __init__(self, display): super(ViewController, self).__init__() self._manipulator = AIS_Manipulator() self._manipulator.SetModeActivationOnDetection(True) self._display = display self._selectedShape = None self._active = False def setActive(self): self._active = True def setDeactive(self): self._active = False self._manipulator.Detach() def selectAIS_Shape(self, x, y): ##object selection if self._active == True: self._display.MoveTo(x, y) assert isinstance(self._display.Context, AIS_InteractiveContext) try: if self._display.Context.HasDetected(): self._display.Context.InitDetected() if self._display.Context.MoreDetected(): detected_object = self._display.Context.DetectedInteractive() assert isinstance(detected_object, AIS_InteractiveObject) if detected_object.Type() == AIS_KOI_Shape: self._selectedShape = detected_object self._manipulator.Attach(self._selectedShape) self._display.Context.NextDetected() except Exception as e: print(e) def startTransform(self, x, y): if self._manipulator.HasActiveMode() and self._active == True: self._manipulator.StartTransform(x, y, self._display.View) def transform(self, x, y): if self._manipulator.HasActiveMode() and self._active == True: self._manipulator.Transform(x, y, self._display.View) self._display.View.Redraw() def finishTransform(self, x, y): if self._manipulator.HasActiveMode() and self._active == True: self.setDeactive()
class OCCApp(SetDir, Viewer): def __init__(self, disp=True, touch=False): SetDir.__init__(self) self.base_axs = gp_Ax3() self.disp = disp self.touch = touch self.colors = [ "BLUE1", "RED", "GREEN", "YELLOW", "ORANGE", "BLACK", "WHITE" ] # OCC Viewer if disp == True: self.display, self.start_display, self.add_menu, self.add_function, self.wi = init_qtdisplay( ) if touch == True: Viewer.__init__(self, disp=True) self.on_select() self.SaveMenu() self.ViewMenu() self.SelectMenu() self.SelectMesh() else: Viewer.__init__(self, disp=False) # GMSH self.gmsh = _gmsh_path() def AddManipulator(self): self.manip = AIS_Manipulator(self.base_axs.Ax2()) ais_shp = self.display.DisplayShape(self.base_axs.Location(), update=True) self.manip.Attach(ais_shp) def SaveMenu(self): self.add_menu("File") self.add_function("File", self.import_cadfile) self.add_function("File", self.export_cap) if self.touch == True: self.add_function("File", self.export_stp_selected) self.add_function("File", self.export_stl_selected) self.add_function("File", self.export_igs_selected) self.add_function("File", self.export_brep_selected) self.add_function("File", self.clear_selected) self.add_function("File", self.open_newtempir) self.add_function("File", self.open_tempir) self.add_function("File", self.exit_win) def ViewMenu(self): self.add_menu("View") self.add_function("View", self.display.FitAll) self.add_function("View", self.display.View_Top) # XY-Plane(+) self.add_function("View", self.display.View_Bottom) # XY-Plane(-) self.add_function("View", self.display.View_Rear) # XZ-Plane(+) self.add_function("View", self.display.View_Front) # XZ-Plane(-) self.add_function("View", self.display.View_Right) # YZ-Plane(+) self.add_function("View", self.display.View_Left) # YZ-Plane(-) self.add_function("View", self.view_xaxis) self.add_function("View", self.view_yaxis) self.add_function("View", self.view_zaxis) self.add_function("View", self.ray_tracing_mode) self.add_function("View", self.display.SetRasterizationMode) def SelectMenu(self): self.add_menu("Select") self.add_function("Select", self.display.SetSelectionModeVertex) self.add_function("Select", self.display.SetSelectionModeEdge) self.add_function("Select", self.display.SetSelectionModeFace) self.add_function("Select", self.SetSelectionModeShape) self.add_function("Select", self.display.SetSelectionModeNeutral) def SelectMesh(self): self.add_menu("Mesh") self.add_function("Mesh", self.gen_aligned_bounded_box) self.add_function("Mesh", self.gen_oriented_bounded_box) self.add_function("Mesh", self.gen_mesh_face) def SetSelectionModeShape(self): self.display.SetSelectionMode(TopAbs_SHAPE) def view_xaxis(self): self.display.View.Rotate(0, np.deg2rad(15), 0, 0, 1, 0, True) def view_yaxis(self): self.display.View.Rotate(np.deg2rad(15), 0, 0, 1, 0, 0, True) def view_zaxis(self): self.display.View.Rotate(0, 0, np.deg2rad(15), 0, 0, 1, True) def gen_mesh_face(self): self.export_cap() comp = self.make_comp_selcted() mesh = face_mesh_triangle(comp, 0.1, 0.1) self.display.DisplayShape(mesh, update=True) self.export_cap() def gen_aligned_bounded_box(self): comp = self.make_comp_selcted() c, dxyz, box = get_aligned_boundingbox_ratio(comp, ratio=1.0) if self.disp == True: self.display.DisplayShape(box, transparency=0.9, update=True) self.export_cap() return c, dxyz, box def gen_oriented_bounded_box(self): comp = self.make_comp_selcted() c, dxyz, box = get_oriented_boundingbox_ratio(comp, ratio=1.0) if self.disp == True: self.display.DisplayShape(box, transparency=0.9, update=True) self.export_cap() return c, dxyz, box def ray_tracing_mode(self): # create one spotlight spot_light = V3d_SpotLight(gp_Pnt(-1000, -1000, 1000), V3d_XnegYnegZpos, Quantity_Color(Quantity_NOC_WHITE)) # display the spotlight in rasterized mode self.display.Viewer.AddLight(spot_light) self.display.View.SetLightOn() self.display.SetRaytracingMode(depth=8) # pythonocc-core=7.4.0 # TKOpenGl | Type: Error | ID: 0 | Severity: High | Message: # Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension # pythonocc-core=7.4.1 # RuntimeError: Aspect_GraphicDeviceDefinitionErrorOpenGl_Window::CreateWindow: SetPixelFormat failed. # Error code: 2000 raised from method Init of class Display3d def import_geofile(self, geofile, tol=0.1): # msh1, msh2, msh22, msh3, msh4, msh40, msh41, msh, # unv, vtk, wrl, mail, stl, p3d, mesh, bdf, cgns, med, # diff, ir3, inp, ply2, celum, su2, x3d, dat, neu, m, key geo_dir = os.path.dirname(geofile) geo_base = os.path.basename(geofile) geo_name = create_tempnum(self.rootname, self.tmpdir, ".geo") geo_file = os.path.basename(geo_name) shutil.copyfile(geofile, geo_name) stl_name, _ = os.path.splitext(self.tmpdir + geo_file) stl_name += ".stl" stl_name = os.path.abspath(stl_name) txt_name, _ = os.path.splitext(self.tmpdir + geo_file) txt_name += "_gmsh.txt" txt_name = os.path.abspath(txt_name) gmsh_run = self.gmsh gmsh_run += " -tol {:.2f}".format(tol) gmsh_run += " " + geo_base gmsh_run += " -3 -o" gmsh_run += " {} -format stl".format(stl_name) gmsh_run += " -log {}".format(txt_name) os.chdir(geo_dir) gmsh_success = os.system(gmsh_run) os.chdir(self.root_dir) return stl_name def read_cadfile(self, fileName, disp=True): print(fileName) base_dir = os.path.dirname(fileName) basename = os.path.basename(fileName) rootname, extname = os.path.splitext(fileName) if extname in [".stp", ".step"]: shpe = read_step_file(fileName) elif extname in [".igs", ".iges"]: shpe = read_iges_file(fileName) elif extname in [".stl"]: shpe = read_stl_file(fileName) elif extname in [".brep"]: shpe = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shpe, fileName, builder) elif extname in [".geo"]: stlfile = self.import_geofile(fileName, 0.1) shpe = read_stl_file(stlfile) else: print("Incorrect file index") # sys.exit(0) if disp == True: self.display.DisplayShape(shpe, update=True) return shpe def import_cadfile(self): options = QFileDialog.Options() fileNames, _ = QFileDialog.getOpenFileNames( self.wi, 'QFileDialog.getOpenFileName()', '', 'CAD files (*.stp *.step *.stl *.igs *.iges, *.brep. *.geo)', options=options) for fileName in fileNames: print(fileName) self.read_cadfile(fileName, disp=True) self.export_cap() def export_cap(self): pngname = create_tempnum(self.rootname, self.tmpdir, ".png") self.display.View.Dump(pngname) def export_stp(self, shp): stpname = create_tempnum(self.rootname, self.tmpdir, ".stp") write_step_file(shp, stpname) def export_stp_selected(self): comp = self.make_comp_selcted() self.export_stp(comp) def export_stl_selected(self): comp = self.make_comp_selcted() stlname = create_tempnum(self.rootname, self.tmpdir, ".stl") write_stl_file(comp, stlname) def export_igs_selected(self): comp = self.make_comp_selcted() igsname = create_tempnum(self.rootname, self.tmpdir, ".stl") write_iges_file(comp, igsname) def export_brep_selected(self): comp = self.make_comp_selcted() brepname = create_tempnum(self.rootname, self.tmpdir, ".brep") breptools_Write(comp, brepname) def exit_win(self): self.wi.close() def show(self): self.display.FitAll() self.display.View.Dump(self.tempname + ".png") self.start_display()
class plotocc(SetDir): def __init__(self): self.display, self.start_display, self.add_menu, self.add_function = init_display( ) self.base_axs = gp_Ax3() SetDir.__init__(self) def show_box(self, axs=gp_Ax3(), lxyz=[100, 100, 100]): box = make_box(*lxyz) ax1 = gp_Ax3(gp_Pnt(-lxyz[0] / 2, -lxyz[1] / 2, -lxyz[2] / 2), gp_Dir(0, 0, 1)) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) trf.SetTransformation(ax1, gp_Ax3()) box.Location(TopLoc_Location(trf)) self.display.DisplayShape(axs.Location()) self.show_axs_pln(axs, scale=lxyz[0]) self.display.DisplayShape(box, transparency=0.7) def show_pnt(self, xyz=[0, 0, 0]): self.display.DisplayShape(gp_Pnt(*xyz)) def show_pts(self, pts=[gp_Pnt()], num=1): for p in pts[::num]: self.display.DisplayShape(p) self.display.DisplayShape(make_polygon(pts)) def show_ball(self, scale=100, trans=0.5): shape = BRepPrimAPI_MakeSphere(scale).Shape() self.display.DisplayShape(shape, transparency=trans) def show_vec(self, beam=gp_Ax3(), scale=1.0): pnt = beam.Location() vec = dir_to_vec(beam.Direction()).Scaled(scale) print(vec.Magnitude()) self.display.DisplayVector(vec, pnt) def show_ellipsoid(self, axs=gp_Ax3(), rxyz=[10., 10., 10.], trans=0.5): shape = gen_ellipsoid(axs, rxyz) self.display.DisplayShape(shape, transparency=trans, color="BLUE") return shape def show_axs_pln(self, axs=gp_Ax3(), scale=100): pnt = axs.Location() dx = axs.XDirection() dy = axs.YDirection() dz = axs.Direction() vx = dir_to_vec(dx).Scaled(1 * scale) vy = dir_to_vec(dy).Scaled(2 * scale) vz = dir_to_vec(dz).Scaled(3 * scale) pnt_x = pnt_trf_vec(pnt, vx) pnt_y = pnt_trf_vec(pnt, vy) pnt_z = pnt_trf_vec(pnt, vz) self.display.DisplayShape(pnt) self.display.DisplayShape(make_line(pnt, pnt_x), color="RED") self.display.DisplayShape(make_line(pnt, pnt_y), color="GREEN") self.display.DisplayShape(make_line(pnt, pnt_z), color="BLUE") def show_plane(self, axs=gp_Ax3(), scale=100): pnt = axs.Location() vec = dir_to_vec(axs.Direction()) pln = make_plane(pnt, vec, -scale, scale, -scale, scale) self.display.DisplayShape(pln) def make_EllipWire(self, rxy=[1.0, 1.0], shft=0.0, axs=gp_Ax3()): rx, ry = rxy if rx > ry: major_radi = rx minor_radi = ry axis = gp_Ax2() axis.SetXDirection(axis.XDirection()) else: major_radi = ry minor_radi = rx axis = gp_Ax2() axis.SetXDirection(axis.YDirection()) axis.Rotate(axis.Axis(), np.deg2rad(shft)) elip = make_edge(gp_Elips(axis, major_radi, minor_radi)) poly = make_wire(elip) poly.Location(set_loc(gp_Ax3(), axs)) return poly def make_PolyWire(self, num=6, radi=1.0, shft=0.0, axs=gp_Ax3(), skin=None): lxy = radi pnts = [] angl = 360 / num for i in range(num): thet = np.deg2rad(i * angl) + np.deg2rad(shft) x, y = radi * np.sin(thet), radi * np.cos(thet) pnts.append(gp_Pnt(x, y, 0)) pnts.append(pnts[0]) poly = make_polygon(pnts) poly.Location(set_loc(gp_Ax3(), axs)) n_sided = BRepFill_Filling() for e in Topo(poly).edges(): n_sided.Add(e, GeomAbs_C0) n_sided.Build() face = n_sided.Face() if skin == None: return poly elif skin == 0: return face else: solid = BRepOffset_MakeOffset(face, skin, 1.0E-5, BRepOffset_Skin, False, True, GeomAbs_Arc, True, True) return solid.Shape() def make_StarWire(self, num=5, radi=[2.0, 1.0], shft=0.0, axs=gp_Ax3(), skin=None): lxy = radi pnts = [] angl = 360 / num for i in range(num): a_thet = np.deg2rad(i * angl) + np.deg2rad(shft) ax, ay = radi[0] * np.sin(a_thet), radi[0] * np.cos(a_thet) pnts.append(gp_Pnt(ax, ay, 0)) b_thet = a_thet + np.deg2rad(angl) / 2 bx, by = radi[1] * np.sin(b_thet), radi[1] * np.cos(b_thet) pnts.append(gp_Pnt(bx, by, 0)) pnts.append(pnts[0]) poly = make_polygon(pnts) poly.Location(set_loc(gp_Ax3(), axs)) n_sided = BRepFill_Filling() for e in Topo(poly).edges(): n_sided.Add(e, GeomAbs_C0) n_sided.Build() face = n_sided.Face() if skin == None: return poly elif skin == 0: return face else: solid = BRepOffset_MakeOffset(face, skin, 1.0E-5, BRepOffset_Skin, False, True, GeomAbs_Arc, True, True) return solid.Shape() def make_FaceByOrder(self, pts=[]): pnt = [] for p in pts: pnt.append([p.X(), p.Y(), p.Z()]) pnt = np.array(pnt) cov = ConvexHull(pnt, qhull_options='QJ') #pts_ord = [] # print(cov) # print(cov.simplices) # print(cov.vertices) # for idx in cov.vertices: # print(idx, pnt[idx]) # pts_ord.append(gp_Pnt(*pnt[idx])) #poly = make_polygon(pts_ord) poly = make_polygon(pts) n_sided = BRepFill_Filling() for e in Topo(poly).edges(): n_sided.Add(e, GeomAbs_C0) n_sided.Build() face = n_sided.Face() return face def AddManipulator(self): self.manip = AIS_Manipulator(self.base_axs.Ax2()) ais_shp = self.display.DisplayShape(self.base_axs.Location(), update=True) self.manip.Attach(ais_shp) def SaveMenu(self): self.add_menu("File") self.add_function("File", self.export_cap) def export_cap(self): pngname = create_tempnum(self.rootname, self.tmpdir, ".png") self.display.View.Dump(pngname) def export_stp(self, shp): stpname = create_tempnum(self.rootname, self.tmpdir, ".stp") write_step_file(shp, stpname) def show(self): self.display.FitAll() self.display.View.Dump(self.tempname + ".png") self.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/>. """ The very first pythonocc example. This uses to be the script used to check the following points: pythonocc installation is correct, i.e. pythonocc modules are found and properly imported a GUI manager is installed. Wether it is wxpython or pyqt/pyside, it's necessary to display a 3d window the rendering window can be initialized and set up, that is to say the graphic driver and OpenGl works correctly. If this example run on your machine, that means you're ready to explore the wide pythonocc world and run all the other examples. """ from OCC.Display.SimpleGui import init_display from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox from OCC.Core.AIS import AIS_Manipulator display, start_display, add_menu, add_function_to_menu = init_display() my_box = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() display.View.TriedronErase() ais_shp = display.DisplayShape(my_box, update=True) manip = AIS_Manipulator() manip.Attach(ais_shp) start_display()