Пример #1
0
 def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
     self.gl = gl
     glut.glutInit(sys.argv)
     glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
     glut.glutInitWindowPosition(0, 0)
     glut.glutCreateWindow(b"BlitzLoop Karaoke")
     if not fullscreen:
         glut.glutReshapeWindow(width, height)
     else:
         glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
     BaseDisplay.__init__(self, width, height, fullscreen, aspect)
     self._on_reshape(width, height)
     if fullscreen:
         self.saved_size = (width, height)
         glut.glutFullScreen()
     glut.glutDisplayFunc(self._render)
     glut.glutIdleFunc(self._render)
     glut.glutReshapeFunc(self._on_reshape)
     glut.glutKeyboardFunc(self._on_keyboard)
     glut.glutSpecialFunc(self._on_keyboard)
     try:
         glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
         print("Using FreeGLUT mainloop return feature")
     except:
         pass
     self._initialize()
Пример #2
0
    def __init__(self):
        """
        Basic GLUT init and glut function definition.

        Notes
        -----
        `self.render_obj` is initialized here, which is then being used and drawn in `self.display`
        """

        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_RGBA | glut.GLUT_DOUBLE
                                 | glut.GLUT_DEPTH | glut.GLUT_MULTISAMPLE)
        glut.glutCreateWindow('Frightened Glut Rabbit')
        glut.glutReshapeWindow(Global.WIDTH, Global.HEIGHT)
        glut.glutReshapeFunc(self.reshape)
        glut.glutDisplayFunc(self.display)
        glut.glutKeyboardFunc(self.keyboard)
        glut.glutMouseFunc(self.glutMousePressEvent)
        glut.glutMotionFunc(self.glutMouseMoveEvent)
        glut.glutTimerFunc(Global.REFRESH_TIMER, self.onTimer,
                           Global.REFRESH_TIMER)

        self.buildProgram()

        self.reshape(Global.WIDTH, Global.HEIGHT)

        # set object to be rendered
        self.render_obj = default_obj()

        # For checking if need to swap
        self.standalone = True
Пример #3
0
    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 )
Пример #4
0
 def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
     self.gl = gl
     glut.glutInit(sys.argv)
     glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB
                              | glut.GLUT_DEPTH)
     glut.glutInitWindowPosition(0, 0)
     glut.glutCreateWindow(b"BlitzLoop Karaoke")
     if not fullscreen:
         glut.glutReshapeWindow(width, height)
     else:
         glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
     BaseDisplay.__init__(self, width, height, fullscreen, aspect)
     self._on_reshape(width, height)
     if fullscreen:
         self.saved_size = (width, height)
         glut.glutFullScreen()
     glut.glutDisplayFunc(self._render)
     glut.glutIdleFunc(self._render)
     glut.glutReshapeFunc(self._on_reshape)
     glut.glutKeyboardFunc(self._on_keyboard)
     glut.glutSpecialFunc(self._on_keyboard)
     try:
         glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                            glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
         print("Using FreeGLUT mainloop return feature")
     except:
         pass
     self._initialize()
Пример #5
0
    def toggle_fullscreen(self):
        if self.fullscreen:
            glut.glutReshapeWindow(*self.saved_size)
        else:
            self.saved_size = self.win_width, self.win_height
            glut.glutFullScreen()

        self.fullscreen = not self.fullscreen
Пример #6
0
    def toggle_fullscreen(self):
        if self.fullscreen:
            glut.glutReshapeWindow(*self.saved_size)
        else:
            self.saved_size = self.win_width, self.win_height
            glut.glutFullScreen()

        self.fullscreen = not self.fullscreen
Пример #7
0
 def init_glut(self):
     glut.glutInit()
     glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
     glut.glutCreateWindow('')
     glut.glutReshapeWindow(self.resolution[0], self.resolution[1])
     glut.glutReshapeFunc(self.reshape)
     glut.glutDisplayFunc(self.display)
     glut.glutKeyboardFunc(self.keyboard)
     glut.glutTimerFunc(0, self.timer, 0)
Пример #8
0
def init_glut():
    glut.glutInit()
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
    glut.glutCreateWindow('')
    glut.glutReshapeWindow(RESOLUTION[0], RESOLUTION[1])
    glut.glutReshapeFunc(reshape)
    glut.glutDisplayFunc(display)
    glut.glutKeyboardFunc(keyboard)
    glut.glutTimerFunc(0, timer, 0)
Пример #9
0
def main():
    glut.glutInit()
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
    glut.glutCreateWindow('Hello world!')
    glut.glutReshapeWindow(512, 512)
    glut.glutReshapeFunc(reshape)
    glut.glutDisplayFunc(display)
    glut.glutKeyboardFunc(keyboard)
    glut.glutMainLoop()
Пример #10
0
 def set_fullscreen(self, state):
     ''' Exit fullscreen mode '''
     self._fullscreen = state
     if state:
         self._saved_width  = glut.glutGet(glut.GLUT_WINDOW_WIDTH)
         self._saved_height = glut.glutGet(glut.GLUT_WINDOW_HEIGHT)
         glut.glutFullScreen()
     else:
         glut.glutReshapeWindow(self._saved_width, self._saved_height)
Пример #11
0
    def __init__(self, geos, vertex_code, fragment_code):
        self.time = time.time()
        num_vertices = np.sum([len(g) for g in geos])
        data = np.zeros(num_vertices, [("position", np.float32, 2),
                                       ("color", np.float32, 4)])
        cs = []
        vs = []
        for g in geos:
            for c in g.colors:
                cs.append(c)
            for v in g.vertices:
                vs.append(v)
        data["color"] = cs
        data["position"] = vs
        data["position"] = 0.5 * data["position"]
        self.data = data
        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
        glut.glutCreateWindow("Hello world!")
        glut.glutReshapeWindow(512, 512)
        glut.glutReshapeFunc(self.reshape)
        glut.glutDisplayFunc(self.display)
        glut.glutIdleFunc(self.idle)
        glut.glutKeyboardFunc(self.keyboard)
        glut.glutMouseFunc(self.mouse)

        program = gl.glCreateProgram()
        vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        gl.glShaderSource(vertex, vertex_code)
        gl.glShaderSource(fragment, fragment_code)
        gl.glCompileShader(vertex)
        gl.glCompileShader(fragment)
        gl.glAttachShader(program, vertex)
        gl.glAttachShader(program, fragment)
        gl.glLinkProgram(program)
        gl.glDetachShader(program, vertex)
        gl.glDetachShader(program, fragment)
        gl.glUseProgram(program)
        self.buffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.data.nbytes, self.data,
                        gl.GL_DYNAMIC_DRAW)
        stride = self.data.strides[0]
        offset = ctypes.c_void_p(0)
        loc = gl.glGetAttribLocation(program, "position")
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset)

        offset = ctypes.c_void_p(self.data.dtype["position"].itemsize)
        loc = gl.glGetAttribLocation(program, "color")
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glVertexAttribPointer(loc, 4, gl.GL_FLOAT, False, stride, offset)
        loc = gl.glGetUniformLocation(program, "scale")
        gl.glUniform1f(loc, 1.0)
