def mouse_motion(self, x, y): glut.glutSetWindow(self.window_handle) old_x = self.mouse_x old_y = self.mouse_y dx = 2 * (x - old_x) / self.window_width dy = 2 * (old_y - y) / self.window_height aspect_ratio = self.window_width / self.window_height if self.mouse_button == glut.GLUT_LEFT_BUTTON: if self.mouse_state == glut.GLUT_DOWN: self.trans["x"] += dx * ZOOM_FACTOR * aspect_ratio self.trans["y"] += dy * ZOOM_FACTOR glut.glutPostRedisplay() if self.mouse_state == glut.GLUT_UP: pass if self.mouse_button == glut.GLUT_RIGHT_BUTTON: if self.mouse_state == glut.GLUT_DOWN: self.rot["y"] -= 90 * dx self.rot["x"] -= 90 * dy # self.rotate['y'] -= 5 * dx # self.rotate['x'] -= 5 * dy glut.glutPostRedisplay() if self.mouse_state == glut.GLUT_UP: pass if self.mouse_button == glut.GLUT_MIDDLE_BUTTON: if self.mouse_state == glut.GLUT_DOWN: pass if self.mouse_state == glut.GLUT_UP: pass self.mouse_x = x self.mouse_y = y
def _vispy_set_visible(self, visible): # Show or hide the window or widget glut.glutSetWindow(self._id) if visible: glut.glutShowWindow() else: glut.glutHideWindow()
def __init__(self, *args, **kwargs): BaseCanvasBackend.__init__(self) title, size, show, position = self._process_backend_kwargs(kwargs) glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) self._vispy_canvas_ = None if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow()
def setFullscreen(self, state): ''' If **state** is True, the set_fullscreen() method requests the window manager to place the window in the fullscreen state. If **state** is False the set_fullscreen() method requests the window manager to toggle off the fullscreen state for the window. Note that in any case, you shouldn't not assume the window state is definitely set afterward, because other entities (e.g. the user or window manager) could fullscreen/unfullscreen it again, and not all window managers honor requests to fullscreen windows. :param bool state: Fullscreen state to be set. ''' if self._fullscreen == state: return if state == True: glut.glutSetWindow( self._id ) self._saved_width = glut.glutGet(glut.GLUT_WINDOW_WIDTH) self._saved_height = glut.glutGet(glut.GLUT_WINDOW_HEIGHT) self._saved_x = glut.glutGet(glut.GLUT_WINDOW_X) self._saved_y = glut.glutGet(glut.GLUT_WINDOW_Y) self._fullscreen = True glut.glutFullScreen() else: self._fullscreen = False glut.glutSetWindow( self._id ) glut.glutReshapeWindow(self._saved_width, self._saved_height) glut.glutPositionWindow( self._saved_x, self._saved_y ) glut.glutSetWindowTitle( self._title )
def _vispy_get_geometry(self): # Should return widget (x, y, w, h) glut.glutSetWindow(self._id) x = glut.glutGet(glut.GLUT_WINDOW_X) y = glut.glutGet(glut.GLUT_WINDOW_Y) w = glut.glutGet(glut.GLUT_WINDOW_WIDTH) h = glut.glutGet(glut.GLUT_WINDOW_HEIGHT) return x, y, w, h
def show_event(self, ps): if not self.exitgl: if not self.is_initialized: self.initialize() self.set_particle_system(ps) glut.glutMainLoopEvent() glut.glutSetWindow(self.window_handle) glut.glutPostRedisplay()
def show(self): ''' The show() method causes a window to be displayed as soon as possible. ''' glut.glutSetWindow( self._id ) glut.glutShowWindow() self.dispatch_event('on_show')
def hide(self): ''' The hide() method reverses the effects of the show() method, causing the window to be hidden (removed from the display). ''' glut.glutSetWindow( self._id ) glut.glutHideWindow() self.dispatch_event('on_hide')
def _close(self): __windows__.remove(self) # WARNING: This does not work on OSX 10.9 (seg fault or bus error) # glut.glutDestroyWindow(self._native_window) glut.glutSetWindow(self._native_window) glut.glutHideWindow() for i in range(len(self._timer_stack)): handler, interval = self._timer_stack[i] self._clock.unschedule(handler) self.dispatch_event("on_close")
def __init__(self, *args, **kwargs): BaseCanvasBackend.__init__(self, *args) title, size, position, show, vsync, resize, dec, fs, parent, context, \ = self._process_backend_kwargs(kwargs) self._initialized = False # Deal with context if not context.istaken: context.take('glut', self) _set_config(context.config) else: raise RuntimeError('Glut cannot share contexts.') glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) if fs is not False: self._fullscreen = True self._old_size = size if fs is not True: logger.warning('Cannot specify monitor for glut fullscreen, ' 'using default') glut.glutFullScreen() else: self._fullscreen = False # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow() # Init self._initialized = True self._vispy_set_current() self._vispy_canvas.events.initialize()
def getPosition(self): ''' The get_position() method returns the current posiiton of the window. :rtype: (int, int) :return: The current window coordinates, in pixels. ''' glut.glutSetWindow( self._id ) self._x = glut.glutGet( glut.GLUT_WINDOW_X ) self._y = glut.glutGet( glut.GLUT_WINDOW_Y ) return self._x, self._y
def show_fps(self, secs=0.0): elapsed_time = self.timer.elapsed() if elapsed_time < secs: self.frame_count += 1 else: fmt = "{0}: {1:.1f} fps @ {2} x {3}" win_title = fmt.format( WINDOW_TITLE_PREFIX, self.frame_count / elapsed_time, self.window_width, self.window_height ) glut.glutSetWindow(self.window_handle) glut.glutSetWindowTitle(win_title) self.frame_count = 0 self.timer.start()
def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
def getSize(self): ''' The get_size() methods returns the current size of the window and does not include the size of the window manager decorations (aka the window frame or border). :rtype: (int, int) :return: The width and height of the window, in pixels. ''' glut.glutSetWindow( self._id ) self._width = glut.glutGet( glut.GLUT_WINDOW_WIDTH ) self._height = glut.glutGet( glut.GLUT_WINDOW_HEIGHT ) return self._width, self._height
def mouse(self, button, state, x, y): global ZOOM_FACTOR glut.glutSetWindow(self.window_handle) self.mouse_button = button self.mouse_state = state self.mouse_x = x self.mouse_y = y if button == 3: ZOOM_FACTOR /= 1.03125 glut.glutPostRedisplay() if button == 4: ZOOM_FACTOR *= 1.03125 glut.glutPostRedisplay()
def keyboard_s(self, key, x, y): mkey = glut.glutGetModifiers() if mkey == glut.GLUT_ACTIVE_CTRL: pass elif mkey == glut.GLUT_ACTIVE_ALT: pass else: if key == glut.GLUT_KEY_UP: self.rotate["x"] += 1 elif key == glut.GLUT_KEY_DOWN: self.rotate["x"] -= 1 elif key == glut.GLUT_KEY_LEFT: self.rotate["y"] -= 1 elif key == glut.GLUT_KEY_RIGHT: self.rotate["y"] += 1 glut.glutSetWindow(self.window_handle) glut.glutPostRedisplay()
def setTitle(self, title): ''' The set_title() method sets the "title" property of the Window to the value specified by title. The title of a window will be displayed in its title bar. On the X Window System, the title bar is rendered by the window manager, so exactly how the title appears to users may vary according to a user's exact configuration. The title should help a user distinguish this window from other windows they may have open. A good title might include the application name and current document filename. :param string title: the title of the window. ''' glut.glutSetWindow( self._id ) glut.glutSetWindowTitle( title ) self._title = title
def _set_close_fun(id_, fun): # Set close function. See issue #10. For some reason, the function # can still not exist even if we checked its boolean status. glut.glutSetWindow(id_) closeFuncSet = False if bool(glut.glutWMCloseFunc): # OSX specific test try: glut.glutWMCloseFunc(fun) closeFuncSet = True except OpenGL.error.NullFunctionError: pass if not closeFuncSet: try: glut.glutCloseFunc(fun) closeFuncSet = True except OpenGL.error.NullFunctionError: pass
def __init__(self, **kwargs): BaseCanvasBackend.__init__(self, capability, SharedContext) title, size, position, show, vsync, resize, dec, fs, context = \ self._process_backend_kwargs(kwargs) _set_config(context) glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) if fs is not False: if isinstance(fs, int): logger.warn('Cannot specify monitor for glut fullscreen, ' 'using default') glut.glutFullScreen() # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) self._vispy_canvas_ = None if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow()
def get_position(self): glut.glutSetWindow(self._native_window) self._x = glut.glutGet(glut.GLUT_WINDOW_W) self._y = glut.glutGet(glut.GLUT_WINDOW_Y) return self._x, self._y
def gottasettitle(self): GLUT.glutSetWindow(self.window) GLUT.glutSetWindowTitle(self._title)
def _vispy_set_current(self): # Make this the current context self._vispy_canvas.set_current() # Mark as current glut.glutSetWindow(self._id)
def mouse_button_handler(self, button, state, x, y): if button == GLUT.GLUT_RIGHT_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("RMB up: forward={}\n up={}\n".format(self._forward, self._up)) # sys.stderr.write(" θ={:.2f}, φ={:.2f}, upθ={:.2f}, upφ={:.2f}\n" # .format(self._theta, self._phi, self._uptheta, self._upphi)) GLUT.glutMotionFunc(None) elif state == GLUT.GLUT_DOWN: # sys.stderr.write("RMB down\n") self._mousex0 = x self._mousey0 = y self._origtheta = math.acos( -self._forward[1] / math.sqrt(self._forward[0]**2 + self._forward[1]**2 + self._forward[2]**2)) self._origphi = math.atan2(-self._forward[0], -self._forward[2]) # sys.stderr.write("origθ = {:.2f}, origφ = {:.2f}\n".format(self._origtheta, self._origphi)) GLUT.glutMotionFunc(lambda x, y: self.rmb_moved(x, y)) if button == GLUT.GLUT_MIDDLE_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("MMB up\n") GLUT.glutMotionFunc(None) elif state == GLUT.GLUT_DOWN: # sys.stderr.write("MMB down\n") self._mousex0 = x self._mousey0 = y self._origrange = self._range GLUT.glutMotionFunc(lambda x, y: self.mmb_moved(x, y)) if button == GLUT.GLUT_LEFT_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("LMB up: self._center={}\n".format(self._center)) GLUT.glutMotionFunc(None) if state == GLUT.GLUT_DOWN: # sys.stderr.write("LMB down\n") keys = GLUT.glutGetModifiers() if keys & GLUT.GLUT_ACTIVE_SHIFT: self._mouseposx0 = x self._mouseposy0 = y self._origcenter = self._center self._upinscreen = self._up - self._forward * ( numpy.sum(self._up * self._forward) / math.sqrt( self._up[0]**2 + self._up[1]**2 + self._up[2]**2)) self._upinscreen /= math.sqrt(self._upinscreen[0]**2 + self._upinscreen[1]**2 + self._upinscreen[2]**2) self._rightinscreen = numpy.array([ self._forward[1] * self._upinscreen[2] - self._forward[2] * self._upinscreen[1], self._forward[2] * self._upinscreen[0] - self._forward[0] * self._upinscreen[2], self._forward[0] * self._upinscreen[1] - self._forward[1] * self._upinscreen[0] ]) self._rightinscreen /= math.sqrt( self._rightinscreen[0]**2 + self._rightinscreen[1]**2 + self._rightinscreen[2]**2) GLUT.glutMotionFunc(lambda x, y: self.lmb_moved(x, y)) if (state == GLUT.GLUT_UP) and (button == 3 or button == 4): # wheel up/down GLUT.glutSetWindow(self.window) if button == 3: self._range *= 0.9 else: self._range *= 1.1 self.update_cam_posrot_gl()
def activate(self): glut.glutSetWindow(self._native_window)
def _vispy_set_position(self, x, y): # Set position of the widget or window. May have no effect for widgets glut.glutSetWindow(self._id) glut.glutPositionWindow(x, y)
def _vispy_set_size(self, w, h): # Set size of the widget or window glut.glutSetWindow(self._id) glut.glutReshapeWindow(w, h)
def _vispy_swap_buffers(self): # Swap front and back buffer glut.glutSetWindow(self._id) glut.glutSwapBuffers()
def _vispy_set_current(self): # Make this the current context glut.glutSetWindow(self._id)
def _vispy_get_size(self): glut.glutSetWindow(self._id) w = glut.glutGet(glut.GLUT_WINDOW_WIDTH) h = glut.glutGet(glut.GLUT_WINDOW_HEIGHT) return w, h
def _vispy_set_title(self, title): # Set the window title. Has no effect for widgets glut.glutSetWindow(self._id) glut.glutSetWindowTitle(title)
def gottaresize(self): GLUT.glutSetWindow(self.window) GLUT.glutReshapeWindow(self._width, self._height)
def keyboard(self, key, x, y): global ALPHA global COLORMAP global CONTRAST global FULLSCREEN global POINT_SIZE global RECORDSCREEN global TRACEORBITS global ZOOM_FACTOR (ps_min, ps_max) = gl.glGetFloatv(gl.GL_ALIASED_POINT_SIZE_RANGE) if key == ' ': self.rotate['x'] = 0 self.rotate['y'] = 0 self.rotate['z'] = 0 elif key == '+': POINT_SIZE += 1 if POINT_SIZE > ps_max: POINT_SIZE = ps_max elif key == '-': POINT_SIZE -= 1 if POINT_SIZE < ps_min: POINT_SIZE = ps_min elif key == '<': self.rotate['z'] -= 1 elif key == '>': self.rotate['z'] += 1 elif key in '0123456789': COLORMAP = int(key) elif key == 'a': ALPHA /= 1.03125 if ALPHA < 0.0: ALPHA = 0.0 elif key == 'A': ALPHA *= 1.03125 if ALPHA > 1.0: ALPHA = 1.0 elif key == 'c': CONTRAST *= 1.015625 if CONTRAST > 256.0: CONTRAST = 256.0 elif key == 'C': CONTRAST /= 1.015625 if CONTRAST < 0.0625: CONTRAST = 0.0625 elif key == 'r': if not COLORMASK['r']: COLORMASK['r'] = True COLORMASK['g'] = False COLORMASK['b'] = False else: COLORMASK['r'] = False elif key == 'g': if not COLORMASK['g']: COLORMASK['r'] = False COLORMASK['g'] = True COLORMASK['b'] = False else: COLORMASK['g'] = False elif key == 'b': if not COLORMASK['b']: COLORMASK['r'] = False COLORMASK['g'] = False COLORMASK['b'] = True else: COLORMASK['b'] = False elif key == 'Z': ZOOM_FACTOR *= 1.03125 elif key == 'z': ZOOM_FACTOR /= 1.03125 elif key == 'o' or key == 'O': if not TRACEORBITS: TRACEORBITS = True else: TRACEORBITS = False elif key == 'f' or key == 'F': if not FULLSCREEN: glut.glutFullScreen() FULLSCREEN = True else: glut.glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT) FULLSCREEN = False elif key == 's' or key == 'S': if not RECORDSCREEN: RECORDSCREEN = True else: RECORDSCREEN = False elif key == ESCAPE: self.exitgl = True glut.glutLeaveMainLoop() glut.glutHideWindow() glut.glutSetWindow(self.window_handle) glut.glutPostRedisplay()
def _vispy_set_title(self, title): # Set the window title. Has no effect for widgets glut.glutSetWindow(self._id) glut.glutSetWindowTitle(title.encode('ASCII'))
def _vispy_update(self): # Invoke a redraw glut.glutSetWindow(self._id) glut.glutPostRedisplay()
def _vispy_get_position(self): glut.glutSetWindow(self._id) x = glut.glutGet(glut.GLUT_WINDOW_X) y = glut.glutGet(glut.GLUT_WINDOW_Y) return x, y