Пример #12
0
    def __init__( self, width=256, height=256, title=None, visible=True, aspect=None,
                  decoration=True, fullscreen=False, config=None, context=None, color=(0,0,0,1), vsync=False):

        if vsync:
            log.warn('vsync not implemented for osxglut backend')

        if len(__windows__) > 0:
            log.critical(
                """OSXGLUT backend is unstable with more than one window.\n"""
                """Exiting...""")
            sys.exit(0)

        window.Window.__init__(self, width=width,
                                     height=height,
                                     title=title,
                                     visible=visible,
                                     aspect=aspect,
                                     decoration=decoration,
                                     fullscreen=fullscreen,
                                     config=config,
                                     context=context,
                                     color=color)

        if config is None:
            config = configuration.Configuration()
        set_configuration(config)

        self._native_window = glut.glutCreateWindow( self._title )
        if bool(glut.glutSetOption):
            glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                               glut.GLUT_ACTION_CONTINUE_EXECUTION)
            glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS,
                               glut.GLUT_ACTION_CONTINUE_EXECUTION)
        glut.glutWMCloseFunc( self._close )
        glut.glutDisplayFunc( self._display )
        glut.glutReshapeFunc( self._reshape )
        glut.glutKeyboardFunc( self._keyboard )
        glut.glutKeyboardUpFunc( self._keyboard_up )
        glut.glutMouseFunc( self._mouse )
        glut.glutMotionFunc( self._motion )
        glut.glutPassiveMotionFunc( self._passive_motion )
        glut.glutVisibilityFunc( self._visibility )
        glut.glutEntryFunc( self._entry )
        glut.glutSpecialFunc( self._special )
        glut.glutSpecialUpFunc( self._special_up )
        glut.glutReshapeWindow( self._width, self._height )
        if visible:
            glut.glutShowWindow()
        else:
            glut.glutHideWindow()

        # This ensures glutCheckLoop never blocks
        def on_idle(): pass
        glut.glutIdleFunc(on_idle)

        __windows__.append(self)
Пример #13
0
    def __init__(self, geos, vertex_code, fragment_code):
        self.time = time.time()
        num_vertices = np.sum([len(g) for g in geos])
        data = np.zeros(num_vertices, [("position", np.float32, 2),
                            ("color",    np.float32, 4)])
        cs = []
        vs = []
        for g in geos:
            for c in g.colors:
                cs.append(c)
            for v in g.vertices:
                vs.append(v)
        data["color"] = cs
        data["position"] = vs
        data["position"] = 0.5 * data["position"]
        self.data = data
        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
        glut.glutCreateWindow("Hello world!")
        glut.glutReshapeWindow(512,512)
        glut.glutReshapeFunc(self.reshape)
        glut.glutDisplayFunc(self.display)
        glut.glutIdleFunc(self.idle)
        glut.glutKeyboardFunc(self.keyboard)
        glut.glutMouseFunc(self.mouse)

        program  = gl.glCreateProgram()
        vertex   = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        gl.glShaderSource(vertex, vertex_code)
        gl.glShaderSource(fragment, fragment_code)
        gl.glCompileShader(vertex)
        gl.glCompileShader(fragment)
        gl.glAttachShader(program, vertex)
        gl.glAttachShader(program, fragment)
        gl.glLinkProgram(program)
        gl.glDetachShader(program, vertex)
        gl.glDetachShader(program, fragment)
        gl.glUseProgram(program)
        self.buffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.data.nbytes, self.data, gl.GL_DYNAMIC_DRAW)
        stride = self.data.strides[0]
        offset = ctypes.c_void_p(0)
        loc = gl.glGetAttribLocation(program, "position")
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset)

        offset = ctypes.c_void_p(self.data.dtype["position"].itemsize)
        loc = gl.glGetAttribLocation(program, "color")
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glVertexAttribPointer(loc, 4, gl.GL_FLOAT, False, stride, offset)
        loc = gl.glGetUniformLocation(program, "scale")
        gl.glUniform1f(loc, 1.0)
Пример #14
0
    def init(self):
        # Initialize display
        global global_init
        if not global_init:
            glut.glutInit()
            glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA
                                     | glut.GLUT_DEPTH | glut.GLUT_ALPHA)
            glut.glutCreateWindow(b'fbmatrix')
            global_init = True

        if self.preview or self.raw:
            glut.glutReshapeWindow(512, 512)
        elif self.emulate:
            glut.glutReshapeWindow(1024, 512)

        glut.glutReshapeFunc(lambda w, h: self.reshape(w, h))
        glut.glutDisplayFunc(lambda: self.display())
        glut.glutKeyboardFunc(lambda k, x, y: self.keyboard(k, x, y))

        # Primary offscreen framebuffer
        self.mainfbo = fbo.FBO(self.columns,
                               32,
                               mag_filter=gl.GL_NEAREST,
                               min_filter=gl.GL_NEAREST)

        # Initialize display shader
        layoutfile = 'layout.json'

        if self.displaytype == 'ws2811':
            self.signalgenerator = displays.ws2811.signalgenerator(
                layoutfile, supersample=self.supersample)
            self.signalgenerator.setTexture(self.mainfbo.getTexture())
        elif self.displaytype == 'hub75e':
            self.signalgenerator = displays.hub75e.signalgenerator(
                columns=self.columns,
                rows=self.rows,
                supersample=self.supersample,
                order=self.order,
                oe=self.oe,
                extract=self.extract)
            self.signalgenerator.setTexture(self.mainfbo.getTexture())

        # Emulation shader
        if self.emulate or self.preview:
            self.texquad = geometry.simple.texquad()
            self.texquad.setTexture(self.mainfbo.getTexture())

        # Tree emulator
        if self.emulate:
            self.tree = assembly.tree.tree(layoutfile)
            self.tree.setTexture(self.mainfbo.getTexture())

        # Render
        glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
        if not self.raw and not self.preview and not self.emulate:
            glut.glutFullScreen()
Пример #15
0
    def enable(self, app=None):
        """DEPRECATED since IPython 5.0

        Enable event loop integration with GLUT.

        Parameters
        ----------

        app : ignored
            Ignored, it's only a placeholder to keep the call signature of all
            gui activation methods consistent, which simplifies the logic of
            supporting magics.

        Notes
        -----

        This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
        integrate with terminal based applications like IPython. Due to GLUT
        limitations, it is currently not possible to start the event loop
        without first creating a window. You should thus not create another
        window but use instead the created one. See 'gui-glut.py' in the
        docs/examples/lib directory.
        
        The default screen mode is set to:
        glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
        """
        warn(
            "This function is deprecated since IPython 5.0 and will be removed in future versions.",
            DeprecationWarning,
            stacklevel=2)

        import OpenGL.GLUT as glut
        from IPython.lib.inputhookglut import glut_display_mode, \
                                              glut_close, glut_display, \
                                              glut_idle, inputhook_glut

        if GUI_GLUT not in self.manager.apps:
            glut.glutInit(sys.argv)
            glut.glutInitDisplayMode(glut_display_mode)
            # This is specific to freeglut
            if bool(glut.glutSetOption):
                glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                                   glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
            glut.glutCreateWindow(sys.argv[0])
            glut.glutReshapeWindow(1, 1)
            glut.glutHideWindow()
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        else:
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        self.manager.set_inputhook(inputhook_glut)
Пример #16
0
 def initAndRunDevice(templateGlutSystem):
     glut.glutInit()
     glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
     glut.glutCreateWindow(b'raVEngine_py')
     glut.glutReshapeWindow(512, 512)
     glut.glutReshapeFunc(reshape)
     glut.glutDisplayFunc(templateGlutSystem.display)
     glut.glutKeyboardFunc(keyboard)
     glut.glutMotionFunc(mouse)
     glut.glutIdleFunc(templateGlutSystem.combineUpdateAndDisplay)
     glut.glutMainLoop()
Пример #17
0
    def __init__(self,
                 width=256,
                 height=256,
                 title=None,
                 visible=True,
                 decoration=True,
                 fullscreen=False,
                 config=None,
                 context=None):

        if len(__windows__) > 0:
            log.critical(
                """OSXGLUT backend is unstable with more than one window.\n"""
                """Exiting...""")
            sys.exit(0)

        window.Window.__init__(self, width, height, title, visible, decoration,
                               fullscreen, config, context)

        if config is None:
            config = configuration.Configuration()
        set_configuration(config)

        self._native_window = glut.glutCreateWindow(self._title)
        if bool(glut.glutSetOption):
            glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                               glut.GLUT_ACTION_CONTINUE_EXECUTION)
            glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS,
                               glut.GLUT_ACTION_CONTINUE_EXECUTION)
        glut.glutWMCloseFunc(self._close)
        glut.glutDisplayFunc(self._display)
        glut.glutReshapeFunc(self._reshape)
        glut.glutKeyboardFunc(self._keyboard)
        glut.glutKeyboardUpFunc(self._keyboard_up)
        glut.glutMouseFunc(self._mouse)
        glut.glutMotionFunc(self._motion)
        glut.glutPassiveMotionFunc(self._passive_motion)
        glut.glutVisibilityFunc(self._visibility)
        glut.glutEntryFunc(self._entry)
        glut.glutSpecialFunc(self._special)
        glut.glutSpecialUpFunc(self._special_up)
        glut.glutReshapeWindow(self._width, self._height)
        if visible:
            glut.glutShowWindow()
        else:
            glut.glutHideWindow()

        # This ensures glutCheckLoop never blocks
        def on_idle():
            pass

        glut.glutIdleFunc(on_idle)

        __windows__.append(self)
Пример #18
0
    def _init_glut(self, time):

        if type(time) != bytes:
            raise TypeError

        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
        glut.glutCreateWindow(time)
        glut.glutReshapeWindow(700, 700)
        glut.glutReshapeFunc(self.set_window_size)
        glut.glutDisplayFunc(self._display)
        glut.glutKeyboardFunc(self._keyboard)
Пример #19
0
    def enable(self, app=None):
        """DEPRECATED since IPython 5.0

        Enable event loop integration with GLUT.

        Parameters
        ----------

        app : ignored
            Ignored, it's only a placeholder to keep the call signature of all
            gui activation methods consistent, which simplifies the logic of
            supporting magics.

        Notes
        -----

        This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
        integrate with terminal based applications like IPython. Due to GLUT
        limitations, it is currently not possible to start the event loop
        without first creating a window. You should thus not create another
        window but use instead the created one. See 'gui-glut.py' in the
        docs/examples/lib directory.
        
        The default screen mode is set to:
        glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
        """
        warn(
            "This function is deprecated since IPython 5.0 and will be removed in future versions.",
            DeprecationWarning,
            stacklevel=2,
        )

        import OpenGL.GLUT as glut
        from IPython.lib.inputhookglut import glut_display_mode, glut_close, glut_display, glut_idle, inputhook_glut

        if GUI_GLUT not in self.manager.apps:
            glut.glutInit(sys.argv)
            glut.glutInitDisplayMode(glut_display_mode)
            # This is specific to freeglut
            if bool(glut.glutSetOption):
                glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
            glut.glutCreateWindow(sys.argv[0])
            glut.glutReshapeWindow(1, 1)
            glut.glutHideWindow()
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        else:
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        self.manager.set_inputhook(inputhook_glut)
Пример #20
0
    def __init__(self, limit_fps=100, show_fps=True, window_name='GlutWindow', size=np.asarray([768, 512])):
        self.limit_fps = limit_fps
        self.show_fps = show_fps
        self.window_name = window_name
        self.window_size = size

        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
        glut.glutInitWindowPosition(*GlutWindow.allocate_window_position(self.window_size))
        self.window_handle = glut.glutCreateWindow(self.window_name)
        glut.glutReshapeWindow(*self.window_size)
        glut.glutReshapeFunc(self.reshape)
        glut.glutDisplayFunc(self.display)
        glut.glutKeyboardFunc(self.keyboard)
Пример #21
0
    def enable_glut(self, app=None):
        """ Enable event loop integration with GLUT.

        Parameters
        ----------

        app : ignored
            Ignored, it's only a placeholder to keep the call signature of all
            gui activation methods consistent, which simplifies the logic of
            supporting magics.

        Notes
        -----

        This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
        integrate with terminal based applications like IPython. Due to GLUT
        limitations, it is currently not possible to start the event loop
        without first creating a window. You should thus not create another
        window but use instead the created one. See 'gui-glut.py' in the
        docs/examples/lib directory.

        The default screen mode is set to:
        glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
        """

        import OpenGL.GLUT as glut  # @UnresolvedImport
        from pydev_ipython.inputhookglut import glut_display_mode, \
                                              glut_close, glut_display, \
                                              glut_idle, inputhook_glut

        if GUI_GLUT not in self._apps:
            argv = getattr(sys, 'argv', [])
            glut.glutInit(argv)
            glut.glutInitDisplayMode(glut_display_mode)
            # This is specific to freeglut
            if bool(glut.glutSetOption):
                glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                                   glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
            glut.glutCreateWindow(argv[0] if len(argv) > 0 else '')
            glut.glutReshapeWindow(1, 1)
            glut.glutHideWindow()
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        else:
            glut.glutWMCloseFunc(glut_close)
            glut.glutDisplayFunc(glut_display)
            glut.glutIdleFunc(glut_idle)
        self.set_inputhook(inputhook_glut)
        self._current_gui = GUI_GLUT
        self._apps[GUI_GLUT] = True
Пример #22
0
    def set_size(self, width, height):
        '''Resize the window.
        
        The behaviour is undefined if the window is not resizable, or if
        it is currently fullscreen.

        The window size does not include the border or title bar.

        :Parameters:
            `width` : int
                New width of the window, in pixels.
            `height` : int
                New height of the window, in pixels.

        '''
        glut.glutReshapeWindow(width,height)
Пример #23
0
    def setSize(self, width, height):
        '''
        The set_size() method requests the window manager to resize the window
        to the specified width and height as if the user had done so, obeying
        geometry constraints. Note you shouldn't assume the new window size is
        definitely the requested one afterward, because other entities (e.g. the user
        or window manager) could change it ssize again, and not all window
        managers honor requests to resize windows. 

        :param integer width:
            The new width of the window, in pixels.

        :param integer height:
            The new height of the window, in pixels.
        '''

        glut.glutReshapeWindow(width, height)
Пример #24
0
    def __init__( self, source, duration, width=250, height=100 ):
        self.source   = source
        self.duration = duration
        self.width    = width
        self.height   = height

        self.points = []

        GLUT.glutInit( sys.argv )
        GLUT.glutInitDisplayMode( GLUT.GLUT_DOUBLE )

        self.window = GLUT.glutCreateWindow( "fft!" )
        GLUT.glutReshapeWindow( width, height )

        GLUT.glutIdleFunc( self.idle )
        GLUT.glutDisplayFunc( self.display )

        self.framecount = 0
Пример #25
0
    def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
        self.gl = gl
        glut.glutInit(sys.argv)
        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
        glut.glutInitWindowPosition(0, 0)
        glut.glutCreateWindow(b"BlitzLoop Karaoke")
        if not fullscreen:
            glut.glutReshapeWindow(width, height)
        else:
            glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
        BaseDisplay.__init__(self, width, height, fullscreen, aspect)
        self._on_reshape(width, height)
        if fullscreen:
            self.saved_size = (width, height)
            glut.glutFullScreen()
        glut.glutDisplayFunc(self._render)
        glut.glutIdleFunc(self._render)
        glut.glutReshapeFunc(self._on_reshape)
        glut.glutKeyboardFunc(self._on_keyboard)
        glut.glutSpecialFunc(self._on_keyboard)

        self._initialize()
Пример #26
0
	def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
		self.kbd_handler = None
		self.win_width = width
		self.win_height = height
		glut.glutInit(sys.argv)
		glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
		glut.glutInitWindowPosition(0, 0)
		glut.glutCreateWindow("Karaoke")
		if not fullscreen:
			glut.glutReshapeWindow(width, height)
		else:
			glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
		self.win_width = width
		self.win_height = height
		self.set_aspect(aspect)
		self._on_reshape(width, height)
		if fullscreen:
			glut.glutFullScreen()
		glut.glutDisplayFunc(self._render)
		glut.glutIdleFunc(self._render)
		glut.glutReshapeFunc(self._on_reshape)
		glut.glutKeyboardFunc(self._on_keyboard)
		glut.glutSpecialFunc(self._on_keyboard)
Пример #27
0
    def set_window_size(self, width, height):
        """
        Изменение размеров окна

        (int, int) -> None

        Аргументы:
           width - Ширина окна
           height - Высота окна

        Возвращает: None
        """

        # Проверка аргументов
        if type(width) is not int or width < 0 or type(
                height) is not int or height < 0:
            return None

        self.window_width = width  # Установка ширины окна
        self.window_height = height  # Установка высоты окна

        GLUT.glutReshapeWindow(self.window_width,
                               self.window_height)  # Размер окна
Пример #28
0
 def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
     self.kbd_handler = None
     self.win_width = width
     self.win_height = height
     glut.glutInit(sys.argv)
     glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB
                              | glut.GLUT_DEPTH)
     glut.glutInitWindowPosition(0, 0)
     glut.glutCreateWindow("BlitzLoop Karaoke")
     if not fullscreen:
         glut.glutReshapeWindow(width, height)
     else:
         glut.glutSetCursor(glut.GLUT_CURSOR_NONE)
     self.win_width = width
     self.win_height = height
     self.set_aspect(aspect)
     self._on_reshape(width, height)
     if fullscreen:
         glut.glutFullScreen()
     glut.glutDisplayFunc(self._render)
     glut.glutIdleFunc(self._render)
     glut.glutReshapeFunc(self._on_reshape)
     glut.glutKeyboardFunc(self._on_keyboard)
     glut.glutSpecialFunc(self._on_keyboard)
Пример #29
0
    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()
from StandardShader import *
from AABBShader import *
import time
from copy import deepcopy
import keyboard

# Initialize GLUT ------------------------------------------------------------------|
from UnlitBlendShader import UnlitBlendShader

glut.glutInit()
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)

# Create a window
screen_size = glm.vec2(800, 600)
glut.glutCreateWindow("Put Window Title Here")
glut.glutReshapeWindow(int(screen_size.x), int(screen_size.y))

# Configure GL -----------------------------------------------------------------------|

# Enable depth test
gl.glEnable(gl.GL_DEPTH_TEST)
# Accept fragment if it closer to the camera than the former one
gl.glDepthFunc(gl.GL_LESS)

# This command is necessary in our case to load different type of image formats.
# Read more on https://www.khronos.org/opengl/wiki/Common_Mistakes under "Texture upload and pixel reads"
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)

# Creating Data Buffers -----------------------------------------------------------|

# With the ability of .obj file loading, all the data will be read from the files and bound to proper buffers
Пример #31
0
def glut_int_handler(signum, frame):
    # Catch sigint and print the defaultipyt   message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage

# Initialisation code
glut.glutInit( sys.argv )
glut.glutInitDisplayMode( glut_display_mode )
# This is specific to freeglut
if bool(glut.glutSetOption):
    glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                        glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
glut.glutCreateWindow( b'ipython' )
glut.glutReshapeWindow( 1, 1 )
glut.glutHideWindow( )
glut.glutWMCloseFunc( glut_close )
glut.glutDisplayFunc( glut_display )
glut.glutIdleFunc( glut_idle )


def inputhook(context):
    """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
Пример #32
0
 def gottaresize(self):
     GLUT.glutSetWindow(self.window)
     GLUT.glutReshapeWindow(self._width, self._height)
Пример #33
0
    phi += .5
    model = np.eye(4, dtype=np.float32)
    #rotate(model, theta, 0,0,1)
    rotate(model, phi, 0,1,0)
    program['model'] = model
    program2['model'] = model
    glut.glutTimerFunc(1000/fps, timer, fps)
    glut.glutPostRedisplay()


# Glut init
# --------------------------------------
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH)
glut.glutCreateWindow('Rotating Cube')
glut.glutReshapeWindow(1280,1024)
glut.glutReshapeFunc(reshape)
glut.glutKeyboardFunc(keyboard )
glut.glutDisplayFunc(display)
glut.glutTimerFunc(1000/60, timer, 60)

# Build cube data
# --------------------------------------
V = np.zeros(8, [("position", np.float32, 3)])
V["position"] = [[ 1, 1, 1], [-1, 1, 1], [-1,-1, 1], [ 1,-1, 1],
                 [ 1,-1,-1], [ 1, 1,-1], [-1, 1,-1], [-1,-1,-1]]

vertices = VertexBuffer(V)

I = [0,1,2, 0,2,3,  0,3,4, 0,4,5,  0,5,6, 0,6,1,
     1,6,7, 1,7,2,  7,4,3, 7,3,2,  4,7,6, 4,6,5]
Пример #34
0
    circles.append( center = p2, radius = 4, fg_color=(0.0,0.0,1.0,1.0) )
    circles.append( center = p3, radius = 4, fg_color=(0.0,0.0,1.0,1.0) )


# -----------------------------------------------------------------------------
if __name__ == '__main__':
    import sys
    import OpenGL.GLUT as glut

    from glagg import curve3_bezier, curve4_bezier
    from glagg import PathCollection, CircleCollection

    glut.glutInit(sys.argv)
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
    glut.glutCreateWindow("Cubic Bézier curves")
    glut.glutReshapeWindow(1000, 1000)
    glut.glutDisplayFunc(on_display)
    glut.glutReshapeFunc(on_reshape)
    glut.glutKeyboardFunc(on_keyboard)


    paths = PathCollection( )
    circles = CircleCollection()

    points = np.array( [ [ (100.,200.), (100.,300.), (400.,300.), (400.,200.) ],
                         [ (600.,200.), (675.,300.), (975.,300.), (900.,200.) ],
                         [ (100.,500.), ( 25.,600.), (475.,600.), (400.,500.) ],
                         [ (600.,500.), (600.,650.), (900.,350.), (900.,500.) ],
                         [ (100.,800.), (175.,900.), (325.,900.), (400.,800.) ],
                         [ (600.,800.), (625.,900.), (725.,900.), (750.,800.) ],
                         [ (750.,800.), (775.,700.), (875.,700.), (900.,800.) ] ] )
Пример #35
0
        else:   r = r2
        theta = np.pi/12 + 2*np.pi * i/float(n)
        x = r*np.cos(theta)
        y = r*np.sin(theta)
        points.append( [x,y])
    return np.array(points).reshape(n,2)


# -----------------------------------------------------------------------------
if __name__ == '__main__':
    from glagg import PathCollection

    glut.glutInit(sys.argv)
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB)
    glut.glutCreateWindow("OpenGL antialiased stars")
    glut.glutReshapeWindow(512, 512+32)
    glut.glutDisplayFunc(on_display)
    glut.glutReshapeFunc(on_reshape)
    glut.glutKeyboardFunc(on_keyboard)

    collection = PathCollection()
    s = star()
    radius = 255.0
    theta, dtheta = 0, 5.5/180.0*np.pi
    for i in range(500):
        theta += dtheta
        x = 256+radius*np.cos(theta)
        y = 256+32+radius*np.sin(theta)
        r = 10.1-i*0.02
        radius -= 0.45
        collection.append( s*r + (x,y), closed=True, linejoin='miter')
Пример #36
0
    gl.glViewport(0, 0, width, height)

def on_keyboard(key, x, y):
    if key == '\033': sys.exit()


if __name__ == '__main__':
    import sys
    import OpenGL.GLUT as glut
    from glagg import elliptical_arc, arc
    from glagg import PathCollection, CircleCollection

    glut.glutInit(sys.argv)
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
    glut.glutCreateWindow("Elliptical arcs")
    glut.glutReshapeWindow(800,450)
    glut.glutDisplayFunc(on_display)
    glut.glutReshapeFunc(on_reshape)
    glut.glutKeyboardFunc(on_keyboard)

    paths = PathCollection()
    circles = CircleCollection()
    rx,ry = 100, 50
    x1,y1 = 0,ry
    x2,y2 = rx,0
    def add_ellipses(tx,ty, large, sweep):
        vertices = arc(0, 0, rx, ry, 0, 2*math.pi, True)
        paths.append(vertices, translate=(tx,ty),
                     linewidth=.75, dash_pattern='loosely dashed')
        paths.append(vertices, translate=(tx+rx,ty+ry),
                     linewidth=.75, dash_pattern='loosely dashed')
    else:
        program['scale'] = 1, width / float(height)
    gl.glViewport(0, 0, width, height)


def keyboard(key, x, y):
    if key == '\033':
        sys.exit()


# Glut init
# --------------------------------------
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
glut.glutCreateWindow('Hello world!')
glut.glutReshapeWindow(256, 512)
glut.glutReshapeFunc(reshape)
glut.glutKeyboardFunc(keyboard)
glut.glutDisplayFunc(display)

# Build program & data
# ----------------------------------------
program = Program(vertex, fragment, count=4)
program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)]
program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
program['scale'] = 1.0, 1.0

# Enter mainloop
# --------------------------------------
glut.glutMainLoop()
Пример #38
0
	zoom = gl.glGetUniformLocation (program, 'zoom')
	gl.glProgramUniform1f (program, zoom, 0.75 + 0.25 * math.cos (timer.angle))
	
	angle = gl.glGetUniformLocation (program, 'angle')
	gl.glProgramUniform1f (program, angle, timer.angle / timer.maxGear)
	
	glut.glutTimerFunc (milliSecondsPerFrame, timer, None)
	glut.glutPostRedisplay ()
	
timer.angle = 0
timer.maxGear = 10
	
glut.glutInit ()
glut.glutInitDisplayMode (glut.GLUT_DOUBLE | glut.GLUT_RGBA)
glut.glutCreateWindow ('Vertex and fragment shaders')
glut.glutReshapeWindow (windowSize, windowSize)
glut.glutReshapeFunc (reshape)
glut.glutDisplayFunc (display)
glut.glutKeyboardFunc (keyboard)
glut.glutTimerFunc (0, timer, None)

	
# === Fill numpy data arrays

data = np.zeros (nrOfTriangles, dtype = [('position', np.float32, 2), ('color', np.float32, 3)])
data ['position'] = [(0, 0), (-1, -1), (-1, 1), (1, 1), (1, -1), (-1, -1)]
data ['color'] = [(1, 1, 1), (1, 1, 0), (1 , 0, 0), (0, 1 , 0), (0 , 0, 1), (1, 1, 0)]

# === Prepare program

# Get empty program and shaders
Пример #39
0
    def __init__(self):
        self.aspectRatio = 1
        self.angle = 0
        self.startTime = dt.datetime.now()

        # Initialize GLUT

        def display():
            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            gl.glDrawArrays(gl.GL_TRIANGLES, 0,
                            self.getSubjectVertices().shape[0])
            glut.glutSwapBuffers()

        def reshape(width, height):
            self.aspectRatio = float(width) / height
            gl.glViewport(0, 0, width, height)

        def keyboard(key, x, y):
            sys.exit()

        def setTransform():
            self.program.setUniform(
                'transformation',
                trf.getPerspMat(self.fieldOfViewY, self.aspectRatio,
                                self.zNearFarVec) * self.getPositionMat())

        def timer(dummy):
            setTransform()

            glut.glutTimerFunc(self.milliSecondsPerFrame, timer, None)
            glut.glutPostRedisplay()

        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA
                                 | glut.GLUT_DEPTH | glut.GLUT_MULTISAMPLE)
        glut.glutCreateWindow('Vertex and fragment shaders')
        glut.glutReshapeWindow(self.windowSize, self.windowSize)
        glut.glutReshapeFunc(reshape)
        glut.glutDisplayFunc(display)
        glut.glutKeyboardFunc(keyboard)
        glut.glutTimerFunc(0, timer, None)

        #gl.glEnable (gl.GL_LINE_SMOOTH)
        #gl.glEnable (gl.GL_BLEND);
        #gl.glEnable (gl.GL_MULTISAMPLE)
        # gl.glDepthFunc (gl.GL_LESS)
        gl.glClearColor(0.2, 0.2, 0.2, 1)
        gl.glEnable(gl.GL_DEPTH_TEST)
        #gl.glShadeModel (gl.GL_SMOOTH)
        #gl.glHint (gl.GL_LINE_SMOOTH_HINT, gl.GL_DONT_CARE)
        #gl.glBlendFunc (gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        # Initialize shaders

        self.program = prg.Program(
            prg.Shader(
                'vertex', '''
					uniform mat4 transformation;
					attribute vec3 position;
					attribute vec4 color;
					varying vec4 varyingColor;
					void main () {
						gl_Position = vec4 (transformation * vec4 (position, 1));
						varyingColor = color;
					}		
				'''),
            prg.Shader(
                'fragment', '''
					varying vec4 varyingColor;
					void main () {
						gl_FragColor = varyingColor;
					}
				'''),
        )

        # Set subject to be displayed

        self.program.setAttributes(self.getSubjectVertices())

        # Enter GLUT main loop

        glut.glutMainLoop()
Пример #40
0
    def __init__( self, size=None, position=None, title=None, fullscreen=False):
        '''
        Create a window with given sise, position and title.

        :param (int,int) size:
            Initial window size as (width,height) in pixels.

        :param (int,int) position:
            Initial window position. Depending on the window-manager, the
            position request may or may not be honored.

        :param string title:
           The title of the window.
        '''

        global _window

        window.Window.__init__( self, size, position, title )
        self._mouse_x = 0
        self._mouse_y = 0
        self._button = mouse.NONE
        self._modifiers = None
        self._time = None
        self._timer_stack = []
        self._timer_date = []
        self._title = title or sys.argv[0]
        self._fullscreen = -1

        # Is there any glut loop already running ?
        if glut.glutGetWindow( ) == 0:
            glut.glutInit( sys.argv )
            glut.glutInitDisplayMode( glut.GLUT_DOUBLE |
                                      glut.GLUT_RGBA   |
                                      glut.GLUT_DEPTH )
            self._interactive = False
        else:
            self._interactive = True

        self._id = glut.glutCreateWindow( self._title )
        glut.glutShowWindow( )

        glut.glutDisplayFunc( self._display )
        glut.glutReshapeFunc( self._reshape )
        glut.glutKeyboardFunc( self._keyboard )
        glut.glutKeyboardUpFunc( self._keyboard_up )
        glut.glutMouseFunc( self._mouse )
        glut.glutMotionFunc( self._motion )
        glut.glutPassiveMotionFunc( self._passive_motion )
        glut.glutVisibilityFunc( self._visibility )
        glut.glutEntryFunc( self._entry )
        glut.glutSpecialFunc( self._special )
        glut.glutSpecialUpFunc( self._special_up )

        if size is not None:
            width, height = size
            glut.glutReshapeWindow( width, height )
        width = glut.glutGet( glut.GLUT_WINDOW_WIDTH )
        height= glut.glutGet( glut.GLUT_WINDOW_HEIGHT )
        self._width = width
        self._height = height
        if position is not None:
            x,y = position
            glut.glutPositionWindow( x, y )
        #else:
        #    screen_width = glut.glutGet( glut.GLUT_SCREEN_WIDTH )
        #    screen_height= glut.glutGet( glut.GLUT_SCREEN_HEIGHT )
        #    x = (screen_width - self._size[0]) / 2
        #    y = (screen_width - self._size[0]) / 2
        #    glut.glutPositionWindow( x, y )
        x = glut.glutGet( glut.GLUT_WINDOW_X )
        y = glut.glutGet( glut.GLUT_WINDOW_X )
        self._x, self._y = x, y

        # These ones will be used when exiting fullscreen
        self._saved_width  = self._width
        self._saved_height = self._height
        self._saved_x = self._x
        self._saved_y = self._y

        self._time = glut.glutGet( glut.GLUT_ELAPSED_TIME )
        _window = self
        self._fullscreen = False
        if fullscreen:
            self.set_fullscreen(True)
Пример #41
0
    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()
Пример #42
0
 def window_resize(self, w, h):
     glut.glutReshapeWindow(w, h)
Пример #43
0

def timer(fps):
    galaxy.update(100000)  # in years !
    program['a_size'] = galaxy['size']
    glut.glutTimerFunc(1000 / fps, timer, fps)
    glut.glutPostRedisplay()


galaxy = Galaxy(35000)
galaxy.reset(13000, 4000, 0.0004, 0.90, 0.90, 0.5, 200, 300)

glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
glut.glutCreateWindow('Galaxy')
glut.glutReshapeWindow(800, 800)
glut.glutReshapeFunc(reshape)
glut.glutKeyboardFunc(keyboard)
glut.glutDisplayFunc(display)
glut.glutTimerFunc(1000 / 60, timer, 60)

program = gloo.Program(vertex, fragment, count=len(galaxy))
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
translate(view, 0, 0, -5)
program['u_model'] = model
program['u_view'] = view

from PIL import Image
image = Image.open("particle.bmp")
Пример #44
0
 def _vispy_set_size(self, w, h):
     # Set size of the widget or window
     glut.glutSetWindow(self._id)
     glut.glutReshapeWindow(w, h)
Пример #45
0
 def _vispy_set_size(self, w, h):
     # Set size of the widget or window
     glut.glutSetWindow(self._id)
     glut.glutReshapeWindow(w, h)
Пример #46
0
	_myProg = program

def reshape(width,height):
	gl.glViewport(0, 0, width, height)

def keyboard( key, x, y ):
	if key == '\033':
		sys.exit( )

if __name__=="__main__":
	# GLUT init
	# --------------------------------------
	glut.glutInit()
	glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
	glut.glutCreateWindow('Hello world!')
	glut.glutReshapeWindow(640,480)
	glut.glutReshapeFunc(reshape)
	glut.glutDisplayFunc(displayFunc)
	glut.glutKeyboardFunc(keyboard)

	program = common2d.init_shader_program()
	set_global_program(program)

	# Make program the default program
	gl.glUseProgram(program)

	# Enter mainloop
	# --------------------------------------
	glut.glutMainLoop()

if __name__ == '__main__': 
Пример #47
0
	gl.glBegin(gl.GL_QUADS)
	gl.glColor3f(0,1,1); gl.glVertex2f( 0.5,-0.5) 
	gl.glColor3f(1,0,1); gl.glVertex2f(-0.5,-0.5)
	gl.glColor3f(1,1,1); gl.glVertex2f(-0.5, 0.5)
	gl.glColor3f(1,0,0); gl.glVertex2f( 0.5, 0.5)
	gl.glEnd()  

	glut.glutSwapBuffers()
	#cetverokuti se popunjavaju aktivnom bojom

def reshape(width,height):
    gl.glViewport(0, 0, width, height)

def keyboard( key, x, y ):
    if key == 'a':
        sys.exit( )

glut.glutInit()

glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)

glut.glutCreateWindow('Moj sedmi prozor')

glut.glutReshapeWindow(550,550)
glut.glutReshapeFunc(reshape)

glut.glutDisplayFunc(display)
glut.glutKeyboardFunc(keyboard)

glut.glutMainLoop()
Пример #48
0
        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

    def on_keyboard(key, x, y):
        if key == '\033':
            sys.exit()

    glut.glutInit(sys.argv)
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA
                             | glut.GLUT_DEPTH)
    glut.glutCreateWindow("Freetype OpenGL")
    glut.glutReshapeWindow(240, 330)
    glut.glutDisplayFunc(on_display)
    glut.glutReshapeFunc(on_reshape)
    glut.glutKeyboardFunc(on_keyboard)

    font = TextureFont(atlas, './Vera.ttf', 9)
    text = "|... A Quick Brown Fox Jumps Over The Lazy Dog"
    labels = []
    x, y = 20, 310
    for i in range(30):
        labels.append(Label(text=text, font=font, x=x, y=y))
        x += 0.1000000000001
        y -= 10
    atlas.upload()
    shader = Shader(vert, frag)
    glut.glutMainLoop()
Пример #49
0
 def reshape(self, size):
     if (size != self._lastsize):
         glt.glutReshapeWindow(size, size)
         self._lastsize = size
Пример #50
0
    glut.glutPostRedisplay()


# -----------------------------------------------------------------------------
if __name__ == '__main__':
    import sys
    import OpenGL.GLUT as glut

    from glagg import curve4_bezier
    from glagg import PathCollection

    t0, frames = glut.glutGet(glut.GLUT_ELAPSED_TIME), 0
    glut.glutInit(sys.argv)
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
    glut.glutCreateWindow("Shapes")
    glut.glutReshapeWindow(800, 800)
    glut.glutDisplayFunc(on_display)
    glut.glutReshapeFunc(on_reshape)
    glut.glutKeyboardFunc(on_keyboard)
    glut.glutIdleFunc(on_idle)

    collection = PathCollection()
    def heart():
        vertices = curve4_bezier( (0.0,-0.5), (0.75,+0.25), (.75,+1.0), (0.0,+0.5) )
        n = len(vertices)
        V = np.zeros((2*n,2))
        V[:n] = vertices
        V[n:] = vertices[::-1]
        V[n:,0] *=-1
        V[n:,0] -= .0001
        return V
Пример #51
0
    def __init__(self, size=None, position=None, title=None, fullscreen=False,enableAlpha=True,pointSize=2):
        '''
        Constructor
        '''
        self._mouse_x = 0
        self._mouse_y = 0
        self._button = mouse.NONE
        self._modifiers = None
        self._motionEventCounter=0
        self._time = None
        self._timer_stack = []
        self._timer_date = []
        self._title = title or "PyGLer" # FIXME: get default name from a central location 
        self._fullscreen = -1
        
        self.dragSensitivity = 5
        
        # Is there any glut loop already running ?
        if glut.glutGetWindow( ) == 0:
            glut.glutInit()
            glut.glutInitDisplayMode( glut.GLUT_DOUBLE |
                                      glut.GLUT_RGBA   |
                                      glut.GLUT_DEPTH )
            self._interactive = False
        else:
            self._interactive = True
            
        self._id = glut.glutCreateWindow( self._title )
        glut.glutShowWindow()        
        
        glut.glutDisplayFunc( self.redraw )
        glut.glutReshapeFunc( self._reshape )
        glut.glutKeyboardFunc( self._keyboard )
        glut.glutKeyboardUpFunc( self._keyboard_up )
        glut.glutMouseFunc( self._mouse )
        glut.glutMotionFunc( self._motion )
        glut.glutPassiveMotionFunc( self._passive_motion )
        glut.glutVisibilityFunc( self._visibility )
        glut.glutEntryFunc( self._entry )
        glut.glutSpecialFunc( self._special )
        glut.glutSpecialUpFunc( self._special_up )   
            
        GL.glEnable(GL.GL_DEPTH_TEST)
        
        GL.glEnable(GL.GL_BLEND)
        if enableAlpha:
            GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
        
        GL.glPolygonOffset(1, 1);
        GL.glEnable(GL.GL_POLYGON_OFFSET_FILL);

        GL.glPointSize(pointSize)
        GL.glEnable(GL.GL_PROGRAM_POINT_SIZE)
            
        if size is not None:
            width, height = size
            glut.glutReshapeWindow( width, height )

        width = glut.glutGet( glut.GLUT_WINDOW_WIDTH )
        height= glut.glutGet( glut.GLUT_WINDOW_HEIGHT )
        self._width = width
        self._height = height
        if position is not None:
            x,y = position
            glut.glutPositionWindow( x, y )
            
        x = glut.glutGet( glut.GLUT_WINDOW_X )
        y = glut.glutGet( glut.GLUT_WINDOW_X )
        self._x, self._y = x, y

        # These ones will be used when exiting fullscreen
        self._saved_width  = self._width
        self._saved_height = self._height
        self._saved_x = self._x
        self._saved_y = self._y

        self._time = glut.glutGet( glut.GLUT_ELAPSED_TIME )
        self._fullscreen = fullscreen
        if fullscreen:
            self.set_fullscreen(True)
Пример #52
0
 def set_size(self, width, height):
     self.activate()
     glut.glutReshapeWindow(width, height)
Пример #53
0
    def on_reshape( width, height ):
        gl.glViewport( 0, 0, width, height )
        gl.glMatrixMode( gl.GL_PROJECTION )
        gl.glLoadIdentity( )
        gl.glOrtho( 0, width, 0, height, -1, 1 )
        gl.glMatrixMode( gl.GL_MODELVIEW )
        gl.glLoadIdentity( )

    def on_keyboard( key, x, y ):
        if key == '\033':
            sys.exit( )

    glut.glutInit( sys.argv )
    glut.glutInitDisplayMode( glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH )
    glut.glutCreateWindow( "Freetype OpenGL" )
    glut.glutReshapeWindow( 240, 330 )
    glut.glutDisplayFunc( on_display )
    glut.glutReshapeFunc( on_reshape )
    glut.glutKeyboardFunc( on_keyboard )

    font = TextureFont(atlas, './Vera.ttf', 9)
    text = "|... A Quick Brown Fox Jumps Over The Lazy Dog"
    labels = []
    x,y = 20,310
    for i in range(30):
        labels.append(Label(text=text, font=font, x=x, y=y))
        x += 0.1000000000001
        y -= 10
    atlas.upload()
    shader = Shader(vert,frag)
    glut.glutMainLoop( )
'''
Minimal example with OpenGL, the 'hard' way from Rougier's online book:
http://www.labri.fr/perso/nrougier/python-opengl/#the-hard-way

Shows how to use glut to open a GL context and draw an empty window.
'''

import sys
import OpenGL.GL as gl
import OpenGL.GLUT as glut

def display():
    glut.glutSwapBuffers()

def reshape(width,height):
    gl.glViewport(0, 0, width, height)

def keyboard( key, x, y ):
    if key == b'\x1b':
        sys.exit( )

glut.glutInit()  #create a gl context -- you won't have access to any GL commands before this
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)  #initial display mode double buffer/rgba color model
glut.glutCreateWindow(b'Hello world!')  #b because https://stackoverflow.com/a/27154196/1886357
glut.glutReshapeWindow(512,512)
glut.glutReshapeFunc(reshape)
glut.glutDisplayFunc(display)
glut.glutKeyboardFunc(keyboard)  #callback -> esc will close window
glut.glutMainLoop()
Пример #55
0
def reshape(width, height):
    gl.glViewport(0, 0, width, height)


def keyboard(key, x, y):
    if key == '\033':
        sys.exit()


if __name__ == "__main__":
    # GLUT init
    # --------------------------------------
    glut.glutInit()
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
    glut.glutCreateWindow('Hello world!')
    glut.glutReshapeWindow(640, 480)
    glut.glutReshapeFunc(reshape)
    glut.glutDisplayFunc(displayFunc)
    glut.glutKeyboardFunc(keyboard)

    program = common2d.init_shader_program()
    set_global_program(program)

    # Make program the default program
    gl.glUseProgram(program)

    # Enter mainloop
    # --------------------------------------
    glut.glutMainLoop()

if __name__ == '__main__':
Пример #56
0
 def set_size(self, width, height):
     self.activate()
     glut.glutReshapeWindow(width, height)
Пример #57
0
def glut_int_handler(signum, frame):
    # Catch sigint and print the defaultipyt   message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage

# Initialisation code
glut.glutInit( sys.argv )
glut.glutInitDisplayMode( glut_display_mode )
# This is specific to freeglut
if bool(glut.glutSetOption):
    glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
                        glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
glut.glutCreateWindow( b'ipython' )
glut.glutReshapeWindow( 1, 1 )
glut.glutHideWindow( )
glut.glutWMCloseFunc( glut_close )
glut.glutDisplayFunc( glut_display )
glut.glutIdleFunc( glut_idle )


def inputhook(context):
    """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