def main():
    global vertices, window_height, window_width, to_redraw

    if not glfw.init():
        return

    window = glfw.create_window(400, 400, "Lab4", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)

    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)
    glClearColor(0, 0, 0, 0)

    while not glfw.window_should_close(window):
        # print(vertices)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        draw()

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.destroy_window(window)
    glfw.terminate()
def main():
    init()

    window = create_window(500, 500, "Hi", None, None)
    make_context_current(window)
    initial_setup()
    colors = {
        "front": (1, 0, 0),
        "back": (0, 1, 0),
        "left": (1, 1, 0),
        "right": (1, 0, 1),
        "up": (0, 0, 1),
        "down": (0, 1, 1),
    }
    glClearColor(1, 1, 1, 1)
    glEnable(GL_DEPTH_TEST)
    set_lightning()
    while not window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glRotate(1, 0, 1, 0)
        draw_cube(0, 0, 0, 5, colors)
        swap_buffers(window)
        poll_events()

    terminate()
Example #3
0
File: main.py Project: Tofs/Pygel
def mainLoop(mainLoopObject, window):
    VAO = mainLoopObject["VAO"]
    i = mainLoopObject["Indexs"]
    VertexCount = mainLoopObject["VertexCount"]
    pos = mainLoopObject["VertexBuffer"]
    shaderProgram = mainLoopObject["ShaderProgram"]

    glEnableVertexAttribArray(0)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        glClearColor(0.1, 0.1, 0.5, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        transMatrix = glGetUniformLocation(shaderProgram, "transMatrix")
        glUseProgram(shaderProgram)

        glUniformMatrix4fv(transMatrix, 1, GL_TRUE, Matrix.translate(0.5 , 0.0 , 0))

        glBindVertexArray(VAO)
        glBindBuffer(GL_ARRAY_BUFFER, pos)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i)
        # draw triangle using index
        glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, ctypes.c_void_p(0))

        # Swap front and back buffers
        glfw.swap_buffers(window)

        glfw.poll_events()
        glBindVertexArray(0)
        glUseProgram(0)
Example #4
0
def main():
    global angles, angley, anglez, scale, carcass, sphere
    if not glfw.init():
        return
    window = glfw.create_window(640, 640, "Lab2", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)
    glfw.set_window_pos_callback(window, drag_callback)
    l_cube = Cube(0, 0, 0, 1)
    # r_cube = Cube(0, 0, 0, 1)
    sphere.recount(parts)
    while not glfw.window_should_close(window):
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        set_projection()
        glLoadIdentity()
        sphere.draw(scale, angles, [0.3, 0.0, 0.4], carcass)
        # r_cube.draw(scale, angles, [0.3, 0.2, 0.4], carcass)
        l_cube.draw(0.5, [0, 0, 0], [-0.5, 0.0, -0.25], False)
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.destroy_window(window)
    glfw.terminate()
Example #5
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640, 480, "ラララ", None, None)
    if not window:
        glfw.terminate()
        return

    #init
    glfw.make_context_current(window)
    gluOrtho2D(0.0, 640, 0.0, 480) #where is this in glfw?

    # loop
    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        randomWidth()
    
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(440.0, 400.0, 540.0, 400.0)
        drawLine(320.0, 350.0, 320.0, 330.0)
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(300.0, 200.0, 340.0, 200.0)
        
        glfw.swap_buffers(window)
        glfw.poll_events()
        glfw.swap_interval(2)
    glfw.terminate()
Example #6
0
def main():
    global R, T
    if not glfw.init(): return
    window = glfw.create_window(480, 480, "2015004584", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)
    glfw.swap_interval(0)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        clear()
        axis()

        glMultMatrixf(R.T)
        glMultMatrixf(T.T)
        render()

        glfw.swap_buffers(window)

    glfw.terminate()
Example #7
0
    def run(self):
        # initializer timer
        glfw.set_time(0.0)
        t = 0.0
        while not glfw.window_should_close(self.win) and not self.exitNow:
            # update every x seconds
            currT = glfw.get_time()
            if currT - t > 0.1:
                # update time
                t = currT
                # clear
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

                # build projection matrix
                pMatrix = glutils.perspective(45.0, self.aspect, 0.1, 100.0)

                mvMatrix = glutils.lookAt([0.0, 0.0, -2.0], [0.0, 0.0, 0.0],
                                          [0.0, 1.0, 0.0])
                # render
                self.scene.render(pMatrix, mvMatrix)
                # step 
                self.scene.step()

                glfw.swap_buffers(self.win)
                # Poll for and process events
                glfw.poll_events()
        # end
        glfw.terminate()
Example #8
0
 def run(self):
     # Initialize the library
     if not glfw.init():
         return
     # Create a windowed mode window and its OpenGL context
     self.window = glfw.create_window(640, 480, "Hello World", None, None)
     if not self.window:
         glfw.terminate()
         return
 
     renderer = RiftGLRendererCompatibility()
     # Paint a triangle in the center of the screen
     renderer.append(TriangleDrawerCompatibility())
 
     # Make the window's context current
     glfw.make_context_current(self.window)
 
     # Initialize Oculus Rift
     renderer.init_gl()
     renderer.rift.recenter_pose()
     
     glfw.set_key_callback(self.window, self.key_callback)
 
     # Loop until the user closes the window
     while not glfw.window_should_close(self.window):
         # Render here, e.g. using pyOpenGL
         renderer.display_rift_gl()
 
         # Swap front and back buffers
         glfw.swap_buffers(self.window)
 
         # Poll for and process events
         glfw.poll_events()
 
     glfw.terminate()
def main():
    window = init_window()
    if not window:
        return

    shader = get_shader()
    vao = get_vertex()
    tex = bind_texture("wall.png")
    tex2 = bind_texture("wall2.jpg")
    gl.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)
    gl.glEnable(gl.GL_DEPTH_TEST)

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Poll for and process events
        glfw.poll_events()

        # Render here, e.g. using pyOpenGL
        render(shader, vao, tex, tex2)

        # Swap front and back buffers
        glfw.swap_buffers(window)
        time.sleep(0.05)

    gl.glDeleteVertexArrays(1, vao)
    glfw.terminate()
Example #10
0
def main():
	# Initialize the library
	if not glfw.init():
		return
	
	glfw.set_error_callback(error_callback)

	# Create a windowed mode window and its OpenGL context
	window = glfw.create_window(640, 480, "Hello World", None, None)
	if not window:
		glfw.terminate()
		return

	# Make the window's context current
	glfw.make_context_current(window)

	program = common2d.init_shader_program()

	# Loop until the user closes the window
	while not glfw.window_should_close(window):
		# Render here
		common2d.display(program)

		# Swap front and back buffers
		glfw.swap_buffers(window)

		# Poll for and process events
		glfw.poll_events()

	glfw.terminate()
Example #11
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(window_width, window_height, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_window_size)

    initGL(window)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        display()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Example #12
0
    def __init__(self):

        self.dir = Dir.empty
        self.run = True
        self.snake = Player()

        if not glfw.init():
            return
        self.window = glfw.create_window(400, 300, "Hello, World!", None, None)
        if not self.window:
            glfw.terminate()
            return
        glfw.make_context_current(self.window)
        glfw.set_key_callback(self.window, self.key_callback)

        while self.run and not glfw.window_should_close(self.window):

            # Update player's position
            self.snake.play(self.dir)
            sleep(0.075)

            self.draw()
            glfw.swap_buffers(self.window)
            glfw.poll_events()

            if self.snake.alive is False:
                sleep(1.075)
                self.run = False
                
        glfw.terminate()
Example #13
0
 def run(self):
     while not glfw.window_should_close(self.window):
         if self.redisplay:
             self.redisplay = False
             self.drawScene()
         glfw.wait_events()
     glfw.terminate()
Example #14
0
    def close(self):
        """Close the window and uninitialize the resources
        """
        # Test if the window has already been closed
        if glfw.window_should_close(self.winHandle):
            return

        _hw_handle = None

        try:
            self.setMouseVisibility(True)
            glfw.set_window_should_close(self.winHandle, 1)
            glfw.destroy_window(self.winHandle)
        except Exception:
            pass
        # If iohub is running, inform it to stop looking for this win id
        # when filtering kb and mouse events (if the filter is enabled of
        # course)
        try:
            if IOHUB_ACTIVE and _hw_handle:
                from psychopy.iohub.client import ioHubConnection
                conn = ioHubConnection.ACTIVE_CONNECTION
                conn.unregisterWindowHandles(_hw_handle)
        except Exception:
            pass
Example #15
0
 def renderLoop(self):
     self.initGL()
     while not glfw.window_should_close(self.window):
         w, h = glfw.get_framebuffer_size(self.window)
         self.renderFrame()
         glfw.swap_buffers(self.window)
         glfw.poll_events()
     self.destroyGL()
Example #16
0
def draw_a_triangle():
    
    if not glfw.init():
        return -1;
    # Create a windowed mode window and its OpenGL context
    
    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    window = glfw.create_window(1024, 768, "Triangle", None, None);
    if window == None:
        glfw.terminate()
        return -1
    # Make the window's context current
    
    glfw.make_context_current(window)
#     glfw.Experimental = True
    glClearColor(0.0, 0.1, 0.2, 1.0)
    
    flatten = lambda l: [u for t in l for u in t]
    vertices = [(-1.0, -1.0, 0.0),
                (1.0, -1.0, 0.0),
                (0.0, 1.0, 0.0)]
    indices = range(3)
    vao_handle = glGenVertexArrays(1)
    glBindVertexArray(vao_handle)
    program_handle = tools.load_program("../shader/simple.v.glsl",
                                        "../shader/simple.f.glsl")
    
    f_vertices = flatten(vertices)
    c_vertices = (c_float*len(f_vertices))(*f_vertices)
    v_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, v_buffer)
    glBufferData(GL_ARRAY_BUFFER, c_vertices, GL_STATIC_DRAW)
    glEnableVertexAttribArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, v_buffer)
    glVertexAttribPointer(0,
        #glGetAttribLocation(program_handle, "vertexPosition_modelspace"),
        3, GL_FLOAT, False, 0, None)
    
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here
        glClear(GL_COLOR_BUFFER_BIT)
        glUseProgram(program_handle)
        
        glDrawArrays(GL_TRIANGLES, 0, 3)
        glDisableVertexAttribArray(vao_handle)
        
        # Swap front and back buffers 
        glfw.swap_buffers(window)
        # Poll for and process events
        glfw.poll_events()
    glfw.terminate();
    
    pass
Example #17
0
def show(molecule, width=500, height=500,
         show_bonds=True, bonds_method='radii', bonds_param=None,
         camera=None, title='mogli'):
    """
    Interactively show the given molecule with OpenGL. By default, bonds are
    drawn, if this is undesired the show_bonds parameter can be set to False.
    For information on the bond calculation, see Molecule.calculate_bonds.
    If you pass a tuple of camera position, center of view and an up vector to
    the camera parameter, the camera will be set accordingly. Otherwise the
    molecule will be viewed in the direction of the z axis, with the y axis
    pointing upward.
    """
    global _camera
    molecule.positions -= np.mean(molecule.positions, axis=0)
    max_atom_distance = np.max(la.norm(molecule.positions, axis=1))
    if show_bonds:
        molecule.calculate_bonds(bonds_method, bonds_param)

    # If GR3 was initialized earlier, it would use a different context, so
    # it will be terminated first.
    gr3.terminate()

    # Initialize GLFW and create an OpenGL context
    glfw.init()
    glfw.window_hint(glfw.SAMPLES, 16)
    window = glfw.create_window(width, height, title, None, None)
    glfw.make_context_current(window)
    glEnable(GL_MULTISAMPLE)

    # Set up the camera (it will be changed during mouse rotation)
    if camera is None:
        camera_distance = -max_atom_distance*2.5
        camera = ((0, 0, camera_distance),
                  (0, 0, 0),
                  (0, 1, 0))
    camera = np.array(camera)
    _camera = camera

    # Create the GR3 scene
    gr3.setbackgroundcolor(255, 255, 255, 0)
    _create_gr3_scene(molecule, show_bonds)
    # Configure GLFW
    glfw.set_cursor_pos_callback(window, _mouse_move_callback)
    glfw.set_mouse_button_callback(window, _mouse_click_callback)
    glfw.swap_interval(1)
    # Start the GLFW main loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        width, height = glfw.get_window_size(window)
        glViewport(0, 0, width, height)
        _set_gr3_camera()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gr3.drawimage(0, width, 0, height,
                      width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL)
        glfw.swap_buffers(window)
    glfw.terminate()
    gr3.terminate()
Example #18
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        # Swap front and back buffers
        glfw.swap_buffers(window)
        
        gl_begin( GL_TRIANGLES )
        glColor3f( 1.0, 0.0, 0.0 )
        glVertex3f( 0.0, 1.0, 0.0 )
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0 )
        glColor3f( 0.0, 0.0, 1.0 ) 
        glVertex3f( 1.0, -1.0, 1.0)
        
        glColor3f( 1.0, 0.0, 0.0 ) 
        glVertex3f( 0.0, 1.0, 0.0)
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0)
        glColor3f( 0.0, 0.0, 1.0 )
        glVertex3f( 0.0, -1.0, -1.0)
        
        #glColor3f( 1.0f, 0.0f, 0.0f ) 
        #glVertex3f( 0.0f, 1.0f, 0.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f ) 
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f ) 
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        
        #glColor3f( 1.0f, 0.0f, 0.0f )
        #glVertex3f( -1.0f, -1.0f, 1.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f )
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f )
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        glEnd()

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Example #19
0
 def run(self):
    # This is the main game loop 
    self.init()
    while not glfw.window_should_close(self.window):
       self.poll()
       self.tick()
       self.render()
       assert(gl.glGetError()==0) # Remove this in prod
    glfw.terminate()
    os._exit(0)
Example #20
0
 def main_loop(self):
     while True:
         glfw.poll_events()
         if glfw.window_should_close(self.window) or self.should_exit:
             self.do_exit()
             return
         try:
             self._render()
         except StopIteration:
             self.do_exit()
             return
Example #21
0
File: 003-ebo.py Project: lhl/vrdev
def main():
    # Initialize the library
    if not glfw.init():
        return

    # Set some window hints
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3);
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3);
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE);
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE);
    glfw.window_hint(glfw.SAMPLES, 16)

    # This works as expected
    glfw.window_hint(glfw.RESIZABLE, 0)

    # These should work, but don't :(
    # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226
    # ended up using xdotool, see run.py
    glfw.window_hint(glfw.FOCUSED, 0)

    # I've set 'shader-*' to raise in openbox-rc as workaround
    # Looking at the code and confirming version 3.1.2 and it should work
    glfw.window_hint(glfw.FLOATING, 1)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(300, 300, "shader-test", None, None)
    if not window:
        glfw.terminate()
        return

    # Move Window
    glfw.set_window_pos(window, 1600, 50)

    # Make the window's context current
    glfw.make_context_current(window)

    # vsync
    glfw.swap_interval(1)

    # Setup GL shaders, data, etc.
    initialize()

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        render()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Example #22
0
    def run(self):
        glfw.make_context_current(self._wnd)
        self._ctx = ModernGL.create_context()

        self.initialize(self._ctx)

        while not glfw.window_should_close(self._wnd):
            width, height = self.size()
            self._ctx.viewport = (0, 0, width, height)
            self.render(self._ctx)
            glfw.swap_buffers(self._wnd)
            glfw.wait_events()
Example #23
0
    def render(self):
        """
        Render the current simulation state to the screen or off-screen buffer.
        """
        if self.window is None:
            return
        elif glfw.window_should_close(self.window):
            exit(0)

        with self._gui_lock:
            super().render()

        glfw.poll_events()
Example #24
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640, 480, "Lab2", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    while not glfw.window_should_close(window) and not ex:
        draw()
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
def main():
	global current_vao
	global vaos

	if not opengl_init():
		return

	glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) 
	glfw.set_key_callback(window,key_event)
	# Set opengl clear color to something other than red (color used by the fragment shader)
	glClearColor(0,0,0.4,0)
	
	# Create vertex array object (VAO) 1: Full Triangle
	vao = glGenVertexArrays(1)
	glBindVertexArray(vao)
	init_object(vertex_data)
	glBindVertexArray(0)

	# Create vertex array object (VAO) 2: 1/2 Triangle
	vao2 = glGenVertexArrays(1)
	glBindVertexArray(vao2)
	init_object(vertex_data2)
	glBindVertexArray(0)

	program_id = common.LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" )
	vertex_buffer = glGenBuffers(1)

	current_vao = 0
	vaos = [vao,vao2]
	glewInit()


	while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window):
		glClear(GL_COLOR_BUFFER_BIT)

		glUseProgram(program_id)	
		glBindVertexArray(vaos[current_vao])

		# Draw the triangle !
		glDrawArrays (GL_TRIANGLES, 0, 3)#3 indices starting at 0 -> 1 triangle

		glBindVertexArray(0)

		# Swap front and back buffers
		glfw.swap_buffers(window)

		# Poll for and process events
		glfw.poll_events()

	glfw.terminate()
Example #26
0
File: Lab1.py Project: ROOOOO/Study
def main():
    global delta
    global angle
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 640, "Lab1", None, None)
    if not window:
        glfw.terminate()
        return
    # Make the window's context current
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glPushMatrix()

        glRotatef(angle, 0, 0, 1)

        glBegin(GL_QUADS)

        glColor3f(0.0,0.0,0.0)
        glVertex3f( 0.5, 0.5, 0.0)
        glColor3f(1.0,0.0,0.0)
        glVertex3f(-0.5, 0.5, 0.0)
        glColor3f(0.0,0.0,1.0)
        glVertex3f(-0.5, -0.5, 0.0)
        glColor3f(1.0,0.0,1.0)
        glVertex3f( 0.5, -0.5, 0.0)


        glEnd()

        glPopMatrix()
        angle += delta

        # Swap front and back buffers
        glfw.swap_buffers(window)
        # Poll for and process events
        glfw.poll_events()
    glfw.destroy_window(window)
    glfw.terminate()
Example #27
0
def main():
   if not glfw.init(): return
   window = glfw.create_window(640,640,'2015004584', None,None)
   if not window: 
      glfw.terminate()
      return
   
   glfw.make_context_current(window)
   glfw.set_key_callback(window, key_callback)
   
   while not glfw.window_should_close(window): 
      glfw.poll_events()
      render(gCamAng)
      glfw.swap_buffers(window)
   
   glfw.terminate()
def main():
    # Initialize the library
	if not glfw.init():
		return

	# Open Window and create its OpenGL context
	window = glfw.create_window(1024, 768, "Tutorial 01", None, None)

	# 
	glfw.window_hint(glfw.SAMPLES, 4)
	glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
	glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
	glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
	glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
 
	if not window:
		print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr)
		glfw.terminate()
		return

	# Initialize GLEW
	glfw.make_context_current(window)
	glewExperimental = True

	# GLEW is a framework for testing extension availability.  Please see tutorial notes for
	# more information including why can remove this code.
	if glewInit() != GLEW_OK:
	 	print("Failed to initialize GLEW\n",file=sys.stderr);
	 	return
	
	glfw.set_input_mode(window,glfw.STICKY_KEYS,True) 


	# Loop until the user closes the window
	
	#while not glfw.window_should_close(window):
	while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window):

		# Draw nothing sucker

		# Swap front and back buffers
		glfw.swap_buffers(window)

		# Poll for and process events
		glfw.poll_events()

	glfw.terminate()
Example #29
0
def main():
    if not glfw.init(): return
    window = glfw.create_window(480, 480, "Hello World", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)

    glfw.terminate()
def main():
    if not glfw_init_routine():
        return

    if not gl_init_routine():
        return

    # Main event loop
    while not glfw.window_should_close(window):
        update_surface()
        render()
        glfw.swap_buffers(window)
        mark_blob()
        do_input()
        glfw.poll_events()

    gl_deinit_routine()

    glfw.terminate()
Example #31
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    window = glfw.create_window(800, 600, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    #           positions        colors          texture coords
    quad = [
        -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0,
        0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.0,
        1.0, 1.0, 1.0, 0.0, 1.0
    ]

    quad = numpy.array(quad, dtype=numpy.float32)

    indices = [0, 1, 2, 2, 3, 0]

    indices = numpy.array(indices, dtype=numpy.uint32)

    print(quad.itemsize * len(quad))
    print(indices.itemsize * len(indices))
    print(quad.itemsize * 8)

    vertex_shader = """
    #version 330
    layout(location = 0) in vec3 position;
    layout(location = 1) in vec3 color;
    layout(location = 2) in vec2 inTexCoords;

    out vec3 newColor;
    out vec2 outTexCoords;
    void main()
    {
        gl_Position = vec4(position, 1.0f);
        newColor = color;
        outTexCoords = inTexCoords;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;
    in vec2 outTexCoords;

    out vec4 outColor;
    uniform sampler2D samplerTex;
    void main()
    {
        outColor = texture(samplerTex, outTexCoords) * vec4(newColor, 1.0f);
    }
    """

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    #position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    #color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    #texture_coords = glGetAttribLocation(shader, "inTexCoords")
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, quad.itemsize * 8,
                          ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    #texture wrapping params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    #texture filtering params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    image = Image.open("res/smiley.png")
    #img_data = numpy.array(list(image.getdata()), numpy.uint8)
    flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM)
    img_data = flipped_image.convert("RGBA").tobytes()
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, img_data)
    #print(image.width, image.height)

    glClearColor(0.2, 0.3, 0.2, 1.0)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        glUseProgram(shader)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    glDeleteProgram(shader)
    glDeleteVertexArrays(1, [VAO])
    glDeleteBuffers(2, [VBO, EBO])

    glfw.terminate()
Example #32
0
    def run(self):
        # Initialize the library
        if not glfw.init():
            return

        # Set some window hints
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3);
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3);
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE);
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE);
        glfw.window_hint(glfw.SAMPLES, 16)

        # This works as expected
        # glfw.window_hint(glfw.RESIZABLE, 0)

        # These should work, but don't :(
        # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226
        # ended up using xdotool, see run.py
        glfw.window_hint(glfw.FOCUSED, 0)

        # I've set 'shader-*' to raise in openbox-rc as workaround
        # Looking at the code and confirming version 3.1.2 and it should work
        glfw.window_hint(glfw.FLOATING, 1)

        # Create a windowed mode window and its OpenGL context
        self.w = glfw.create_window(500, 500, "shader-test", None, None)
        if not self.w:
            glfw.terminate()
            return

        # Move Window
        glfw.set_window_pos(self.w, 1400, 50)

        # Callbacks
        glfw.set_key_callback(self.w, self.on_key)
        glfw.set_framebuffer_size_callback(self.w, self.on_resize);


        # Make the window's context current
        glfw.make_context_current(self.w)

        # vsync
        glfw.swap_interval(1)

        # Setup GL shaders, data, etc.
        self.initialize()

        # Loop until the user closes the window
        while not glfw.window_should_close(self.w):
            # print difference in time since start
            # this should always be 16.6-16.7 @ 60fps
            # print('%0.1fms' % (1000 * (time.time()-self.lastframe)))

            # start of the frame
            self.lastframe = time.time()

            # Render here, e.g. using pyOpenGL
            self.render()

            # Swap front and back buffers
            glfw.swap_buffers(self.w)

            # Poll for and process events
            glfw.poll_events()

        glfw.terminate()
Example #33
0
def main():
    pygame.init()
    infoObject = pygame.display.Info()

    WIDTH = infoObject.current_w
    HEIGHT = infoObject.current_h
    PHASE = 0

    FPS = 1/60.0
    drawpoint1 = [100, 600]
    drawpoint2 = [1200, 100]
    if not glfw.init():
        return

    window = glfw.create_window(WIDTH,HEIGHT, "window", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)



    quad = [-1.0,-1.0, 0.0,
            1.0, -1.0, 0.0,
            1.0, 1.0, 0.0,
            -1.0, 1.0, 0.0]

    quad = np.array(quad, dtype = np.float32)

    indices = [0, 1, 2,
                2, 3, 0]

    indices = np.array(indices, dtype = np.uint32)


    vertex_shader = """
    #version 330
    in vec3 position;
    void main(){
        gl_Position = vec4 (position, 1.0f);
    }
    """

    fragment_shader = """
    #version 330

    uniform float pointX;
    uniform float pointY;
    uniform float pointX2;
    uniform float pointY2;
    uniform float phase;
    uniform float step;
    void main(){
        vec4 color = vec4(0.0, 0.0, 0.0, 1.0);
        float x = gl_FragCoord.x;
        float y = gl_FragCoord.y;
        float distance1 = sqrt(pow(x-pointX, 2) + pow(y-pointY, 2));
        float distance2 = sqrt(pow(x-pointX2, 2) + pow(y-pointY2, 2));
        float sini1 = distance1*0.5 - phase;
        float sini2 = distance2*0.5 - phase;
        float r1 = sin(sini1)*0.5 + 0.25;
        float g1 = sin(sini1 + step)*0.5 + 0.25;
        float b1 = sin(sini1 + step*2)*0.5 + 0.25;

        float r2 = sin(sini2)*0.5 + 0.25;
        float g2 = sin(sini2 + step)*0.5 + 0.25;
        float b2 = sin(sini2 + step*2)*0.5 + 0.25;
        color.r = (r1 + r2)/2;
        color.g = (g1 +g2)/2;
        color.b = (b1+b2)/2;
        gl_FragColor = color;
    }

    """

    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                                OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)

    glBufferData(GL_ARRAY_BUFFER, getsizeof(quad), quad, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)

    glBufferData(GL_ELEMENT_ARRAY_BUFFER, getsizeof(indices), indices, GL_STATIC_DRAW)

    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 12, ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)


    glUseProgram(shader)

    glUniform1f(glGetUniformLocation(shader, "pointX"), drawpoint1[0])
    glUniform1f(glGetUniformLocation(shader, "pointY"), drawpoint1[1])
    glUniform1f(glGetUniformLocation(shader, "pointX2"), drawpoint2[0])
    glUniform1f(glGetUniformLocation(shader, "pointY2"), drawpoint2[1])

    glUniform1f(glGetUniformLocation(shader, "phase"), PHASE)
    glUniform1f(glGetUniformLocation(shader, "step"), (2*3.14)/3)

    direction = 1
    while not glfw.window_should_close(window):


        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)
        PHASE = (PHASE + 0.05)%360
        glUniform1f(glGetUniformLocation(shader, "phase"), PHASE)
        time.sleep(FPS)



    glfw.terminate()
Example #34
0
def main():
    if not glfw.init():
        raise Exception("glfw cannot be initialised.......")

    window = glfw.create_window(700, 700, "rotation 2D pattern - b117049",
                                None, None)

    if not window:
        glfw.terminate()
        raise Exception("glfw window not created")

    w, h = glfw.get_framebuffer_size(window)
    print("width: {}, height:{}".format(w, h))

    glfw.set_window_pos(window, 400, 40)
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)

    glfw.set_window_size_callback(window, reshape_callback)

    gluOrtho2D(-200.0, 200.0, -200.0, 200.0)
    setpixel(0, 0, [1, 0, 1])

    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        #glClearColor(0.0,0.76,0.56,1.0)
        glClearColor(0, 0, 0, 1.0)

        #drawAxes()

        a = (40, 40)  #yellow
        b = (40, 100)  #green
        c = (100, 100)  #red
        d = (100, 40)  #blue
        i = 8

        while i != 0:

            glBegin(GL_QUADS)
            glColor3f(1, 1, 0)  #yellow vertex
            glVertex2fv(a)
            glColor3f(0, 1, 0)
            glVertex2fv(b)
            glColor3f(1, 0, 0)
            glVertex2fv(c)
            glColor3f(0, 0, 1)  #blue vertex
            glVertex2fv(d)
            glEnd()

            #print("rotate square vertices by 45 degrees anti clockwise x-dir")

            #rotate square vertices by 45 degrees anti clockwise x-dir
            angle = 45
            a = rotationOrigin2D(a, angle)
            b = rotationOrigin2D(b, angle)
            c = rotationOrigin2D(c, angle)
            d = rotationOrigin2D(d, angle)
            i = i - 1
        #print(A_new,"||", B_new,"||", C_new,"||", D_new)

        glfw.swap_buffers(window)

        glfw.poll_events()

    glfw.terminate()
Example #35
0
def main():
    vertex_src = """
    # version 410

    in vec3 a_position;
    in vec3 a_color;

    out vec3 v_color;

    void main()
    {
        gl_Position = vec4(a_position, 1.0);
        v_color = a_color;
    }
    """

    fragment_src = """
    # version 410

    in vec3 v_color;
    out vec4 out_color;

    void main()
    {
        out_color = vec4(v_color, 1.0);
    }
    """

    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw can not be initialized!")

    if "Windows" in pltf.platform():
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    else:
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    # creating the window
    window = glfw.create_window(1280, 720, "My OpenGL window", None, None)

    # check if window was created
    if not window:
        glfw.terminate()
        raise Exception("glfw window can not be created!")

    # set window's position
    glfw.set_window_pos(window, 100, 100)

    # make the context current
    glfw.make_context_current(window)

    vertices = [
        -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
        0.5, 0.0, 0.0, 0.0, 1.0
    ]

    vertices = np.array(vertices, dtype=np.float32)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
                            compileShader(fragment_src, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

    position = glGetAttribLocation(shader, "a_position")
    glEnableVertexAttribArray(position)
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(0))

    color = glGetAttribLocation(shader, "a_color")
    glEnableVertexAttribArray(color)
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(12))

    glBindVertexArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    # glUseProgram(shader)
    glClearColor(0, 0.1, 0.1, 1)

    # the main application loop
    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        glUseProgram(shader)
        glBindVertexArray(VAO)
        glDrawArrays(GL_TRIANGLES, 0, 3)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Example #36
0
def main():
    global delta_time, last_frame

    glfw.init()
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)

    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None,
                                None)
    if not window:
        glfw.terminate()
        raise ValueError("Failed to create window")

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)
    glfw.set_scroll_callback(window, scroll_callback)

    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    gl.glEnable(gl.GL_DEPTH_TEST)

    lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs",
                         CURDIR / "shaders/1.lamp.fs")
    lighting_shader = Shader(CURDIR / "shaders/5.2.light_casters.vs",
                             CURDIR / "shaders/5.2.light_casters.fs")

    vertices = [
        # positions        normals           texture coords
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        0.0,
        0.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        1.0,
        0.0,
        0.5,
        0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        1.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        1.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        -1.0,
        0.0,
        0.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        1.0,
        1.0,
        0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        1.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        -1.0,
        0.0,
        0.0,
        1.0,
        0.0,
        -0.5,
        0.5,
        -0.5,
        -1.0,
        0.0,
        0.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        -1.0,
        0.0,
        0.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        -1.0,
        0.0,
        0.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        -1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        -1.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        0.0,
        0.0,
        1.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        1.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        1.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.0,
        1.0,
        0.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        -1.0,
        0.0,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        -1.0,
        0.0,
        1.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        -1.0,
        0.0,
        1.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        -1.0,
        0.0,
        1.0,
        0.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        -1.0,
        0.0,
        0.0,
        0.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        -1.0,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        0.0,
        0.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        0.0,
        1.0,
        1.0,
        0.5,
        0.5,
        0.5,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        0.0,
        0.0,
        1.0
    ]
    vertices = (c_float * len(vertices))(*vertices)

    cube_positions = [(0.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -2.2, -2.5),
                      (-3.8, -2.0, -12.3), (2.4, -0.4, -3.5),
                      (-1.7, 3.0, -7.5), (1.3, -2.0, -2.5), (1.5, 2.0, -2.5),
                      (1.5, 0.2, -1.5), (-1.3, 1.0, -1.5)]

    cube_vao = gl.glGenVertexArrays(1)
    vbo = gl.glGenBuffers(1)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                    gl.GL_STATIC_DRAW)

    gl.glBindVertexArray(cube_vao)

    # -- position attribute
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             8 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)
    # -- normal attribute
    gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT,
                             gl.GL_FALSE, 8 * sizeof(c_float),
                             c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)
    # -- texture coordinate
    gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT,
                             gl.GL_FALSE, 8 * sizeof(c_float),
                             c_void_p(6 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(2)

    # -- second configure light vao (vbo is the same)
    light_vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(light_vao)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             8 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    # -- load texture
    diffuse_map = load_texture("container2.png")
    specular_map = load_texture("container2_specular.png")

    # -- shader configuration
    lighting_shader.use()
    lighting_shader.set_int("material.diffuse", 0)
    lighting_shader.set_int("material.specular", 1)

    while not glfw.window_should_close(window):
        # -- time logic
        current_frame = glfw.get_time()
        delta_time = current_frame - last_frame
        last_frame = current_frame

        # -- input
        process_input(window)

        # -- render
        gl.glClearColor(0.1, 0.1, 0.1, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        lighting_shader.use()
        lighting_shader.set_vec3("light.position", light_pos)
        lighting_shader.set_vec3("viewPos", camera.position)

        # -- light properties
        lighting_shader.set_vec3("light.ambient", Vector3([0.2, 0.2, 0.2]))
        lighting_shader.set_vec3("light.diffuse", Vector3([0.5, 0.5, 0.5]))
        lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0]))
        lighting_shader.set_float("light.constant", 1.0)
        lighting_shader.set_float("light.linear", 0.09)
        lighting_shader.set_float("light.quadratic", 0.032)

        # -- material properties
        lighting_shader.set_float("material.shininess", 32.0)

        # -- view.projection transformations
        projection = Matrix44.perspective_projection(camera.zoom,
                                                     SRC_WIDTH / SRC_HEIGHT,
                                                     0.1, 100.0)
        view = camera.get_view_matrix()
        lighting_shader.set_mat4("projection", projection)
        lighting_shader.set_mat4("view", view)

        # -- world transformation
        model = Matrix44.identity()
        lighting_shader.set_mat4("model", model)

        # -- bind diffuse map
        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, diffuse_map)

        # -- bind specular map
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, specular_map)

        # -- render continers
        gl.glBindVertexArray(cube_vao)
        for idx, position in enumerate(cube_positions):
            angle = 20.0 * idx
            rotation = matrix44.create_from_axis_rotation([1.0, 0.3, 0.5],
                                                          math.radians(angle))
            translation = Matrix44.from_translation(position)
            model = translation * rotation
            lighting_shader.set_mat4('model', model)
            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        # -- draw lamp object
        lamp_shader.use()
        lamp_shader.set_mat4("projection", projection)
        lamp_shader.set_mat4("view", view)

        model = Matrix44.identity()
        model *= Matrix44.from_translation(light_pos)
        model *= Matrix44.from_scale(Vector3([.2, .2, .2]))
        lamp_shader.set_mat4("model", model)

        gl.glBindVertexArray(light_vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        glfw.swap_buffers(window)
        glfw.poll_events()

    gl.glDeleteVertexArrays(1, id(cube_vao))
    gl.glDeleteVertexArrays(1, id(light_vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
def main():
    # init GLFW
    glfw.init()

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window_width, window_height = 1280, 720
    window_aspect = window_width / float(window_height)

    window = glfw.create_window(window_width, window_height, 'Triangle', None, None)

    glfw.make_context_current(window)

    # init GL
    glViewport(0, 0, window_width, window_height)
    glEnable(GL_DEPTH_TEST)
    glClearColor(0.5, 0.5, 0.5, 1)



    program = glutils.loadShaders(strVS, strFS)

    vertexData = numpy.array([-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0,], numpy.float32)

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    vertexBuffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)
    glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData, GL_STATIC_DRAW)

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)

    glBindVertexArray(0)



    glfw.set_time(0)
    win_t = 0.0

    while not glfw.window_should_close(window):
        currT = glfw.get_time()
        if currT - win_t > 0.1:
            # rotation angle
            # print(win_t)
            win_t = currT
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            # render scene
            glUseProgram(program)

            glBindVertexArray(vao)
            
            glDrawArrays(GL_TRIANGLE_FAN, 0, 4)
            glBindVertexArray(0)

            glfw.swap_buffers(window)
            glfw.poll_events()
    glfw.terminate()
def main():
    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec3 a_color;

    uniform mat4 rotation;

    out vec3 v_color;

    void main()
    {
        gl_Position = rotation * vec4(a_position, 1.0);
        v_color = a_color;
    }
    """

    fragment_src = """
    # version 330

    in vec3 v_color;
    out vec4 out_color;

    void main()
    {
        out_color = vec4(v_color, 1.0);
    }
    """

    def window_resize(window, width, height):
        glViewport(0, 0, width, height)

    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw can not be initialized!")

    if "Windows" in pltf.platform():
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    else:
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    # creating the window
    window = glfw.create_window(1024, 768, "My OpenGL window", None, None)

    # check if window was created
    if not window:
        glfw.terminate()
        raise Exception("glfw window can not be created!")

    # set window's position
    glfw.set_window_pos(window, 100, 100)

    # set the callback function for window resize
    glfw.set_window_size_callback(window, window_resize)

    # make the context current
    glfw.make_context_current(window)

    vertices = [
        -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 0.5,
        0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, -0.5, -0.5,
        -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5,
        0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0
    ]

    indices = [
        0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6,
        5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7
    ]

    vertices = np.array(vertices, dtype=np.float32)
    indices = np.array(indices, dtype=np.uint32)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
                            compileShader(fragment_src, GL_FRAGMENT_SHADER))

    # Vertex Buffer Object
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

    # Element Buffer Object
    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices,
                 GL_STATIC_DRAW)

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

    glBindVertexArray(0)

    glClearColor(0, 0.1, 0.1, 1)
    glEnable(GL_DEPTH_TEST)

    rotation_loc = glGetUniformLocation(shader, "rotation")

    # the main application loop
    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time())
        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())

        glUseProgram(shader)
        # glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x * rot_y)
        # glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x @ rot_y)
        glUniformMatrix4fv(rotation_loc, 1, GL_FALSE,
                           pyrr.matrix44.multiply(rot_x, rot_y))
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Example #39
0
def main():
    if not glfw.init():
        return -1

    #configure glfw (using OpenGL 3.3 Core)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    # create the window
    window = glfw.create_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return -1
    glfw.make_context_current(window)
    # set callbacks
    glfw.set_window_size_callback(window, framebuffer_size_callback)
    glfw.set_key_callback(window, key_callback)

    # set the OpenGL viewport to the whole window
    (width, height) = glfw.get_framebuffer_size(window)
    glViewport(0, 0, width, height)

    # SHADERS #########################################################
    vertex_shader_source = """
    #version 330 core

    layout (location = 0) in vec3 position;

    void main()
    {
        gl_Position = vec4(position, 1.0f);
    }
    """

    orange_fragment_shader_source = """
    #version 330 core

    out vec4 color;

    void main()
    {
        color = vec4(1.0f, 0.5f, 0.2f, 1.0f);
    }
    """

    green_fragment_shader_source = """
    #version 330 core

    out vec4 color;

    void main()
    {
        color = vec4(0.5f, 1.0f, 0.2f, 1.0f);
    }
    """

    vertex_shader = OpenGL.GL.shaders.compileShader(vertex_shader_source, GL_VERTEX_SHADER)
    orange_fragment_shader = OpenGL.GL.shaders.compileShader(orange_fragment_shader_source, GL_FRAGMENT_SHADER)
    green_fragment_shader = OpenGL.GL.shaders.compileShader(green_fragment_shader_source, GL_FRAGMENT_SHADER)
    orange_shader = OpenGL.GL.shaders.compileProgram(vertex_shader, orange_fragment_shader)
    green_shader = OpenGL.GL.shaders.compileProgram(vertex_shader, green_fragment_shader)
    # END SHADERS #########################################################

    # vertices data (a triangle)
    triangle = [
        -0.5,  0.75, 0.0,
        -0.9, -0.75, 0.0,
        -0.1, -0.75, 0.0
    ]
    triangle = numpy.array(triangle, dtype=numpy.float32)

    triangleVAO = glGenVertexArrays(1)
    triangleVBO = glGenBuffers(1)

    glBindVertexArray(triangleVAO)
    glBindBuffer(GL_ARRAY_BUFFER, triangleVBO)
    glBufferData(GL_ARRAY_BUFFER, triangle.itemsize * len(triangle), triangle, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(0)
    glBindVertexArray(0)

    # vertices data (a square)
    square = [
    0.1,  -0.4, 0.0,   # first triangle
    0.1,   0.4, 0.0,
    0.9,  -0.4, 0.0,
    0.1,   0.4, 0.0,   # second triangle
    0.9,  -0.4, 0.0,
    0.9,   0.4, 0.0
    ]
    square = numpy.array(square, dtype=numpy.float32)

    triangleVAO = glGenVertexArrays(1)
    triangleVBO = glGenBuffers(1)

    glBindVertexArray(triangleVAO)
    glBindBuffer(GL_ARRAY_BUFFER, triangleVBO)
    glBufferData(GL_ARRAY_BUFFER, triangle.itemsize * len(triangle), triangle, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(0)
    glBindVertexArray(0)

    squareVAO = glGenVertexArrays(1)
    squareVBO = glGenBuffers(1)

    glBindVertexArray(squareVAO)
    glBindBuffer(GL_ARRAY_BUFFER, squareVBO)
    glBufferData(GL_ARRAY_BUFFER, square.itemsize * len(square), square, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(0)
    glBindVertexArray(0)

    # game loop
    while not glfw.window_should_close(window):
        # set the color buffer
        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        glUseProgram(orange_shader)
        glBindVertexArray(triangleVAO)
        glDrawArrays(GL_TRIANGLES, 0, 3)

        glUseProgram(green_shader)
        glBindVertexArray(squareVAO)
        glDrawArrays(GL_TRIANGLES, 0, 6)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Example #40
0
def main():
    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1920, 1080
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None)
    #window = glfw.create_window(w_width, w_height, "My OpenGL window", glfw.get_primary_monitor(), None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)
    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    #        positions        texture_coords
    cube = [-0.5, -0.5, 0.5, 0.0, 0.0,
            0.5, -0.5, 0.5, 1.0, 0.0,
            0.5, 0.5, 0.5, 1.0, 1.0,
            -0.5, 0.5, 0.5, 0.0, 1.0,

            -0.5, -0.5, -0.5, 0.0, 0.0,
            0.5, -0.5, -0.5, 1.0, 0.0,
            0.5, 0.5, -0.5, 1.0, 1.0,
            -0.5, 0.5, -0.5, 0.0, 1.0,

            0.5, -0.5, -0.5, 0.0, 0.0,
            0.5, 0.5, -0.5, 1.0, 0.0,
            0.5, 0.5, 0.5, 1.0, 1.0,
            0.5, -0.5, 0.5, 0.0, 1.0,

            -0.5, 0.5, -0.5, 0.0, 0.0,
            -0.5, -0.5, -0.5, 1.0, 0.0,
            -0.5, -0.5, 0.5, 1.0, 1.0,
            -0.5, 0.5, 0.5, 0.0, 1.0,

            -0.5, -0.5, -0.5, 0.0, 0.0,
            0.5, -0.5, -0.5, 1.0, 0.0,
            0.5, -0.5, 0.5, 1.0, 1.0,
            -0.5, -0.5, 0.5, 0.0, 1.0,

            0.5, 0.5, -0.5, 0.0, 0.0,
            -0.5, 0.5, -0.5, 1.0, 0.0,
            -0.5, 0.5, 0.5, 1.0, 1.0,
            0.5, 0.5, 0.5, 0.0, 1.0]

    cube = numpy.array(cube, dtype=numpy.float32)

    indices = [0, 1, 2, 2, 3, 0,
               4, 5, 6, 6, 7, 4,
               8, 9, 10, 10, 11, 8,
               12, 13, 14, 14, 15, 12,
               16, 17, 18, 18, 19, 16,
               20, 21, 22, 22, 23, 20]

    indices = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec2 texture_cords;
    in layout(location = 2) vec3 offset;

    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 proj;

    out vec2 textures;

    void main()
    {
        vec3 final_pos = vec3(position.x + offset.x, position.y + offset.y, position.z + offset.z);
        gl_Position =  proj * view * model * vec4(final_pos, 1.0f);
        textures = texture_cords;
    }
    """

    fragment_shader = """
    #version 330
    in vec2 textures;

    out vec4 color;
    uniform sampler2D tex_sampler;

    void main()
    {
        color = texture(tex_sampler, textures);
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                              OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW)

    # position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    # instances
    instance_array = []
    offset = 1

    for z in range(0, 100, 2):
        for y in range(0, 100, 2):
            for x in range(0, 100, 2):
                translation = Vector3([0.0, 0.0, 0.0])
                translation.x = x + offset
                translation.y = y + offset
                translation.z = z + offset
                instance_array.append(translation)

    instance_array = numpy.array(instance_array, numpy.float32).flatten()

    instanceVBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
    glBufferData(GL_ARRAY_BUFFER, instance_array.itemsize * len(instance_array), instance_array, GL_STATIC_DRAW)

    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(2)
    glVertexAttribDivisor(2, 1)

    crate = TextureLoader.load_texture("res/crate.jpg")

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    model = matrix44.create_from_translation(Vector3([-14.0, -8.0, 0.0]))
    projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0)

    model_loc = glGetUniformLocation(shader, "model")
    view_loc = glGetUniformLocation(shader, "view")
    proj_loc = glGetUniformLocation(shader, "proj")

    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        do_movement()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        view = cam.get_view_matrix()
        glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

        glDrawElementsInstanced(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None, 125000)

        glfw.swap_buffers(window)

    glfw.terminate()
Example #41
0
def main():

    # initialize glfw
    if not glfw.init():
        return
    
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    window = glfw.create_window(800, 600, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    #        positions         colors          texture coords
    cube = [-0.5, -0.5,  0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
             0.5, -0.5,  0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
             0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
            -0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

            -0.5, -0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
             0.5, -0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
             0.5,  0.5, -0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
            -0.5,  0.5, -0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

             0.5, -0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
             0.5,  0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
             0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
             0.5, -0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

            -0.5,  0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
            -0.5, -0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
            -0.5, -0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
            -0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

            -0.5, -0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
             0.5, -0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
             0.5, -0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
            -0.5, -0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

             0.5,  0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
            -0.5,  0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
            -0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
             0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0]

    cube = numpy.array(cube, dtype = numpy.float32)

    indices = [ 0,  1,  2,  2,  3,  0,
                4,  5,  6,  6,  7,  4,
                8,  9, 10, 10, 11,  8,
               12, 13, 14, 14, 15, 12,
               16, 17, 18, 18, 19, 16,
               20, 21, 22, 22, 23, 20]

    indices = numpy.array(indices, dtype= numpy.uint32)

    vertex_shader = """
    #version 330
    layout(location = 0) in vec3 position;
    layout(location = 1) in vec3 color;
    layout(location = 2) in vec2 textureCoords;
    uniform mat4 transform;
    out vec3 newColor;
    out vec2 newTexture;
    void main()
    {
        gl_Position = transform * vec4(position, 1.0f);
        newColor = color;
        newTexture = textureCoords;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;
    in vec2 newTexture;

    out vec4 outColor;
    uniform sampler2D samplerTexture;
    void main()
    {
        outColor = texture(samplerTexture, newTexture) * vec4(newColor, 1.0f);
    }
    """

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                              OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW)

    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    #texture
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    # Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # load image
    image = Image.open("res/crate.jpg")
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)
    
    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)
    #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time() )
        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time() )
        
        glUseProgram(shader)
        glBindVertexArray(VAO)
        
        transformLoc = glGetUniformLocation(shader, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y)

        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
        
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    glDeleteProgram(shader)
    glDeleteVertexArrays(1, [VAO])
    glDeleteBuffers(2, [VBO, EBO])

    glfw.terminate()
def main():

    # Initialize GLFW and open a window
    if not opengl_init():
        return

    # Enable key events
    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)
    glfw.set_cursor_pos(window, 1024 / 2, 768 / 2)

    # Set opengl clear color to something other than red (color used by the fragment shader)
    glClearColor(0.0, 0.0, 0.4, 0.0)

    # Enable depth test
    glEnable(GL_DEPTH_TEST)

    # Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS)

    # Cull triangles which normal is not towards the camera
    glEnable(GL_CULL_FACE)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)

    # Create and compile our GLSL program from the shaders
    program_id = common.LoadShaders(
        ".\\shaders\\Tutorial8\\StandardShading.vertexshader",
        ".\\shaders\\Tutorial8\\StandardShading.fragmentshader")

    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP")
    view_matrix_id = glGetUniformLocation(program_id, "V")
    model_matrix_id = glGetUniformLocation(program_id, "M")

    # Load the texture
    texture = load_image(".\\content\\oppo.bmp")  #load image

    # Get a handle for our "myTextureSampler" uniform
    texture_id = glGetUniformLocation(program_id, "myTextureSampler")

    # Read our OBJ file
    # vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj")
    # vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors)

    # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL
    # vertex_data = objloader.generate_2d_ctypes(vertex_data)
    # uv_data = objloader.generate_2d_ctypes(uv_data)

    koordinat = 0.01
    koordinat2 = 0.5
    koordinat3 = 1.7
    koordinat4 = 1.0
    koordinat5 = 1.7
    koordinat6 = 0.1

    vertex_data = [
        -koordinat2, -koordinat3, -koordinat, -koordinat2, -koordinat3,
        koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4,
        koordinat5, -koordinat, -koordinat2, -koordinat3, -koordinat,
        -koordinat2, koordinat5, -koordinat, koordinat4, -koordinat3,
        koordinat6, -koordinat2, -koordinat3, -koordinat, koordinat4,
        -koordinat3, -koordinat, koordinat4, koordinat5, -koordinat,
        koordinat4, -koordinat3, -koordinat, -koordinat2, -koordinat3,
        -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2,
        koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat,
        koordinat4, -koordinat3, koordinat6, -koordinat2, -koordinat3,
        koordinat6, -koordinat2, -koordinat3, -koordinat, -koordinat2,
        koordinat5, koordinat6, -koordinat2, -koordinat3, koordinat6,
        koordinat4, -koordinat3, koordinat6, koordinat4, koordinat5,
        koordinat6, koordinat4, -koordinat3, -koordinat, koordinat4,
        koordinat5, -koordinat, koordinat4, -koordinat3, -koordinat,
        koordinat4, koordinat5, koordinat6, koordinat4, -koordinat3,
        koordinat6, koordinat4, koordinat5, koordinat6, koordinat4, koordinat5,
        -koordinat, -koordinat2, koordinat5, -koordinat, koordinat4,
        koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat,
        -koordinat2, koordinat5, koordinat6, koordinat4, koordinat5,
        koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4,
        -koordinat3, koordinat6
    ]

    # Two UV coordinatesfor each vertex. They were created withe Blender.
    uv_data = [
        0.000059, 1.0 - 0.000004, 0.000103, 1.0 - 0.336048, 0.335973,
        1.0 - 0.335903, 1.000023, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851,
        0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.336024,
        1.0 - 0.671877, 0.667969, 1.0 - 0.671889, 1.000023, 1.0 - 0.000013,
        0.668104, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.000059,
        1.0 - 0.000004, 0.335973, 1.0 - 0.335903, 0.336098, 1.0 - 0.000071,
        0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.336024,
        1.0 - 0.671877, 1.000004, 1.0 - 0.671847, 0.999958, 1.0 - 0.336064,
        0.667979, 1.0 - 0.335851, 0.668104, 1.0 - 0.000013, 0.335973,
        1.0 - 0.335903, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903,
        0.668104, 1.0 - 0.000013, 0.336098, 1.0 - 0.000071, 0.000103,
        1.0 - 0.336048, 0.000004, 1.0 - 0.671870, 0.336024, 1.0 - 0.671877,
        0.000103, 1.0 - 0.336048, 0.336024, 1.0 - 0.671877, 0.335973,
        1.0 - 0.335903, 0.667969, 1.0 - 0.671889, 1.000004, 1.0 - 0.671847,
        0.667979, 1.0 - 0.335851
    ]

    normal_data = [
        -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5,
        0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5,
        -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0,
        0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
        1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
        0, 0, 1, 0, 0, 1
    ]

    # Load OBJ in to a VBO
    vertex_buffer = glGenBuffers(1)
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(vertex_data) * 4, array_type(*vertex_data),
                 GL_STATIC_DRAW)

    uv_buffer = glGenBuffers(1)
    array_type = GLfloat * len(uv_data)
    glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW)

    normal_buffer = glGenBuffers(1)
    array_type = GLfloat * len(normal_data)
    glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(normal_data) * 4, array_type(*normal_data),
                 GL_STATIC_DRAW)

    # vsync and glfw do not play nice.  when vsync is enabled mouse movement is jittery.
    common.disable_vsyc()

    # Get a handle for our "LightPosition" uniform
    glUseProgram(program_id)
    light_id = glGetUniformLocation(program_id, "LightPosition_worldspace")

    last_time = glfw.get_time()
    frames = 0

    while glfw.get_key(
            window, glfw.KEY_ESCAPE
    ) != glfw.PRESS and not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        current_time = glfw.get_time()
        if current_time - last_time >= 1.0:
            glfw.set_window_title(window, "Tutorial 8.  FPS: %d" % (frames))
            frames = 0
            last_time = current_time

        glUseProgram(program_id)

        controls.computeMatricesFromInputs(window)
        ProjectionMatrix = controls.getProjectionMatrix()
        ViewMatrix = controls.getViewMatrix()
        ModelMatrix = mat4.identity()
        mvp = ProjectionMatrix * ViewMatrix * ModelMatrix

        # Send our transformation to the currently bound shader,
        # in the "MVP" uniform
        glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data)
        glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data)
        glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data)

        lightPos = vec3(4, 4, 4)
        glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z)

        # Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, texture)
        # Set our "myTextureSampler" sampler to user Texture Unit 0
        glUniform1i(texture_id, 0)

        #1rst attribute buffer : vertices
        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
        glVertexAttribPointer(
            0,  # attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,  # len(vertex_data)
            GL_FLOAT,  # type
            GL_FALSE,  # ormalized?
            0,  # stride
            null  # array buffer offset (c_type == void*)
        )

        # 2nd attribute buffer : colors
        glEnableVertexAttribArray(1)
        glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
        glVertexAttribPointer(
            1,  # attribute 1. No particular reason for 1, but must match the layout in the shader.
            2,  # len(vertex_data)
            GL_FLOAT,  # type
            GL_FALSE,  # ormalized?
            0,  # stride
            null  # array buffer offset (c_type == void*)
        )

        # 3rd attribute buffer : normals
        glEnableVertexAttribArray(2)
        glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
        glVertexAttribPointer(
            2,  # attribute
            3,  # size
            GL_FLOAT,  # type
            GL_FALSE,  # ormalized?
            0,  # stride
            null  # array buffer offset (c_type == void*)
        )

        # Draw the triangles, vertex data now contains individual vertices
        # so use array length
        glDrawArrays(GL_TRIANGLES, 0, len(vertex_data))

        # Not strictly necessary because we only have
        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

        frames += 1

    # !Note braces around vertex_buffer and uv_buffer.
    # glDeleteBuffers expects a list of buffers to delete
    glDeleteBuffers(1, [vertex_buffer])
    glDeleteBuffers(1, [uv_buffer])
    glDeleteBuffers(1, [normal_buffer])
    glDeleteProgram(program_id)
    glDeleteTextures([texture_id])
    glDeleteVertexArrays(1, [vertex_array_id])

    glfw.terminate()
def main():
    # initalize glfw
    if not glfw.init():
        return

    window = glfw.create_window(800, 600, "My OpenGL Window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    # Create shaders
    vertex_shader = """
    #version 330
    in vec3 position;
    in vec3 color;
    uniform mat4 transform;

    out vec3 newColor;

    void main()
    {
        gl_Position = transform * vec4(position, 1.0f);
        newColor = color;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;
    out vec4 outColor;

    void main()
    {
        outColor = vec4(newColor, 1.0f);
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))
    # Create triangle
    #    POSITIONS      COLORS
    cube = np.array([
        -0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        1.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        1.0,
        0.0,
        0.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        -0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        1.0,
    ],
                    dtype=np.float32)

    indices = np.array([
        0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6,
        5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7
    ],
                       dtype=np.uint32)

    # Create buffer on GPU
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 8 * 6 * 4, cube,
                 GL_STATIC_DRAW)  # 6 * 4 values * 4 bytes

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * 6 * 4, indices,
                 GL_STATIC_DRAW)  # 6 values * 4 bytes

    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(12))
    # 12 is the starting position of color in the array. Since we have three 4 bytes for position, color will start at 12

    glEnableVertexAttribArray(color)

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_x = pyrr.Matrix44.from_x_rotation(0.5 * np.pi * glfw.get_time())
        rot_y = pyrr.Matrix44.from_y_rotation(0.08 * np.pi * glfw.get_time())

        transformLoc = glGetUniformLocation(shader, "transform")

        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y)

        glDrawElements(GL_TRIANGLES, 6 * 6, GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
Example #44
0
def main():
    # Check arguments
    if (len(sys.argv) != 2):
        print('Please add the name of the json file as an argument.')
        print('Example: python main.py unicorn')
        return
    file_name = sys.argv[1]

    # Initialize glfw
    if not glfw.init():
        return

    window = glfw.create_window(800, 600, "My OpenGL Window", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    # import json file containing vertices & elements
    json_file = open(os.path.join(os.path.dirname(__file__), 'res', file_name + '.json'))
    data = json.load(json_file)

    # Create a Vertex Buffer Object and copy the vertex data to it
    vbo = glGenBuffers(1)
    vertices = numpy.array(data['vertices'], dtype=numpy.float32)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, len(vertices) * 4, vertices, GL_STATIC_DRAW)

    # Create an element array
    ebo = glGenBuffers(1)
    elements = numpy.array(data['elements'], dtype=numpy.uint32)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(elements) * 4, elements, GL_STATIC_DRAW)

    # Create vertex shader
    vertex_shader = """
        #version 150 core
        in vec2 position;
        in vec3 color;
        out vec3 Color;
        void main()
        {
            Color = color;
            gl_Position = vec4(position, 0.0, 1.0);
        }
    """

    # Create fragment shader
    fragment_shader = """
        #version 150 core
        in vec3 Color;
        out vec4 outColor;
        void main()
        {
            outColor = vec4(Color, 1.0);
        }
    """

    # Compile vertex and fragment shader
    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                              OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    # Specify the layout of the vertex data
    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(8))
    glEnableVertexAttribArray(color)

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 0.1)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        glDrawElements(GL_TRIANGLES, len(elements), GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
Example #45
0
def main():
    glfw.init()
    window = glfw.create_window(640, 320, "Chip8", None, None)
    glfw.make_context_current(window)

    program = glCreateProgram()

    with open("vertex.glsl") as source:
        vertex = glCreateShader(GL_VERTEX_SHADER)
        glShaderSource(vertex, source.read())
        glCompileShader(vertex)
        glAttachShader(program, vertex)

    with open("fragment.glsl") as source:
        fragment = glCreateShader(GL_FRAGMENT_SHADER)
        glShaderSource(fragment, source.read())
        glCompileShader(fragment)
        glAttachShader(program, fragment)

    glLinkProgram(program)

    vbo = glGenBuffers(1)
    vao = glGenVertexArrays(1)

    glBindVertexArray(vao)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(0)

    glBindVertexArray(0)

    program_counter = 0x200
    index = 0

    display   = [[0] * 64 for _ in range(32)]
    memory    = [0] * 4096
    variables = [0] * 16
    stack     = [ ]

    delay_timer = 0
    sound_timer = 0

    memory[0: 80] = [
        0xF0, 0x90, 0x90, 0x90, 0xF0,  # 0
        0x20, 0x60, 0x20, 0x20, 0x70,  # 1
        0xF0, 0x10, 0xF0, 0x80, 0xF0,  # 2
        0xF0, 0x10, 0xF0, 0x10, 0xF0,  # 3
        0x90, 0x90, 0xF0, 0x10, 0x10,  # 4
        0xF0, 0x80, 0xF0, 0x10, 0xF0,  # 5
        0xF0, 0x80, 0xF0, 0x90, 0xF0,  # 6
        0xF0, 0x10, 0x20, 0x40, 0x40,  # 7
        0xF0, 0x90, 0xF0, 0x90, 0xF0,  # 8
        0xF0, 0x90, 0xF0, 0x10, 0xF0,  # 9
        0xF0, 0x90, 0xF0, 0x90, 0x90,  # A
        0xE0, 0x90, 0xE0, 0x90, 0xE0,  # B
        0xF0, 0x80, 0x80, 0x80, 0xF0,  # C
        0xE0, 0x90, 0x90, 0x90, 0xE0,  # D
        0xF0, 0x80, 0xF0, 0x80, 0xF0,  # E
        0xF0, 0x80, 0xF0, 0x80, 0x80  # F
    ]

    binary = open("roms/" + input("Program? :> ") + ".ch8", "rb")

    for i, byte in enumerate(binary.read()):
        memory[0x200 + i] = byte

    binary.close()

    timer_clock = time.time()
    cycle_clock = time.time()

    while not glfw.window_should_close(window):
        if time.time() - timer_clock >= 1 / 60:
            if sound_timer > 0:
                sound_timer -= 1
            if delay_timer > 0:
                delay_timer -= 1

            timer_clock = time.time()

        if time.time() - cycle_clock >= 1 / 500:
            glfw.poll_events()

            opcode = memory[program_counter] << 8 | memory[program_counter + 1]

            x   = (opcode & 0x0F00) >> 8
            y   = (opcode & 0x00F0) >> 4
            n   = (opcode & 0x000F)
            nn  = (opcode & 0x00FF)
            nnn = (opcode & 0x0FFF)

            if (opcode & 0xF00F) == 0x0000:
                display = [[0] * 64 for _ in range(32)]

            if (opcode & 0xF00F) == 0x000E:
                program_counter = stack.pop()

            if (opcode & 0xF000) == 0x1000:
                program_counter = nnn - 2

            if (opcode & 0xF000) == 0x2000:
                stack.append(program_counter)
                program_counter = nnn - 2

            if (opcode & 0xF000) == 0x3000:
                if variables[x] == nn:
                    program_counter += 2

            if (opcode & 0xF000) == 0x4000:
                if variables[x] != nn:
                    program_counter += 2

            if (opcode & 0xF000) == 0x5000:
                if variables[x] == variables[y]:
                    program_counter += 2

            if (opcode & 0xF000) == 0x6000:
                variables[x] = nn

            if (opcode & 0xF000) == 0x7000:
                variables[x] = (variables[x] + nn) % 256

            if (opcode & 0xF00F) == 0x8000:
                variables[x] = variables[y]

            if (opcode & 0xF00F) == 0x8001:
                variables[x] = variables[x] | variables[y]

            if (opcode & 0xF00F) == 0x8002:
                variables[x] = variables[x] & variables[y]

            if (opcode & 0xF00F) == 0x8003:
                variables[x] = variables[x] ^ variables[y]

            if (opcode & 0xF00F) == 0x8004:
                if variables[x] + variables[y] > 255:
                    variables[0xF] = 1
                else:
                    variables[0xF] = 0

                variables[x] = (variables[x] + variables[y]) % 256

            if (opcode & 0xF00F) == 0x8005:
                if variables[x] > variables[y]:
                    variables[0xF] = 1
                else:
                    variables[0xF] = 0

                variables[x] = (variables[x] - variables[y]) % 256

            if (opcode & 0xF00F) == 0x8006:
                variables[0xF] = variables[x] & 1
                variables[x] = variables[x] >> 1

            if (opcode & 0xF00F) == 0x8007:
                if variables[y] > variables[x]:
                    variables[0xF] = 1
                else:
                    variables[0xF] = 0

                variables[x] = (variables[y] - variables[x]) % 256

            if (opcode & 0xF00F) == 0x800E:
                variables[0xF] = variables[x] >> 7
                variables[x] = (variables[x] << 1) % 256

            if (opcode & 0xF000) == 0x9000:
                if variables[x] != variables[y]:
                    program_counter += 2

            if (opcode & 0xF000) == 0xA000:
                index = nnn

            if (opcode & 0xF000) == 0xB000:
                program_counter = nnn + variables[0] - 2

            if (opcode & 0xF000) == 0xC000:
                variables[x] = random.randint(0, 255) & nn

            if (opcode & 0xF000) == 0xD000:  # todo
                variables[0xF] = 0
                x_pos, y_pos = variables[x] % 64, variables[y] % 32
                sprite = memory[index: index + n]

                for y_sprite, row in enumerate(sprite):
                    for x_sprite, pixel in enumerate(bin(row)[2:].zfill(8)):
                        pixel_x = x_pos + x_sprite
                        pixel_y = y_pos + y_sprite

                        if pixel_x >= 64 or pixel_y >= 32:
                            continue

                        if display[pixel_y][pixel_x] == 1 and int(pixel) == 1:
                            variables[0xF] = 1

                        display[pixel_y][pixel_x] ^= int(pixel)

            if (opcode & 0xF00F) == 0xE00E:
                if keyboard(window)[variables[x]] == 1:
                    program_counter += 2

            if (opcode & 0xF00F) == 0xE001:
                if keyboard(window)[variables[x]] == 0:
                    program_counter += 2

            if opcode & 0xF0FF == 0xF007:
                variables[x] = delay_timer

            if opcode & 0xF0FF == 0xF00A:
                key_press = False

                while not key_press:
                    for key, value in keyboard(window).items():
                        if value == 1:
                            variables[x] = key
                            key_press = True
                            break

            if opcode & 0xF0FF == 0xF015:
                delay_timer = variables[x]

            if opcode & 0xF0FF == 0xF018:
                sound_timer = variables[x]

            if opcode & 0xF0FF == 0xF01E:
                index = variables[x] + index

            if opcode & 0xF0FF == 0xF029:
                index = variables[x] * 5

            if opcode & 0xF0FF == 0xF033:
                memory[index + 0] = (variables[x] // 100) % 10
                memory[index + 1] = (variables[x] // 10) % 10
                memory[index + 2] = (variables[x] // 1) % 10

            if opcode & 0xF0FF == 0xF055:
                memory[index: index + x + 1] = variables[:x + 1]

            if opcode & 0xF0FF == 0xF065:
                variables[:x + 1] = memory[index: index + x + 1]

            glClear(GL_COLOR_BUFFER_BIT)
            glUseProgram(program)

            width, height = glfw.get_window_size(window)
            matrix = glm.ortho(0, width, height, 0)

            location = glGetUniformLocation(program, "ortho_matrix")
            glUniformMatrix4fv(location, 1, GL_FALSE, glm.value_ptr(matrix))

            verticies = []
            for x in range(64):
                for y in range(32):
                    if display[y][x] == 1:
                        verticies.extend([
                            (x    ) * 10, (y    ) * 10,
                            (x + 1) * 10, (y    ) * 10,
                            (x    ) * 10, (y + 1) * 10,
                            (x + 1) * 10, (y + 1) * 10,
                            (x    ) * 10, (y + 1) * 10,
                            (x + 1) * 10, (y    ) * 10
                        ])

            verticies = numpy.array(verticies, dtype=numpy.float32)

            glBindVertexArray(vao)
            glBindBuffer(GL_ARRAY_BUFFER, vbo)
            glBufferData(GL_ARRAY_BUFFER, verticies.nbytes, verticies, GL_DYNAMIC_DRAW)

            glDrawArrays(GL_TRIANGLES, 0, len(verticies))

            glBindVertexArray(0)
            glUseProgram(0)

            glfw.swap_buffers(window)

            program_counter += 2
            cycle_clock = time.time()
    glfw.terminate()
Example #46
0
def vista():

    # Initialize glfw
    if not glfw.init(): sys.exit()

    WIDTH = 1000
    HEIGHT = 800

    window = glfw.create_window(WIDTH, HEIGHT, "DISCO SNOK! 3D", None, None)

    if not window:
        glfw.terminate()
        sys.exit()

    glfw.make_context_current(window)

    ctrl = Controller()
    glfw.set_key_callback(window, ctrl.on_key)

    # Assembling the shader program (pipeline) with all shaders
    pipeline = es.SimpleModelViewProjectionShaderProgram()  # SIMPLE PIPELINE
    texture_pipeline = es.SimpleTextureModelViewProjectionShaderProgram(
    )  # TEXTURE PIPELINE
    lighting_pipeline = ls.SimpleTexturePhongShaderProgram(
    )  # LIGHTING PIPELINE
    phong_pipeline = ls.SimplePhongShaderProgram()  # PHONG PIPELINE

    # Telling OpenGL to use our shader program
    glUseProgram(pipeline.shaderProgram)

    # Setting up the clear screen color
    glClearColor(0.0, 0.0, 0.0, 1.0)

    # As we work in 3D, we need to check which part is in front,
    # and which one is at the back
    glEnable(GL_DEPTH_TEST)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

    # Using the same view and projection matrices in the whole application
    projection = tr.perspective(45, float(WIDTH) / float(HEIGHT), 0.1, 100)

    # MODELOS
    floor = Floor()
    vinyl = Vinyl()
    snake = Snake()
    ctrl.snake = snake.snake_parts[0]
    snake.objective = vinyl
    snake.floor = floor
    vinyl.bans = snake.positions
    screens = Screens()
    camera = Camera()
    camera.snakeView = snake.snake_parts[0]
    ctrl.camera = camera

    wall = bs.createTextureCube(os.path.join("img", "clouds.png"))
    GPUwall = es.toGPUShape(wall, GL_REPEAT, GL_NEAREST)
    wallTransform = tr.matmul(
        [tr.translate(0, 0, 0),
         tr.uniformScale(50),
         tr.uniformScale(1)])
    building = bs.createTextureCube(os.path.join("img", "building.png"))
    GPUbuilding = es.toGPUShape(building, GL_REPEAT, GL_NEAREST)
    buildingTransform = tr.matmul(
        [tr.translate(0, 0, -10.01),
         tr.scale(20, 20, 10),
         tr.uniformScale(1)])
    bottom = bs.createColorCube(0.0, 0.0, 0.0)
    GPUbottom = es.toGPUShape(bottom, GL_REPEAT, GL_NEAREST)
    bottomTransform = tr.matmul(
        [tr.translate(0, 0, -22),
         tr.scale(49.9, 49.9, 1),
         tr.uniformScale(1)])

    limitFPS = 1.0 / 30.0

    lastTime = 0
    timer = 0

    deltaTime = 0
    nowTime = 0

    frames = 0
    updates = 0

    playsound(os.path.join("sound", "Conga_2.mp3"), block=False)

    while not glfw.window_should_close(window):
        # Using GLFW to check for input events
        glfw.poll_events()

        # Clearing the screen in both, color and depth
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Main Menu
        if not ctrl.gameStart:
            view = tr.lookAt(
                np.array([0, 0, 20]),  # eye
                np.array([0.0001, 0, 0]),  # at
                np.array([0, 0, 1])  # up
            )

            glUseProgram(texture_pipeline.shaderProgram)
            wallTransform0 = tr.matmul([
                tr.translate(0, 0, 0),
                tr.scale(22, 22, 0.001),
                tr.uniformScale(1),
                tr.rotationZ(3 * np.pi / 2)
            ])
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram, "model"),
                1, GL_TRUE, wallTransform0)
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram,
                                     "projection"), 1, GL_TRUE, projection)
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram, "view"),
                1, GL_TRUE, view)
            texture_pipeline.drawShape(GPUwall)

            screens.mainMenu(lighting_pipeline, projection, view,
                             phong_pipeline)
            glfw.swap_buffers(window)
            continue
        elif ctrl.gameStart and lastTime == 0:
            lastTime = glfw.get_time()
            timer = lastTime

        # GAME OVER
        if not snake.alive:
            view = tr.lookAt(
                np.array([0, 0, 20]),  # eye
                np.array([0.0001, 0, 0]),  # at
                np.array([0, 0, 1])  # up
            )

            glUseProgram(texture_pipeline.shaderProgram)
            wallTransform0 = tr.matmul([
                tr.translate(0, 0, 0),
                tr.scale(22, 22, 0.001),
                tr.uniformScale(1),
                tr.rotationZ(3 * np.pi / 2)
            ])
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram, "model"),
                1, GL_TRUE, wallTransform0)
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram,
                                     "projection"), 1, GL_TRUE, projection)
            glUniformMatrix4fv(
                glGetUniformLocation(texture_pipeline.shaderProgram, "view"),
                1, GL_TRUE, view)
            texture_pipeline.drawShape(GPUwall)

            screens.gameOver(lighting_pipeline, projection, view)
            glfw.swap_buffers(window)
            continue

        # Calculamos el dt
        nowTime = glfw.get_time()
        deltaTime += (nowTime - lastTime) / limitFPS
        lastTime = nowTime

        if not vinyl.exists:
            vinyl.spawn()

        while deltaTime >= 1.0:
            vinyl.update()
            snake.move()
            floor.timer += 1
            if floor.timer % 20 == 0:
                floor.floorPicker += 1
            if floor.weirdTimer > 0:
                if floor.weirdTimer % 10 == 0:
                    floor.update()
                    snake.weirdLight = (floor.r, floor.g, floor.b)
                    snake.lightChange()
                floor.weirdTimer -= 1
                if floor.weirdTimer == 0:
                    snake.weirdLight = (1.0, 1.0, 1.0)
                    snake.lightChange()
            updates += 1
            deltaTime -= 1.0

        view = camera.view()

        if timer > 2.0:
            snake.collisions()

        glUseProgram(texture_pipeline.shaderProgram)

        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "model"), 1,
            GL_TRUE, wallTransform)
        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "projection"),
            1, GL_TRUE, projection)
        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "view"), 1,
            GL_TRUE, view)
        texture_pipeline.drawShape(GPUwall)

        glUseProgram(texture_pipeline.shaderProgram)

        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "model"), 1,
            GL_TRUE, buildingTransform)
        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "projection"),
            1, GL_TRUE, projection)
        glUniformMatrix4fv(
            glGetUniformLocation(texture_pipeline.shaderProgram, "view"), 1,
            GL_TRUE, view)
        texture_pipeline.drawShape(GPUbuilding)

        glUseProgram(pipeline.shaderProgram)

        glUniformMatrix4fv(
            glGetUniformLocation(pipeline.shaderProgram, "model"), 1, GL_TRUE,
            bottomTransform)
        glUniformMatrix4fv(
            glGetUniformLocation(pipeline.shaderProgram, "projection"), 1,
            GL_TRUE, projection)
        glUniformMatrix4fv(
            glGetUniformLocation(pipeline.shaderProgram, "view"), 1, GL_TRUE,
            view)
        pipeline.drawShape(GPUbottom)

        glUseProgram(lighting_pipeline.shaderProgram)
        floor.draw(lighting_pipeline, projection, view)
        snake.draw(lighting_pipeline, projection, view)
        vinyl.draw(phong_pipeline, projection, view)

        frames += 1

        # Once the render is done, buffers are swapped, showing only the complete scene.
        glfw.swap_buffers(window)

        if glfw.get_time() - timer > 1.0:
            timer += 1
            # print("FPS: ",frames," Updates: ",updates)
            updates = 0
            frames = 0

    glfw.terminate()
Example #47
0
def world(
    timebase,
    eye_procs_alive,
    ipc_pub_url,
    ipc_sub_url,
    ipc_push_url,
    user_dir,
    version,
    preferred_remote_port,
    hide_ui,
    debug,
):
    """Reads world video and runs plugins.

    Creates a window, gl context.
    Grabs images from a capture.
    Maps pupil to gaze data
    Can run various plug-ins.

    Reacts to notifications:
        ``eye_process.started``
        ``start_plugin``
        ``should_stop``

    Emits notifications:
        ``eye_process.should_start``
        ``eye_process.should_stop``
        ``world_process.started``
        ``world_process.stopped``
        ``recording.should_stop``: Emits on camera failure
        ``launcher_process.should_stop``

    Emits data:
        ``gaze``: Gaze data from current gaze mapping plugin.``
        ``*``: any other plugin generated data in the events
               that it not [dt,pupil,gaze].
    """

    # We defer the imports because of multiprocessing.
    # Otherwise the world process each process also loads the other imports.
    # This is not harmful but unnecessary.

    # general imports
    from time import sleep
    import logging

    # networking
    import zmq
    import zmq_tools

    # zmq ipc setup
    zmq_ctx = zmq.Context()
    ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url)
    notify_sub = zmq_tools.Msg_Receiver(zmq_ctx,
                                        ipc_sub_url,
                                        topics=("notify", ))

    # log setup
    logging.getLogger("OpenGL").setLevel(logging.ERROR)
    logger = logging.getLogger()
    logger.handlers = []
    logger.setLevel(logging.NOTSET)
    logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url))
    # create logger for the context of this function
    logger = logging.getLogger(__name__)

    def launch_eye_process(eye_id, delay=0):
        n = {
            "subject": "eye_process.should_start.{}".format(eye_id),
            "eye_id": eye_id,
            "delay": delay,
        }
        ipc_pub.notify(n)

    def stop_eye_process(eye_id):
        n = {
            "subject": "eye_process.should_stop.{}".format(eye_id),
            "eye_id": eye_id,
            "delay": 0.2,
        }
        ipc_pub.notify(n)

    def start_stop_eye(eye_id, make_alive):
        if make_alive:
            launch_eye_process(eye_id)
        else:
            stop_eye_process(eye_id)

    def detection_enabled_getter() -> int:
        return int(g_pool.pupil_detection_enabled)

    def detection_enabled_setter(value: int):
        is_on = bool(value)
        g_pool.pupil_detection_enabled = is_on
        n = {"subject": "pupil_detector.set_enabled", "value": is_on}
        ipc_pub.notify(n)

    try:
        from background_helper import IPC_Logging_Task_Proxy

        IPC_Logging_Task_Proxy.push_url = ipc_push_url

        from tasklib.background.patches import IPCLoggingPatch

        IPCLoggingPatch.ipc_push_url = ipc_push_url

        from OpenGL.GL import GL_COLOR_BUFFER_BIT

        # display
        import glfw
        from gl_utils import GLFWErrorReporting

        GLFWErrorReporting.set_default()

        from version_utils import parse_version
        from pyglui import ui, cygl, __version__ as pyglui_version

        assert parse_version(pyglui_version) >= parse_version(
            "1.30.0"), "pyglui out of date, please upgrade to newest version"
        from pyglui.cygl.utils import Named_Texture
        import gl_utils

        # helpers/utils
        from file_methods import Persistent_Dict
        from methods import normalize, denormalize, delta_t, get_system_info, timer
        from uvc import get_time_monotonic

        logger.info("Application Version: {}".format(version))
        logger.info("System Info: {}".format(get_system_info()))
        logger.debug(f"Debug flag: {debug}")

        import audio

        # Plug-ins
        from plugin import (
            Plugin,
            System_Plugin_Base,
            Plugin_List,
            import_runtime_plugins,
        )
        from plugin_manager import Plugin_Manager
        from calibration_choreography import (
            available_calibration_choreography_plugins,
            CalibrationChoreographyPlugin,
            patch_loaded_plugins_with_choreography_plugin,
        )

        available_choreography_plugins = available_calibration_choreography_plugins(
        )

        from gaze_mapping import registered_gazer_classes
        from gaze_mapping.gazer_base import GazerBase
        from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin
        from fixation_detector import Fixation_Detector
        from recorder import Recorder
        from display_recent_gaze import Display_Recent_Gaze
        from time_sync import Time_Sync
        from network_api import NetworkApiPlugin
        from pupil_groups import Pupil_Groups
        from surface_tracker import Surface_Tracker_Online
        from log_display import Log_Display
        from annotations import Annotation_Capture
        from log_history import Log_History
        from blink_detection import Blink_Detection
        from video_capture import (
            source_classes,
            manager_classes,
            Base_Manager,
            Base_Source,
        )
        from pupil_data_relay import Pupil_Data_Relay
        from remote_recorder import Remote_Recorder
        from accuracy_visualizer import Accuracy_Visualizer

        from system_graphs import System_Graphs
        from camera_intrinsics_estimation import Camera_Intrinsics_Estimation
        from hololens_relay import Hololens_Relay
        from head_pose_tracker.online_head_pose_tracker import Online_Head_Pose_Tracker

        # UI Platform tweaks
        if platform.system() == "Linux":
            scroll_factor = 10.0
            window_position_default = (30, 30)
        elif platform.system() == "Windows":
            scroll_factor = 10.0
            window_position_default = (8, 90)
        else:
            scroll_factor = 1.0
            window_position_default = (0, 0)

        process_was_interrupted = False

        def interrupt_handler(sig, frame):
            import traceback

            trace = traceback.format_stack(f=frame)
            logger.debug(f"Caught signal {sig} in:\n" + "".join(trace))
            nonlocal process_was_interrupted
            process_was_interrupted = True

        signal.signal(signal.SIGINT, interrupt_handler)

        icon_bar_width = 50
        window_size = None
        camera_render_size = None
        content_scale = 1.0

        # g_pool holds variables for this process they are accessible to all plugins
        g_pool = SimpleNamespace()
        g_pool.debug = debug
        g_pool.app = "capture"
        g_pool.process = "world"
        g_pool.user_dir = user_dir
        g_pool.version = version
        g_pool.timebase = timebase
        g_pool.zmq_ctx = zmq_ctx
        g_pool.ipc_pub = ipc_pub
        g_pool.ipc_pub_url = ipc_pub_url
        g_pool.ipc_sub_url = ipc_sub_url
        g_pool.ipc_push_url = ipc_push_url
        g_pool.eye_procs_alive = eye_procs_alive
        g_pool.preferred_remote_port = preferred_remote_port

        def get_timestamp():
            return get_time_monotonic() - g_pool.timebase.value

        g_pool.get_timestamp = get_timestamp
        g_pool.get_now = get_time_monotonic

        # manage plugins
        runtime_plugins = import_runtime_plugins(
            os.path.join(g_pool.user_dir, "plugins"))
        runtime_plugins = [
            p for p in runtime_plugins
            if not issubclass(p, PupilDetectorPlugin)
        ]
        user_plugins = [
            Pupil_Groups,
            NetworkApiPlugin,
            Time_Sync,
            Surface_Tracker_Online,
            Annotation_Capture,
            Log_History,
            Fixation_Detector,
            Blink_Detection,
            Remote_Recorder,
            Accuracy_Visualizer,
            Camera_Intrinsics_Estimation,
            Hololens_Relay,
            Online_Head_Pose_Tracker,
        ]

        system_plugins = ([
            Log_Display,
            Display_Recent_Gaze,
            Recorder,
            Pupil_Data_Relay,
            Plugin_Manager,
            System_Graphs,
        ] + manager_classes + source_classes)
        plugins = (system_plugins + user_plugins + runtime_plugins +
                   available_choreography_plugins + registered_gazer_classes())
        user_plugins += [
            p for p in runtime_plugins if not isinstance(
                p,
                (
                    Base_Manager,
                    Base_Source,
                    System_Plugin_Base,
                    CalibrationChoreographyPlugin,
                    GazerBase,
                ),
            )
        ]
        g_pool.plugin_by_name = {p.__name__: p for p in plugins}

        default_capture_name = "UVC_Source"
        default_capture_settings = {
            "preferred_names": [
                "Pupil Cam1 ID2",
                "Logitech Camera",
                "(046d:081d)",
                "C510",
                "B525",
                "C525",
                "C615",
                "C920",
                "C930e",
            ],
            "frame_size": (1280, 720),
            "frame_rate":
            30,
        }

        default_plugins = [
            (default_capture_name, default_capture_settings),
            ("Pupil_Data_Relay", {}),
            ("UVC_Manager", {}),
            ("NDSI_Manager", {}),
            ("HMD_Streaming_Manager", {}),
            ("File_Manager", {}),
            ("Log_Display", {}),
            ("Dummy_Gaze_Mapper", {}),
            ("Display_Recent_Gaze", {}),
            # Calibration choreography plugin is added below by calling
            # patch_loaded_plugins_with_choreography_plugin
            ("Recorder", {}),
            ("NetworkApiPlugin", {}),
            ("Fixation_Detector", {}),
            ("Blink_Detection", {}),
            ("Accuracy_Visualizer", {}),
            ("Plugin_Manager", {}),
            ("System_Graphs", {}),
        ]

        def consume_events_and_render_buffer():
            gl_utils.glViewport(0, 0, *camera_render_size)
            for p in g_pool.plugins:
                p.gl_display()

            gl_utils.glViewport(0, 0, *window_size)
            try:
                clipboard = glfw.get_clipboard_string(main_window).decode()
            except (AttributeError, glfw.GLFWError):
                # clipboard is None, might happen on startup
                clipboard = ""
            g_pool.gui.update_clipboard(clipboard)
            user_input = g_pool.gui.update()
            if user_input.clipboard != clipboard:
                # only write to clipboard if content changed
                glfw.set_clipboard_string(main_window, user_input.clipboard)

            for button, action, mods in user_input.buttons:
                x, y = glfw.get_cursor_pos(main_window)
                pos = gl_utils.window_coordinate_to_framebuffer_coordinate(
                    main_window, x, y, cached_scale=None)
                pos = normalize(pos, camera_render_size)
                # Position in img pixels
                pos = denormalize(pos, g_pool.capture.frame_size)

                for plugin in g_pool.plugins:
                    if plugin.on_click(pos, button, action):
                        break

            for key, scancode, action, mods in user_input.keys:
                for plugin in g_pool.plugins:
                    if plugin.on_key(key, scancode, action, mods):
                        break

            for char_ in user_input.chars:
                for plugin in g_pool.plugins:
                    if plugin.on_char(char_):
                        break

            glfw.swap_buffers(main_window)

        # Callback functions
        def on_resize(window, w, h):
            nonlocal window_size
            nonlocal camera_render_size
            nonlocal content_scale
            if w == 0 or h == 0:
                return

            # Always clear buffers on resize to make sure that there are no overlapping
            # artifacts from previous frames.
            gl_utils.glClear(GL_COLOR_BUFFER_BIT)
            gl_utils.glClearColor(0, 0, 0, 1)

            content_scale = gl_utils.get_content_scale(window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(window)
            g_pool.gui.scale = content_scale
            window_size = w, h
            camera_render_size = w - int(icon_bar_width * g_pool.gui.scale), h
            g_pool.gui.update_window(*window_size)
            g_pool.gui.collect_menus()

            for p in g_pool.plugins:
                p.on_window_resize(window, *camera_render_size)

            # Minimum window size required, otherwise parts of the UI can cause openGL
            # issues with permanent effects. Depends on the content scale, which can
            # potentially be dynamically modified, so we re-adjust the size limits every
            # time here.
            min_size = int(2 * icon_bar_width * g_pool.gui.scale /
                           framebuffer_scale)
            glfw.set_window_size_limits(
                window,
                min_size,
                min_size,
                glfw.DONT_CARE,
                glfw.DONT_CARE,
            )

            # Needed, to update the window buffer while resizing
            with gl_utils.current_context(main_window):
                consume_events_and_render_buffer()

        def on_window_key(window, key, scancode, action, mods):
            g_pool.gui.update_key(key, scancode, action, mods)

        def on_window_char(window, char):
            g_pool.gui.update_char(char)

        def on_window_mouse_button(window, button, action, mods):
            g_pool.gui.update_button(button, action, mods)

        def on_pos(window, x, y):
            x, y = gl_utils.window_coordinate_to_framebuffer_coordinate(
                window, x, y, cached_scale=None)
            g_pool.gui.update_mouse(x, y)
            pos = x, y
            pos = normalize(pos, camera_render_size)
            # Position in img pixels
            pos = denormalize(pos, g_pool.capture.frame_size)
            for p in g_pool.plugins:
                p.on_pos(pos)

        def on_scroll(window, x, y):
            g_pool.gui.update_scroll(x, y * scroll_factor)

        def on_drop(window, paths):
            for plugin in g_pool.plugins:
                if plugin.on_drop(paths):
                    break

        tick = delta_t()

        def get_dt():
            return next(tick)

        # load session persistent settings
        session_settings = Persistent_Dict(
            os.path.join(g_pool.user_dir, "user_settings_world"))
        if parse_version(session_settings.get("version",
                                              "0.0")) != g_pool.version:
            logger.info(
                "Session setting are from a different version of this app. I will not use those."
            )
            session_settings.clear()

        g_pool.min_data_confidence = 0.6
        g_pool.min_calibration_confidence = session_settings.get(
            "min_calibration_confidence", 0.8)
        g_pool.pupil_detection_enabled = bool(
            session_settings.get("pupil_detection_enabled", True))
        g_pool.active_gaze_mapping_plugin = None
        g_pool.capture = None

        audio.set_audio_mode(
            session_settings.get("audio_mode", audio.get_default_audio_mode()))

        def handle_notifications(noti):
            subject = noti["subject"]
            if subject == "pupil_detector.set_enabled":
                g_pool.pupil_detection_enabled = noti["value"]
            elif subject == "start_plugin":
                try:
                    g_pool.plugins.add(g_pool.plugin_by_name[noti["name"]],
                                       args=noti.get("args", {}))
                except KeyError as err:
                    logger.error(f"Attempt to load unknown plugin: {err}")
            elif subject == "stop_plugin":
                for p in g_pool.plugins:
                    if p.class_name == noti["name"]:
                        p.alive = False
                        g_pool.plugins.clean()
            elif subject == "eye_process.started":
                noti = {
                    "subject": "pupil_detector.set_enabled",
                    "value": g_pool.pupil_detection_enabled,
                }
                ipc_pub.notify(noti)
            elif subject == "set_min_calibration_confidence":
                g_pool.min_calibration_confidence = noti["value"]
            elif subject.startswith("meta.should_doc"):
                ipc_pub.notify({
                    "subject": "meta.doc",
                    "actor": g_pool.app,
                    "doc": world.__doc__
                })
                for p in g_pool.plugins:
                    if (p.on_notify.__doc__
                            and p.__class__.on_notify != Plugin.on_notify):
                        ipc_pub.notify({
                            "subject": "meta.doc",
                            "actor": p.class_name,
                            "doc": p.on_notify.__doc__,
                        })
            elif subject == "world_process.adapt_window_size":
                set_window_size()
            elif subject == "world_process.should_stop":
                glfw.set_window_should_close(main_window, True)

        width, height = session_settings.get("window_size",
                                             (1280 + icon_bar_width, 720))

        # window and gl setup
        glfw.init()
        glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE)
        if hide_ui:
            glfw.window_hint(glfw.VISIBLE, 0)  # hide window
        main_window = glfw.create_window(width, height,
                                         "Pupil Capture - World", None, None)

        window_position_manager = gl_utils.WindowPositionManager()
        window_pos = window_position_manager.new_window_position(
            window=main_window,
            default_position=window_position_default,
            previous_position=session_settings.get("window_position", None),
        )
        glfw.set_window_pos(main_window, window_pos[0], window_pos[1])

        glfw.make_context_current(main_window)
        cygl.utils.init()
        g_pool.main_window = main_window

        def reset_restart():
            logger.warning("Resetting all settings and restarting Capture.")
            glfw.set_window_should_close(main_window, True)
            ipc_pub.notify({"subject": "clear_settings_process.should_start"})
            ipc_pub.notify({
                "subject": "world_process.should_start",
                "delay": 2.0
            })

        def toggle_general_settings(collapsed):
            # this is the menu toggle logic.
            # Only one menu can be open.
            # If no menu is opened, the menubar should collapse.
            g_pool.menubar.collapsed = collapsed
            for m in g_pool.menubar.elements:
                m.collapsed = True
            general_settings.collapsed = collapsed

        # setup GUI
        g_pool.gui = ui.UI()
        g_pool.menubar = ui.Scrolling_Menu("Settings",
                                           pos=(-400, 0),
                                           size=(-icon_bar_width, 0),
                                           header_pos="left")
        g_pool.iconbar = ui.Scrolling_Menu("Icons",
                                           pos=(-icon_bar_width, 0),
                                           size=(0, 0),
                                           header_pos="hidden")
        g_pool.quickbar = ui.Stretching_Menu("Quick Bar", (0, 100),
                                             (120, -100))
        g_pool.gui.append(g_pool.menubar)
        g_pool.gui.append(g_pool.iconbar)
        g_pool.gui.append(g_pool.quickbar)

        general_settings = ui.Growing_Menu("General", header_pos="headline")

        def set_window_size():
            # Get current capture frame size
            f_width, f_height = g_pool.capture.frame_size

            # Get current display scale factor
            content_scale = gl_utils.get_content_scale(main_window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(main_window)
            display_scale_factor = content_scale / framebuffer_scale

            # Scale the capture frame size by display scale factor
            f_width *= display_scale_factor
            f_height *= display_scale_factor

            # Increas the width to account for the added scaled icon bar width
            f_width += icon_bar_width * display_scale_factor

            # Set the newly calculated size (scaled capture frame size + scaled icon bar width)
            glfw.set_window_size(main_window, int(f_width), int(f_height))

        general_settings.append(ui.Button("Reset window size",
                                          set_window_size))
        general_settings.append(
            ui.Selector(
                "Audio mode",
                None,
                getter=audio.get_audio_mode,
                setter=audio.set_audio_mode,
                selection=audio.get_audio_mode_list(),
            ))

        general_settings.append(
            ui.Switch(
                "pupil_detection_enabled",
                label="Pupil detection",
                getter=detection_enabled_getter,
                setter=detection_enabled_setter,
            ))
        general_settings.append(
            ui.Switch(
                "eye0_process",
                label="Detect eye 0",
                setter=lambda alive: start_stop_eye(0, alive),
                getter=lambda: eye_procs_alive[0].value,
            ))
        general_settings.append(
            ui.Switch(
                "eye1_process",
                label="Detect eye 1",
                setter=lambda alive: start_stop_eye(1, alive),
                getter=lambda: eye_procs_alive[1].value,
            ))

        general_settings.append(
            ui.Info_Text("Capture Version: {}".format(g_pool.version)))
        general_settings.append(
            ui.Button("Restart with default settings", reset_restart))

        g_pool.menubar.append(general_settings)
        icon = ui.Icon(
            "collapsed",
            general_settings,
            label=chr(0xE8B8),
            on_val=False,
            off_val=True,
            setter=toggle_general_settings,
            label_font="pupil_icons",
        )
        icon.tooltip = "General Settings"
        g_pool.iconbar.append(icon)

        user_plugin_separator = ui.Separator()
        user_plugin_separator.order = 0.35
        g_pool.iconbar.append(user_plugin_separator)

        loaded_plugins = session_settings.get("loaded_plugins",
                                              default_plugins)

        # Resolve the active calibration choreography plugin
        loaded_plugins = patch_loaded_plugins_with_choreography_plugin(
            loaded_plugins, app=g_pool.app)
        session_settings["loaded_plugins"] = loaded_plugins

        # plugins that are loaded based on user settings from previous session
        g_pool.plugins = Plugin_List(g_pool, loaded_plugins)

        if not g_pool.capture:
            # Make sure we always have a capture running. Important if there was no
            # capture stored in session settings.
            g_pool.plugins.add(g_pool.plugin_by_name[default_capture_name],
                               default_capture_settings)

        # Register callbacks main_window
        glfw.set_framebuffer_size_callback(main_window, on_resize)
        glfw.set_key_callback(main_window, on_window_key)
        glfw.set_char_callback(main_window, on_window_char)
        glfw.set_mouse_button_callback(main_window, on_window_mouse_button)
        glfw.set_cursor_pos_callback(main_window, on_pos)
        glfw.set_scroll_callback(main_window, on_scroll)
        glfw.set_drop_callback(main_window, on_drop)

        # gl_state settings
        gl_utils.basic_gl_setup()
        g_pool.image_tex = Named_Texture()

        toggle_general_settings(True)

        # now that we have a proper window we can load the last gui configuration
        g_pool.gui.configuration = session_settings.get("ui_config", {})
        # If previously selected plugin was not loaded this time, we will have an
        # expanded menubar without any menu selected. We need to ensure the menubar is
        # collapsed in this case.
        if all(submenu.collapsed for submenu in g_pool.menubar.elements):
            g_pool.menubar.collapsed = True

        # create a timer to control window update frequency
        window_update_timer = timer(1 / 60)

        def window_should_update():
            return next(window_update_timer)

        # trigger setup of window and gl sizes
        g_pool.trigger_main_window_redraw = lambda: on_resize(
            main_window, *glfw.get_framebuffer_size(main_window))
        g_pool.trigger_main_window_redraw()

        if session_settings.get("eye1_process_alive", True):
            launch_eye_process(1, delay=0.6)
        if session_settings.get("eye0_process_alive", True):
            launch_eye_process(0, delay=0.3)

        ipc_pub.notify({"subject": "world_process.started"})
        logger.warning("Process started.")

        if platform.system() == "Darwin":
            # On macOS, calls to glfw.swap_buffers() deliberately take longer in case of
            # occluded windows, based on the swap interval value. This causes an FPS drop
            # and leads to problems when recording. To side-step this behaviour, the swap
            # interval is set to zero.
            #
            # Read more about window occlusion on macOS here:
            # https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/WorkWhenVisible.html
            glfw.swap_interval(0)

        # Event loop
        while not glfw.window_should_close(
                main_window) and not process_was_interrupted:

            # fetch newest notifications
            new_notifications = []
            while notify_sub.new_data:
                t, n = notify_sub.recv()
                new_notifications.append(n)

            # notify each plugin if there are new notifications:
            for n in new_notifications:
                handle_notifications(n)
                for p in g_pool.plugins:
                    p.on_notify(n)

            # a dictionary that allows plugins to post and read events
            events = {}
            # report time between now and the last loop interation
            events["dt"] = get_dt()

            # allow each Plugin to do its work.
            for p in g_pool.plugins:
                p.recent_events(events)

            # check if a plugin need to be destroyed
            g_pool.plugins.clean()

            # "blacklisted" events that were already sent
            del events["pupil"]
            del events["gaze"]
            # delete if exists. More expensive than del, so only use it when key might not exist
            events.pop("annotation", None)

            # send new events to ipc:
            if "frame" in events:
                del events["frame"]  # send explicitly with frame publisher
            if "depth_frame" in events:
                del events["depth_frame"]
            if "audio_packets" in events:
                del events["audio_packets"]
            del events["dt"]  # no need to send this
            for data in events.values():
                assert isinstance(data, (list, tuple))
                for d in data:
                    ipc_pub.send(d)

            glfw.make_context_current(main_window)
            # render visual feedback from loaded plugins
            glfw.poll_events()
            if window_should_update() and gl_utils.is_window_visible(
                    main_window):

                gl_utils.glViewport(0, 0, *camera_render_size)
                for p in g_pool.plugins:
                    p.gl_display()

                gl_utils.glViewport(0, 0, *window_size)
                try:
                    clipboard = glfw.get_clipboard_string(main_window).decode()
                except (AttributeError, glfw.GLFWError):
                    # clipboard is None, might happen on startup
                    clipboard = ""
                g_pool.gui.update_clipboard(clipboard)
                user_input = g_pool.gui.update()
                if user_input.clipboard != clipboard:
                    # only write to clipboard if content changed
                    glfw.set_clipboard_string(main_window,
                                              user_input.clipboard)

                for button, action, mods in user_input.buttons:
                    x, y = glfw.get_cursor_pos(main_window)
                    pos = gl_utils.window_coordinate_to_framebuffer_coordinate(
                        main_window, x, y, cached_scale=None)
                    pos = normalize(pos, camera_render_size)
                    # Position in img pixels
                    pos = denormalize(pos, g_pool.capture.frame_size)

                    for plugin in g_pool.plugins:
                        if plugin.on_click(pos, button, action):
                            break

                for key, scancode, action, mods in user_input.keys:
                    for plugin in g_pool.plugins:
                        if plugin.on_key(key, scancode, action, mods):
                            break

                for char_ in user_input.chars:
                    for plugin in g_pool.plugins:
                        if plugin.on_char(char_):
                            break

                glfw.swap_buffers(main_window)

        session_settings["loaded_plugins"] = g_pool.plugins.get_initializers()
        session_settings["ui_config"] = g_pool.gui.configuration
        session_settings["version"] = str(g_pool.version)
        session_settings["eye0_process_alive"] = eye_procs_alive[0].value
        session_settings["eye1_process_alive"] = eye_procs_alive[1].value
        session_settings[
            "min_calibration_confidence"] = g_pool.min_calibration_confidence
        session_settings[
            "pupil_detection_enabled"] = g_pool.pupil_detection_enabled
        session_settings["audio_mode"] = audio.get_audio_mode()

        if not hide_ui:
            glfw.restore_window(main_window)  # need to do this for windows os
            session_settings["window_position"] = glfw.get_window_pos(
                main_window)
            session_window_size = glfw.get_window_size(main_window)
            if 0 not in session_window_size:
                f_width, f_height = session_window_size
                if platform.system() in ("Windows", "Linux"):
                    f_width, f_height = (
                        f_width / content_scale,
                        f_height / content_scale,
                    )
                session_settings["window_size"] = int(f_width), int(f_height)

        session_settings.close()

        # de-init all running plugins
        for p in g_pool.plugins:
            p.alive = False
        g_pool.plugins.clean()

        g_pool.gui.terminate()
        glfw.destroy_window(main_window)
        glfw.terminate()

    except Exception:
        import traceback

        trace = traceback.format_exc()
        logger.error("Process Capture crashed with trace:\n{}".format(trace))

    finally:
        # shut down eye processes:
        stop_eye_process(0)
        stop_eye_process(1)

        logger.info("Process shutting down.")
        ipc_pub.notify({"subject": "world_process.stopped"})
        sleep(1.0)
Example #48
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)
    glfw.set_cursor_pos_callback(window, cursor_pos_callback)
    glfw.set_mouse_button_callback(window, mouse_button_callback)

    #        positions
    cube = [
        -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5,
        -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5,
        -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5,
        -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5,
        -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, -0.5,
        -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5
    ]

    cube = numpy.array(cube, dtype=numpy.float32)

    indices = [
        0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14,
        14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20
    ]

    indices = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;

    uniform mat4 vp;
    uniform mat4 model;

    void main()
    {
        gl_Position =  vp * model * vec4(position, 1.0f);
    }
    """

    fragment_shader = """
    #version 330

    out vec4 outColor;
    uniform vec3 color;

    void main()
    {
        outColor = vec4(color, 1.0);
    }
    """

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    # vertex buffer object and element buffer object
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 3,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    ######################################################################################

    # picking texture and a frame buffer object
    pick_texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, pick_texture)

    FBO = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, FBO)

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1280, 720, 0, GL_RGB, GL_FLOAT,
                 None)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           pick_texture, 0)

    glBindFramebuffer(GL_FRAMEBUFFER, 0)
    glBindTexture(GL_TEXTURE_2D, 0)

    ######################################################################################

    glUseProgram(shader)

    glEnable(GL_DEPTH_TEST)

    view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0]))
    projection = matrix44.create_perspective_projection_matrix(
        45.0, aspect_ratio, 0.1, 100.0)

    vp = matrix44.multiply(view, projection)

    vp_loc = glGetUniformLocation(shader, "vp")
    model_loc = glGetUniformLocation(shader, "model")
    color_loc = glGetUniformLocation(shader, "color")

    cube_positions = [(-2.0, 0.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]
    cube_colors = [(1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0)]
    pick_colors = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

    glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClearColor(0.2, 0.3, 0.2, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_y = Matrix44.from_y_rotation(glfw.get_time() * 2)

        # draw to the default frame buffer
        for i in range(len(cube_positions)):
            model = matrix44.create_from_translation(cube_positions[i])
            glUniform3fv(color_loc, 1, cube_colors[i])
            if i == 0:
                if red_rot:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model)
                else:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
            elif i == 1:
                if green_rot:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model)
                else:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
            else:
                if blue_rot:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model)
                else:
                    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)

            glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

        # draw to the custom frame buffer object
        glBindFramebuffer(GL_FRAMEBUFFER, FBO)
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        for i in range(len(cube_positions)):
            pick_model = matrix44.create_from_translation(cube_positions[i])
            glUniform3fv(color_loc, 1, pick_colors[i])
            glUniformMatrix4fv(model_loc, 1, GL_FALSE, pick_model)
            glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

        if pick:
            picker()

        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        glfw.swap_buffers(window)

    glfw.terminate()
def main():
    # glfw: initialize and configure
    glfw.init()
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    # for Apple devices uncomment the following line
    # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # glfw: window creation
    window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "Learn OpenGL", None,
                                None)
    if window is None:
        glfw.terminate()
        raise Exception("Failed to create GLFW window")

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    # build and compile our shader program
    # vertex shader
    vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(
        vertexShader,
        vertexShaderSource)  # INFO: Changed method head in PyOpenGL
    gl.glCompileShader(vertexShader)

    # check for shader compile errors
    success = gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS)
    if not success:
        info_log = gl.glGetShaderInfoLog(vertexShader, 512, None)
        raise Exception("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s" %
                        info_log)

    # fragment shader
    fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragmentShader, fragmentShaderSource)  # Changed!
    gl.glCompileShader(fragmentShader)

    # check for shader compile errors
    success = gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS)
    if not success:
        info_log = gl.glGetShaderInfoLog(fragmentShader, 512, None)
        raise Exception("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s" %
                        info_log)

    # link shaders
    shaderProgram = gl.glCreateProgram()
    gl.glAttachShader(shaderProgram, vertexShader)
    gl.glAttachShader(shaderProgram, fragmentShader)
    gl.glLinkProgram(shaderProgram)

    # check for linking errors
    success = gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS)
    if not success:
        info_log = gl.glGetProgramInfoLog(shaderProgram, 512, None)
        raise Exception("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s" %
                        info_log)

    gl.glDeleteShader(vertexShader)
    gl.glDeleteShader(fragmentShader)

    # set up vertex data (and buffer(s)) and configure vertex attributes
    vertices = np.array(
        [
            -0.9,
            -0.5,
            0.0,  # left
            -0.1,
            -0.5,
            0.0,  # right
            -0.5,
            0.5,
            0.0,  # top
            0.1,
            -0.5,
            0.0,  # left
            0.9,
            -0.5,
            0.0,  # right
            0.5,
            0.5,
            0.0  # top
        ],
        dtype="float32"
    )  # INFO: Stored as np.array with float32 for compatibility

    VAO = gl.glGenVertexArrays(1)
    VBO = gl.glGenBuffers(1)
    # bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    gl.glBindVertexArray(VAO)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                    gl.GL_STATIC_DRAW)  # INFO: use np.array with nsize

    gl.glVertexAttribPointer(
        0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0,
        c_void_p(0))  # INFO: replaced (gl.void*)0 with c_void_p
    gl.glEnableVertexAttribArray(0)

    # note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)

    # You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
    # VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
    gl.glBindVertexArray(0)

    # render loop
    while not glfw.window_should_close(window):
        # input
        process_input(window)

        # render
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        # draw our first triangle
        gl.glUseProgram(shaderProgram)
        gl.glBindVertexArray(VAO)
        gl.glDrawArrays(
            gl.GL_TRIANGLES, 0,
            len(vertices))  # INFO: no of elements is same as length of matrix
        # gl.glBindVertexArray(0) # no need to unbind it every time

        # glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        glfw.swap_buffers(window)
        glfw.poll_events()

    # optional: de-allocate all resources once they've outlived their purpose:
    gl.glDeleteVertexArrays(1, VAO)
    gl.glDeleteBuffers(1, VBO)
    gl.glDeleteProgram(shaderProgram)

    # glfw: terminate, clearing all previously allocated GLFW resources.
    glfw.terminate()
    return 0
Example #50
0
def main():
    if not glfw.init():
        return
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    window = glfw.create_window(800, 600, "MY OPENGL", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    #adding colors
    #    x,    y,  z,   r,   g,   b,  tx,  ty
    quad = [
        -.5,
        -.5,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.5,
        -.5,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        1.0,
        -.5,
        0.5,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
    ]
    quad = numpy.array(quad, dtype=numpy.float32)

    indices = [0, 1, 2, 2, 3, 0]

    indices = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
	#version 410 core
	in vec3 position;
	in vec3 color;
	in vec2 inTexCords;

	out vec2 outTexCords;
	out vec3 newColor;

	void main()
	{
		gl_Position = vec4(position, 1.0f);
		newColor = color;
		outTexCords = inTexCords;
	}
	"""

    fragment_shader = """
	#version 410 core
	in vec3 newColor;
	in vec2 outTexCords;

	uniform sampler2D sampleTex;
	out vec4 outColor;

	void main()
	{
		outColor = texture(sampleTex, outTexCords) * vec4(newColor, 1.0f);
	}
	"""
    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)  # vertex buffer object for GPU
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    #upload data to array buffer
    glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    #get position from vertex_shader variable
    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 32,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    #get color from vertex_shader program variable
    color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 32,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(color)

    texture_cords = glGetAttribLocation(shader, "inTexCords")
    glVertexAttribPointer(texture_cords, 2, GL_FLOAT, GL_FALSE, 32,
                          ctypes.c_void_p(24))
    glEnableVertexAttribArray(texture_cords)

    #load texture
    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    # texture wrapping parametr
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)

    #texture filtering parametr
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    image = Image.open("./res/1.jpg")
    flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM)
    image_data = numpy.array(list(flipped_image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 564, 555, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, image_data)
    # glTexImage2D()

    glUseProgram(shader)

    glClearColor(.2, .3, .2, 1.0)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        glClear(GL_COLOR_BUFFER_BIT)
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
        glfw.swap_buffers(window)

    glfw.terminate()
Example #51
0
def opengl绘图循环(所有图层, psd尺寸):
    def 生成纹理(img):
        w, h = img.shape[:2]
        d = 2**int(max(math.log2(w), math.log2(h)) + 1)
        纹理 = np.zeros([d, d, 4], dtype=img.dtype)
        纹理[:w, :h] = img
        return 纹理, (w / d, h / d)

    Vtuber尺寸 = 512, 512

    glfw.init()
    超融合()
    glfw.window_hint(glfw.RESIZABLE, False)
    window = glfw.create_window(*Vtuber尺寸, 'Vtuber', None, None)
    glfw.make_context_current(window)
    monitor_size = glfw.get_video_mode(glfw.get_primary_monitor()).size
    glfw.set_window_pos(window, monitor_size.width - Vtuber尺寸[0],
                        monitor_size.height - Vtuber尺寸[1])

    glViewport(0, 0, *Vtuber尺寸)

    glEnable(GL_TEXTURE_2D)
    glEnable(GL_BLEND)
    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE,
                        GL_ONE_MINUS_SRC_ALPHA)

    for 图层数据 in 所有图层:
        纹理编号 = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, 纹理编号)
        纹理, 纹理座标 = 生成纹理(图层数据['npdata'])
        width, height = 纹理.shape[:2]
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA,
                     GL_FLOAT, 纹理)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                        GL_LINEAR_MIPMAP_LINEAR)
        glGenerateMipmap(GL_TEXTURE_2D)
        图层数据['纹理编号'] = 纹理编号
        图层数据['纹理座标'] = 纹理座标

    while not glfw.window_should_close(window):
        glfw.poll_events()
        glClearColor(0, 0, 0, 0)
        glClear(GL_COLOR_BUFFER_BIT)
        横旋转量, 竖旋转量 = 特征缓冲()
        for 图层数据 in 所有图层:
            a, b, c, d = 图层数据['位置']
            z = 图层数据['深度']
            if type(z) in [int, float]:
                z1, z2, z3, z4 = [z, z, z, z]
            else:
                [z1, z2], [z3, z4] = z
            q, w = 图层数据['纹理座标']
            p1 = np.array([a, b, z1, 1, 0, 0, 0, z1])
            p2 = np.array([a, d, z2, 1, z2 * w, 0, 0, z2])
            p3 = np.array([c, d, z3, 1, z3 * w, z3 * q, 0, z3])
            p4 = np.array([c, b, z4, 1, 0, z4 * q, 0, z4])

            model = matrix.scale(2 / psd尺寸[0], 2 / psd尺寸[1], 1) @ \
                matrix.translate(-1, -1, 0) @ \
                matrix.rotate_ax(-math.pi / 2, axis=(0, 1))
            glBindTexture(GL_TEXTURE_2D, 图层数据['纹理编号'])
            glColor4f(1, 1, 1, 1)
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
            glBegin(GL_QUADS)
            for p in [p1, p2, p3, p4]:
                a = p[:4]
                b = p[4:8]
                a = a @ model
                a[0:2] *= a[2]
                if not 图层数据['名字'][:2] == '身体':
                    a = a @ matrix.translate(0, 0, -1) \
                          @ matrix.rotate_ax(横旋转量, axis=(0, 2)) \
                          @ matrix.rotate_ax(竖旋转量, axis=(2, 1)) \
                          @ matrix.translate(0, 0, 1)
                a = a @ matrix.perspective(999)
                glTexCoord4f(*b)
                glVertex4f(*a)
            glEnd()
        glfw.swap_buffers(window)
Example #52
0
 def shouldClose(self):
     return glfw.window_should_close(self.windowID)
Example #53
0
def main():
    init()

    window = glfw.create_window(800, 600, "Chapter7", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glClearColor(0.3, 0.3, 0.3, 1)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)
    program_id = load_shaders('res/glsl/chapter7.vs', 'res/glsl/chapter7.fs')

    res_x, res_y = glfw.get_window_size(window)
    #projection = camera.ortho(-4,4,-3,3,0.1,5.0)
    projection = camera.perspective(45.0, res_x / res_y, 0.1, 100.0)
    view = camera.look_at(np.matrix([2, 2, 2], dtype=np.float32),
                          np.matrix([0, 0, 0], dtype=np.float32),
                          np.matrix([0, 1, 0], dtype=np.float32))
    model = np.matrix(np.identity(4), dtype=np.float32)

    projection_id = glGetUniformLocation(program_id, 'projection')
    view_id = glGetUniformLocation(program_id, 'view')
    model_id = glGetUniformLocation(program_id, 'model')

    vertex = np.array([
        -1,
        -1,
        -1,
        1,
        -1,
        -1,
        1,
        1,
        -1,
        -1,
        1,
        -1,
        -1,
        -1,
        1,
        1,
        -1,
        1,
        1,
        1,
        1,
        -1,
        1,
        1,
    ],
                      dtype=np.float32)

    color = np.array([
        0,
        0,
        0,
        1,
        0,
        0,
        1,
        1,
        0,
        1,
        0,
        1,
        0,
        1,
        0,
        0,
        1,
        1,
        0,
        0,
        1,
        1,
        1,
        1,
    ],
                     dtype=np.float32)

    index = np.array(
        [
            #top
            7,
            6,
            2,
            2,
            3,
            7,

            #bottom
            0,
            1,
            5,
            5,
            4,
            0,

            #left
            0,
            4,
            7,
            7,
            3,
            0,

            #right
            5,
            1,
            2,
            2,
            6,
            5,

            #front
            1,
            0,
            3,
            3,
            2,
            1,

            #back
            4,
            5,
            6,
            6,
            7,
            4,
        ],
        dtype=np.uint32)

    vertex_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, vertex.nbytes, vertex, GL_STATIC_DRAW)

    color_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, color_buffer)
    glBufferData(GL_ARRAY_BUFFER, color.nbytes, color, GL_STATIC_DRAW)

    element_buffer = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, index.nbytes, index, GL_STATIC_DRAW)

    while not glfw.window_should_close(window) and glfw.get_key(
            window, glfw.KEY_ESCAPE) != glfw.PRESS:
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glUseProgram(program_id)
        glUniformMatrix4fv(projection_id, 1, GL_FALSE, projection)
        glUniformMatrix4fv(view_id, 1, GL_FALSE, view)
        glUniformMatrix4fv(model_id, 1, GL_FALSE, model)

        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)

        glEnableVertexAttribArray(1)
        glBindBuffer(GL_ARRAY_BUFFER, color_buffer)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer)
        glDrawElements(GL_TRIANGLES, index.nbytes, GL_UNSIGNED_INT, None)

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Example #54
0
def main():
    if not glfw.init():
        return

    window = glfw.create_window(WIDTH, HEIGHT, "Hello World", None, None)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
    if not window:
        glfw.terminate()
        return -1
    glfw.make_context_current(window)

    (width, height) = glfw.get_framebuffer_size(window)
    glViewport(0, 0, width, height)

    glfw.set_key_callback(window, key_callback)

    glClearColor(0.2, 0.3, 0.2, 1.0)

    quad = [
        # coords            # colors        # texture
        -0.5,
        -0.5,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.5,
        -0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,
        0.5,
        0.5,
        0.0,
        0.0,
        0.0,
        1.0,
        1.0,
        1.0,
        -0.5,
        0.5,
        0.0,
        1.0,
        1.0,
        1.0,
        0.0,
        1.0
    ]
    quad = numpy.array(quad, dtype=numpy.float32)
    indexes = [0, 1, 2, 0, 2, 3]
    indexes = numpy.array(indexes, dtype=numpy.uint32)

    ourShader = Shader('vertex_shader.vs', 'fragment_shader.frag')

    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(1)
    EBO = glGenBuffers(1)

    glBindVertexArray(VAO)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad,
                 GL_STATIC_DRAW)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexes.itemsize * len(indexes),
                 indexes, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)
    glBindVertexArray(0)

    texture1 = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture1)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    image = Image.open('../textures/wall.jpg')
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, img_data)
    glGenerateMipmap(GL_TEXTURE_2D)
    glBindTexture(GL_TEXTURE_2D, 0)

    texture2 = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture2)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    image = Image.open('../textures/container.jpg')
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, img_data)
    glGenerateMipmap(GL_TEXTURE_2D)
    glBindTexture(GL_TEXTURE_2D, 0)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        ourShader.Use()

        transformLoc = glGetUniformLocation(ourShader.shader, "transform")
        rot_z = pyrr.Matrix44.from_z_rotation(0.5 * glfw.get_time())
        translate = pyrr.Matrix44.from_translation(numpy.array([0.5, -0.5,
                                                                0.]))
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE,
                           numpy.array(rot_z * translate))
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, texture1)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, len(indexes), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)

        transformLoc = glGetUniformLocation(ourShader.shader, "transform")
        scaleFactor = (1. + math.sin(glfw.get_time())) * 0.5
        scale = pyrr.Matrix44.from_scale(
            numpy.array([scaleFactor, scaleFactor, 1.]))
        translate = pyrr.Matrix44.from_translation(numpy.array([-0.5, 0.5,
                                                                0.]))
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE,
                           numpy.array(scale * translate))
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, texture2)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, len(indexes), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)

        glfw.swap_buffers(window)

    glfw.terminate()
Example #55
0
def eye(
    timebase,
    is_alive_flag,
    ipc_pub_url,
    ipc_sub_url,
    ipc_push_url,
    user_dir,
    version,
    eye_id,
    overwrite_cap_settings=None,
    hide_ui=False,
    debug=False,
    pub_socket_hwm=None,
    parent_application="capture",
    skip_driver_installation=False,
):
    """reads eye video and detects the pupil.

    Creates a window, gl context.
    Grabs images from a capture.
    Streams Pupil coordinates.

    Reacts to notifications:
        ``eye_process.should_stop``: Stops the eye process
        ``recording.started``: Starts recording eye video
        ``recording.stopped``: Stops recording eye video
        ``frame_publishing.started``: Starts frame publishing
        ``frame_publishing.stopped``: Stops frame publishing
        ``start_eye_plugin``: Start plugins in eye process

    Emits notifications:
        ``eye_process.started``: Eye process started
        ``eye_process.stopped``: Eye process stopped

    Emits data:
        ``pupil.<eye id>``: Pupil data for eye with id ``<eye id>``
        ``frame.eye.<eye id>``: Eye frames with id ``<eye id>``
    """

    # We deferr the imports becasue of multiprocessing.
    # Otherwise the world process each process also loads the other imports.
    import zmq
    import zmq_tools

    zmq_ctx = zmq.Context()
    ipc_socket = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url)
    pupil_socket = zmq_tools.Msg_Streamer(zmq_ctx, ipc_pub_url, pub_socket_hwm)
    notify_sub = zmq_tools.Msg_Receiver(zmq_ctx,
                                        ipc_sub_url,
                                        topics=("notify", ))

    # logging setup
    import logging

    logging.getLogger("OpenGL").setLevel(logging.ERROR)
    logger = logging.getLogger()
    logger.handlers = []
    logger.setLevel(logging.NOTSET)
    logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url))
    # create logger for the context of this function
    logger = logging.getLogger(__name__)

    if is_alive_flag.value:
        # indicates eye process that this is a duplicated startup
        logger.warning("Aborting redundant eye process startup")
        return

    with Is_Alive_Manager(is_alive_flag, ipc_socket, eye_id, logger):
        # general imports
        import traceback
        import numpy as np
        import cv2

        from OpenGL.GL import GL_COLOR_BUFFER_BIT

        # display
        import glfw
        from gl_utils import GLFWErrorReporting

        GLFWErrorReporting.set_default()

        from pyglui import ui, graph, cygl
        from pyglui.cygl.utils import Named_Texture
        import gl_utils
        from gl_utils import basic_gl_setup, adjust_gl_view, clear_gl_screen
        from gl_utils import make_coord_system_pixel_based
        from gl_utils import make_coord_system_norm_based
        from gl_utils import is_window_visible, glViewport

        # monitoring
        import psutil

        # Plug-ins
        from plugin import Plugin_List

        # helpers/utils
        from uvc import get_time_monotonic
        from file_methods import Persistent_Dict
        from version_utils import parse_version
        from methods import normalize, denormalize, timer
        from av_writer import JPEG_Writer, MPEG_Writer, NonMonotonicTimestampError
        from ndsi import H264Writer
        from video_capture import source_classes, manager_classes
        from roi import Roi

        from background_helper import IPC_Logging_Task_Proxy
        from pupil_detector_plugins import available_detector_plugins, EVENT_KEY

        IPC_Logging_Task_Proxy.push_url = ipc_push_url

        def interrupt_handler(sig, frame):
            import traceback

            trace = traceback.format_stack(f=frame)
            logger.debug(f"Caught signal {sig} in:\n" + "".join(trace))
            # NOTE: Interrupt is handled in world/service/player which are responsible for
            # shutting down the eye process properly

        signal.signal(signal.SIGINT, interrupt_handler)

        # UI Platform tweaks
        if platform.system() == "Linux":
            scroll_factor = 10.0
            window_position_default = (600, 300 * eye_id + 30)
        elif platform.system() == "Windows":
            scroll_factor = 10.0
            window_position_default = (600, 90 + 300 * eye_id)
        else:
            scroll_factor = 1.0
            window_position_default = (600, 300 * eye_id)

        icon_bar_width = 50
        window_size = None
        content_scale = 1.0

        # g_pool holds variables for this process
        g_pool = SimpleNamespace()

        # make some constants avaiable
        g_pool.debug = debug
        g_pool.user_dir = user_dir
        g_pool.version = version
        g_pool.app = parent_application
        g_pool.eye_id = eye_id
        g_pool.process = f"eye{eye_id}"
        g_pool.timebase = timebase
        g_pool.camera_render_size = None
        g_pool.skip_driver_installation = skip_driver_installation

        g_pool.zmq_ctx = zmq_ctx
        g_pool.ipc_pub = ipc_socket
        g_pool.ipc_pub_url = ipc_pub_url
        g_pool.ipc_sub_url = ipc_sub_url
        g_pool.ipc_push_url = ipc_push_url

        def get_timestamp():
            return get_time_monotonic() - g_pool.timebase.value

        g_pool.get_timestamp = get_timestamp
        g_pool.get_now = get_time_monotonic

        def load_runtime_pupil_detection_plugins():
            from plugin import import_runtime_plugins
            from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin

            plugins_path = os.path.join(g_pool.user_dir, "plugins")

            for plugin in import_runtime_plugins(plugins_path):
                if not isinstance(plugin, type):
                    continue
                if not issubclass(plugin, PupilDetectorPlugin):
                    continue
                if plugin is PupilDetectorPlugin:
                    continue
                yield plugin

        available_detectors = available_detector_plugins()
        runtime_detectors = list(load_runtime_pupil_detection_plugins())
        plugins = (manager_classes + source_classes + available_detectors +
                   runtime_detectors + [Roi])
        g_pool.plugin_by_name = {p.__name__: p for p in plugins}

        preferred_names = [
            f"Pupil Cam3 ID{eye_id}",
            f"Pupil Cam2 ID{eye_id}",
            f"Pupil Cam1 ID{eye_id}",
        ]
        if eye_id == 0:
            preferred_names += ["HD-6000"]

        default_capture_name = "UVC_Source"
        default_capture_settings = {
            "preferred_names": preferred_names,
            "frame_size": (192, 192),
            "frame_rate": 120,
        }

        default_plugins = [
            # TODO: extend with plugins
            (default_capture_name, default_capture_settings),
            ("UVC_Manager", {}),
            *[(p.__name__, {}) for p in available_detectors],
            ("NDSI_Manager", {}),
            ("HMD_Streaming_Manager", {}),
            ("File_Manager", {}),
            ("Roi", {}),
        ]

        def consume_events_and_render_buffer():
            glfw.make_context_current(main_window)
            clear_gl_screen()

            if all(c > 0 for c in g_pool.camera_render_size):
                glViewport(0, 0, *g_pool.camera_render_size)
                for p in g_pool.plugins:
                    p.gl_display()

            glViewport(0, 0, *window_size)
            # render graphs
            fps_graph.draw()
            cpu_graph.draw()

            # render GUI
            try:
                clipboard = glfw.get_clipboard_string(main_window).decode()
            except (AttributeError, glfw.GLFWError):
                # clipboard is None, might happen on startup
                clipboard = ""
            g_pool.gui.update_clipboard(clipboard)
            user_input = g_pool.gui.update()
            if user_input.clipboard != clipboard:
                # only write to clipboard if content changed
                glfw.set_clipboard_string(main_window, user_input.clipboard)

            for button, action, mods in user_input.buttons:
                x, y = glfw.get_cursor_pos(main_window)
                pos = gl_utils.window_coordinate_to_framebuffer_coordinate(
                    main_window, x, y, cached_scale=None)
                pos = normalize(pos, g_pool.camera_render_size)
                if g_pool.flip:
                    pos = 1 - pos[0], 1 - pos[1]
                # Position in img pixels
                pos = denormalize(pos, g_pool.capture.frame_size)

                for plugin in g_pool.plugins:
                    if plugin.on_click(pos, button, action):
                        break

            for key, scancode, action, mods in user_input.keys:
                for plugin in g_pool.plugins:
                    if plugin.on_key(key, scancode, action, mods):
                        break

            for char_ in user_input.chars:
                for plugin in g_pool.plugins:
                    if plugin.on_char(char_):
                        break

            # update screen
            glfw.swap_buffers(main_window)

        # Callback functions
        def on_resize(window, w, h):
            nonlocal window_size
            nonlocal content_scale

            is_minimized = bool(glfw.get_window_attrib(window, glfw.ICONIFIED))

            if is_minimized:
                return

            # Always clear buffers on resize to make sure that there are no overlapping
            # artifacts from previous frames.
            gl_utils.glClear(GL_COLOR_BUFFER_BIT)
            gl_utils.glClearColor(0, 0, 0, 1)

            active_window = glfw.get_current_context()
            glfw.make_context_current(window)
            content_scale = gl_utils.get_content_scale(window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(window)
            g_pool.gui.scale = content_scale
            window_size = w, h
            g_pool.camera_render_size = w - int(
                icon_bar_width * g_pool.gui.scale), h
            g_pool.gui.update_window(w, h)
            g_pool.gui.collect_menus()
            for g in g_pool.graphs:
                g.scale = content_scale
                g.adjust_window_size(w, h)
            adjust_gl_view(w, h)
            glfw.make_context_current(active_window)

            # Minimum window size required, otherwise parts of the UI can cause openGL
            # issues with permanent effects. Depends on the content scale, which can
            # potentially be dynamically modified, so we re-adjust the size limits every
            # time here.
            min_size = int(2 * icon_bar_width * g_pool.gui.scale /
                           framebuffer_scale)
            glfw.set_window_size_limits(
                window,
                min_size,
                min_size,
                glfw.DONT_CARE,
                glfw.DONT_CARE,
            )

            # Needed, to update the window buffer while resizing
            consume_events_and_render_buffer()

        def on_window_key(window, key, scancode, action, mods):
            g_pool.gui.update_key(key, scancode, action, mods)

        def on_window_char(window, char):
            g_pool.gui.update_char(char)

        def on_iconify(window, iconified):
            g_pool.iconified = iconified

        def on_window_mouse_button(window, button, action, mods):
            g_pool.gui.update_button(button, action, mods)

        def on_pos(window, x, y):
            x, y = gl_utils.window_coordinate_to_framebuffer_coordinate(
                window, x, y, cached_scale=None)
            g_pool.gui.update_mouse(x, y)

            pos = x, y
            pos = normalize(pos, g_pool.camera_render_size)
            if g_pool.flip:
                pos = 1 - pos[0], 1 - pos[1]
            # Position in img pixels
            pos = denormalize(pos, g_pool.capture.frame_size)

            for p in g_pool.plugins:
                p.on_pos(pos)

        def on_scroll(window, x, y):
            g_pool.gui.update_scroll(x, y * scroll_factor)

        def on_drop(window, paths):
            for plugin in g_pool.plugins:
                if plugin.on_drop(paths):
                    break

        # load session persistent settings
        session_settings = Persistent_Dict(
            os.path.join(g_pool.user_dir,
                         "user_settings_eye{}".format(eye_id)))
        if parse_version(session_settings.get("version",
                                              "0.0")) != g_pool.version:
            logger.debug(
                "Session setting are from a different version of this app. I will not use those."
            )
            session_settings.clear()

        camera_is_physically_flipped = eye_id == 0
        g_pool.iconified = False
        g_pool.capture = None
        g_pool.flip = session_settings.get("flip",
                                           camera_is_physically_flipped)
        g_pool.display_mode = session_settings.get("display_mode",
                                                   "camera_image")
        g_pool.display_mode_info_text = {
            "camera_image":
            "Raw eye camera image. This uses the least amount of CPU power",
            "roi":
            "Click and drag on the blue circles to adjust the region of interest. The region should be as small as possible, but large enough to capture all pupil movements.",
            "algorithm":
            "Algorithm display mode overlays a visualization of the pupil detection parameters on top of the eye video. Adjust parameters within the Pupil Detection menu below.",
        }

        def set_display_mode_info(val):
            g_pool.display_mode = val
            g_pool.display_mode_info.text = g_pool.display_mode_info_text[val]

        def toggle_general_settings(collapsed):
            # this is the menu toggle logic.
            # Only one menu can be open.
            # If no menu is open the menubar should collapse.
            g_pool.menubar.collapsed = collapsed
            for m in g_pool.menubar.elements:
                m.collapsed = True
            general_settings.collapsed = collapsed

        # Initialize glfw
        glfw.init()
        glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE)
        if hide_ui:
            glfw.window_hint(glfw.VISIBLE, 0)  # hide window
        title = "Pupil Capture - eye {}".format(eye_id)

        # Pupil Cam1 uses 4:3 resolutions. Pupil Cam2 and Cam3 use 1:1 resolutions.
        # As all Pupil Core and VR/AR add-ons are shipped with Pupil Cam2 and Cam3
        # cameras, we adjust the default eye window size to a 1:1 content aspect ratio.
        # The size of 500 was chosen s.t. the menu still fits.
        default_window_size = 500 + icon_bar_width, 500
        width, height = session_settings.get("window_size",
                                             default_window_size)

        main_window = glfw.create_window(width, height, title, None, None)

        window_position_manager = gl_utils.WindowPositionManager()
        window_pos = window_position_manager.new_window_position(
            window=main_window,
            default_position=window_position_default,
            previous_position=session_settings.get("window_position", None),
        )
        glfw.set_window_pos(main_window, window_pos[0], window_pos[1])

        glfw.make_context_current(main_window)
        cygl.utils.init()

        # gl_state settings
        basic_gl_setup()
        g_pool.image_tex = Named_Texture()
        g_pool.image_tex.update_from_ndarray(
            np.ones((1, 1), dtype=np.uint8) + 125)

        # setup GUI
        g_pool.gui = ui.UI()
        g_pool.menubar = ui.Scrolling_Menu("Settings",
                                           pos=(-500, 0),
                                           size=(-icon_bar_width, 0),
                                           header_pos="left")
        g_pool.iconbar = ui.Scrolling_Menu("Icons",
                                           pos=(-icon_bar_width, 0),
                                           size=(0, 0),
                                           header_pos="hidden")
        g_pool.gui.append(g_pool.menubar)
        g_pool.gui.append(g_pool.iconbar)

        general_settings = ui.Growing_Menu("General", header_pos="headline")

        def set_window_size():
            # Get current capture frame size
            f_width, f_height = g_pool.capture.frame_size
            # Eye camera resolutions are too small to be used as default window sizes.
            # We use double their size instead.
            frame_scale_factor = 2
            f_width *= frame_scale_factor
            f_height *= frame_scale_factor

            # Get current display scale factor
            content_scale = gl_utils.get_content_scale(main_window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(main_window)
            display_scale_factor = content_scale / framebuffer_scale

            # Scale the capture frame size by display scale factor
            f_width *= display_scale_factor
            f_height *= display_scale_factor

            # Increas the width to account for the added scaled icon bar width
            f_width += icon_bar_width * display_scale_factor

            # Set the newly calculated size (scaled capture frame size + scaled icon bar width)
            glfw.set_window_size(main_window, int(f_width), int(f_height))

        general_settings.append(ui.Button("Reset window size",
                                          set_window_size))
        general_settings.append(
            ui.Switch("flip", g_pool, label="Flip image display"))
        general_settings.append(
            ui.Selector(
                "display_mode",
                g_pool,
                setter=set_display_mode_info,
                selection=["camera_image", "roi", "algorithm"],
                labels=["Camera Image", "ROI", "Algorithm"],
                label="Mode",
            ))
        g_pool.display_mode_info = ui.Info_Text(
            g_pool.display_mode_info_text[g_pool.display_mode])

        general_settings.append(g_pool.display_mode_info)

        g_pool.menubar.append(general_settings)
        icon = ui.Icon(
            "collapsed",
            general_settings,
            label=chr(0xE8B8),
            on_val=False,
            off_val=True,
            setter=toggle_general_settings,
            label_font="pupil_icons",
        )
        icon.tooltip = "General Settings"
        g_pool.iconbar.append(icon)

        plugins_to_load = session_settings.get("loaded_plugins",
                                               default_plugins)
        if overwrite_cap_settings:
            # Ensure that overwrite_cap_settings takes preference over source plugins
            # with incorrect settings that were loaded from session settings.
            plugins_to_load.append(overwrite_cap_settings)

        # Add runtime plugins to the list of plugins to load with default arguments,
        # if not already restored from session settings
        plugins_to_load_names = set(name for name, _ in plugins_to_load)
        for runtime_detector in runtime_detectors:
            runtime_name = runtime_detector.__name__
            if runtime_name not in plugins_to_load_names:
                plugins_to_load.append((runtime_name, {}))

        g_pool.plugins = Plugin_List(g_pool, plugins_to_load)

        if not g_pool.capture:
            # Make sure we always have a capture running. Important if there was no
            # capture stored in session settings.
            g_pool.plugins.add(g_pool.plugin_by_name[default_capture_name],
                               default_capture_settings)

        toggle_general_settings(True)

        g_pool.writer = None
        g_pool.rec_path = None

        # Register callbacks main_window
        glfw.set_framebuffer_size_callback(main_window, on_resize)
        glfw.set_window_iconify_callback(main_window, on_iconify)
        glfw.set_key_callback(main_window, on_window_key)
        glfw.set_char_callback(main_window, on_window_char)
        glfw.set_mouse_button_callback(main_window, on_window_mouse_button)
        glfw.set_cursor_pos_callback(main_window, on_pos)
        glfw.set_scroll_callback(main_window, on_scroll)
        glfw.set_drop_callback(main_window, on_drop)

        # load last gui configuration
        g_pool.gui.configuration = session_settings.get("ui_config", {})
        # If previously selected plugin was not loaded this time, we will have an
        # expanded menubar without any menu selected. We need to ensure the menubar is
        # collapsed in this case.
        if all(submenu.collapsed for submenu in g_pool.menubar.elements):
            g_pool.menubar.collapsed = True

        # set up performance graphs
        pid = os.getpid()
        ps = psutil.Process(pid)
        ts = g_pool.get_timestamp()

        cpu_graph = graph.Bar_Graph()
        cpu_graph.pos = (20, 50)
        cpu_graph.update_fn = ps.cpu_percent
        cpu_graph.update_rate = 5
        cpu_graph.label = "CPU %0.1f"

        fps_graph = graph.Bar_Graph()
        fps_graph.pos = (140, 50)
        fps_graph.update_rate = 5
        fps_graph.label = "%0.0f FPS"
        g_pool.graphs = [cpu_graph, fps_graph]

        # set the last saved window size
        on_resize(main_window, *glfw.get_framebuffer_size(main_window))

        should_publish_frames = False
        frame_publish_format = "jpeg"
        frame_publish_format_recent_warning = False

        # create a timer to control window update frequency
        window_update_timer = timer(1 / 60)

        def window_should_update():
            return next(window_update_timer)

        logger.debug("Process started.")

        frame = None

        if platform.system() == "Darwin":
            # On macOS, calls to glfw.swap_buffers() deliberately take longer in case of
            # occluded windows, based on the swap interval value. This causes an FPS drop
            # and leads to problems when recording. To side-step this behaviour, the swap
            # interval is set to zero.
            #
            # Read more about window occlusion on macOS here:
            # https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/WorkWhenVisible.html
            glfw.swap_interval(0)

        # Event loop
        window_should_close = False
        while not window_should_close:

            if notify_sub.new_data:
                t, notification = notify_sub.recv()
                subject = notification["subject"]
                if subject.startswith("eye_process.should_stop"):
                    if notification["eye_id"] == eye_id:
                        break
                elif subject == "recording.started":
                    if notification["record_eye"] and g_pool.capture.online:
                        g_pool.rec_path = notification["rec_path"]
                        raw_mode = notification["compression"]
                        start_time_synced = notification["start_time_synced"]
                        logger.debug(f"Saving eye video to: {g_pool.rec_path}")
                        video_path = os.path.join(g_pool.rec_path,
                                                  "eye{}.mp4".format(eye_id))
                        if raw_mode and frame and g_pool.capture.jpeg_support:
                            g_pool.writer = JPEG_Writer(
                                video_path, start_time_synced)
                        elif hasattr(g_pool.capture._recent_frame,
                                     "h264_buffer"):
                            g_pool.writer = H264Writer(
                                video_path,
                                g_pool.capture.frame_size[0],
                                g_pool.capture.frame_size[1],
                                g_pool.capture.frame_rate,
                            )
                        else:
                            g_pool.writer = MPEG_Writer(
                                video_path, start_time_synced)
                elif subject == "recording.stopped":
                    if g_pool.writer:
                        logger.debug("Done recording.")
                        try:
                            g_pool.writer.release()
                        except RuntimeError:
                            logger.info("No eye video recorded")
                        else:
                            # TODO: wrap recording logic into plugin
                            g_pool.capture.intrinsics.save(
                                g_pool.rec_path, custom_name=f"eye{eye_id}")
                        finally:
                            g_pool.writer = None
                elif subject.startswith("meta.should_doc"):
                    ipc_socket.notify({
                        "subject": "meta.doc",
                        "actor": "eye{}".format(eye_id),
                        "doc": eye.__doc__,
                    })
                elif subject.startswith("frame_publishing.started"):
                    should_publish_frames = True
                    frame_publish_format = notification.get("format", "jpeg")
                elif subject.startswith("frame_publishing.stopped"):
                    should_publish_frames = False
                    frame_publish_format = "jpeg"
                elif (subject.startswith("start_eye_plugin")
                      and notification["target"] == g_pool.process):
                    try:
                        g_pool.plugins.add(
                            g_pool.plugin_by_name[notification["name"]],
                            notification.get("args", {}),
                        )
                    except KeyError as err:
                        logger.error(f"Attempt to load unknown plugin: {err}")
                elif (subject.startswith("stop_eye_plugin")
                      and notification["target"] == g_pool.process):
                    try:
                        plugin_to_stop = g_pool.plugin_by_name[
                            notification["name"]]
                    except KeyError as err:
                        logger.error(f"Attempt to load unknown plugin: {err}")
                    else:
                        plugin_to_stop.alive = False
                        g_pool.plugins.clean()

                for plugin in g_pool.plugins:
                    plugin.on_notify(notification)

            event = {}
            for plugin in g_pool.plugins:
                plugin.recent_events(event)

            frame = event.get("frame")
            if frame:
                if should_publish_frames:
                    try:
                        if frame_publish_format == "jpeg":
                            data = frame.jpeg_buffer
                        elif frame_publish_format == "yuv":
                            data = frame.yuv_buffer
                        elif frame_publish_format == "bgr":
                            data = frame.bgr
                        elif frame_publish_format == "gray":
                            data = frame.gray
                        assert data is not None
                    except (AttributeError, AssertionError, NameError):
                        if not frame_publish_format_recent_warning:
                            frame_publish_format_recent_warning = True
                            logger.warning(
                                '{}s are not compatible with format "{}"'.
                                format(type(frame), frame_publish_format))
                    else:
                        frame_publish_format_recent_warning = False
                        pupil_socket.send({
                            "topic":
                            "frame.eye.{}".format(eye_id),
                            "width":
                            frame.width,
                            "height":
                            frame.height,
                            "index":
                            frame.index,
                            "timestamp":
                            frame.timestamp,
                            "format":
                            frame_publish_format,
                            "__raw_data__": [data],
                        })

                t = frame.timestamp
                dt, ts = t - ts, t
                try:
                    fps_graph.add(1.0 / dt)
                except ZeroDivisionError:
                    pass

                if g_pool.writer:
                    try:
                        g_pool.writer.write_video_frame(frame)
                    except NonMonotonicTimestampError as e:
                        logger.error(
                            "Recorder received non-monotonic timestamp!"
                            " Stopping the recording!")
                        logger.debug(str(e))
                        ipc_socket.notify({"subject": "recording.should_stop"})
                        ipc_socket.notify({
                            "subject": "recording.should_stop",
                            "remote_notify": "all"
                        })

                for result in event.get(EVENT_KEY, ()):
                    pupil_socket.send(result)

            # GL drawing
            if window_should_update():
                cpu_graph.update()
                if is_window_visible(main_window):
                    consume_events_and_render_buffer()
                glfw.poll_events()
                window_should_close = glfw.window_should_close(main_window)

        # END while running

        # in case eye recording was still runnnig: Save&close
        if g_pool.writer:
            logger.debug("Done recording eye.")
            g_pool.writer.release()
            g_pool.writer = None

        session_settings["loaded_plugins"] = g_pool.plugins.get_initializers()
        # save session persistent settings
        session_settings["flip"] = g_pool.flip
        session_settings["display_mode"] = g_pool.display_mode
        session_settings["ui_config"] = g_pool.gui.configuration
        session_settings["version"] = str(g_pool.version)

        if not hide_ui:
            glfw.restore_window(main_window)  # need to do this for windows os
            session_settings["window_position"] = glfw.get_window_pos(
                main_window)
            session_window_size = glfw.get_window_size(main_window)
            if 0 not in session_window_size:
                f_width, f_height = session_window_size
                if platform.system() in ("Windows", "Linux"):
                    # Store unscaled window size as the operating system will scale the
                    # windows appropriately during launch on Windows and Linux.
                    f_width, f_height = (
                        f_width / content_scale,
                        f_height / content_scale,
                    )
                session_settings["window_size"] = int(f_width), int(f_height)

        session_settings.close()

        for plugin in g_pool.plugins:
            plugin.alive = False
        g_pool.plugins.clean()

    glfw.destroy_window(main_window)
    g_pool.gui.terminate()
    glfw.terminate()
    logger.debug("Process shutting down.")
Example #56
0
 def __mainLoop(self):
     while not glfw.window_should_close(self.__window):
         glfw.poll_events()
         self.__drawFrame()
Example #57
0
def main():

    # Initialize the library
    if not glfw.init():
        return

    # Create a windowed mode window and its OpenGL context
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 5)
    window = glfw.create_window(640, 480, "Sandbox", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    # Resources
    module = importlib.import_module("Toy")

    frame_size = glfw.get_framebuffer_size(window)
    resources = module.Resources()
    resources.initialize(frame_size)
    print(list_used_names())

    # Exceptions
    disable_render = False

    # Time
    start_time = glfw.get_time()

    # Loop until the user closes the window
    key_r_was_pressed = False

    while not glfw.window_should_close(window):

        # Handle resizing
        last_frame_size = frame_size
        frame_size = glfw.get_framebuffer_size(window)
        if frame_size != last_frame_size:
            resources.dispose()
            resources.initialize(frame_size)
            print(list_used_names())
            start_time = glfw.get_time()

        # Handle shortcuts
        key_r_is_pressed = bool(glfw.get_key(window, glfw.KEY_R))
        key_ctrl_is_pressed = bool(glfw.get_key(window, glfw.KEY_LEFT_CONTROL))
        if key_r_is_pressed is False and key_r_was_pressed is True and key_ctrl_is_pressed is True:
            try:
                resources.dispose()
                importlib.reload(module)
                resources = module.Resources()
                try:
                    resources.initialize(frame_size)
                    print(list_used_names())
                    start_time = glfw.get_time()
                    disable_render = False
                except (error.GLError, FileNotFoundError):
                    traceback.print_exc()
                    disable_render = True
                    try:
                        resources.dispose()
                    except error.GLError:
                        traceback.print_exc()
                        disable_render = True
                        importlib.reload(module)
                        resources = module.Resources(resources)
            except error.GLError:
                traceback.print_exc()
                disable_render = True
                importlib.reload(module)
                resources = module.Resources(resources)

        key_r_was_pressed = key_r_is_pressed

        # Render some shit
        try:
            if disable_render:
                GL.glClearColor(0.7, 0.0, 0.0, 0.0)
                GL.glClear(GL.GL_COLOR_BUFFER_BIT)
            else:
                module.render(resources, frame_size,
                              glfw.get_time() - start_time)

        except error.GLError:
            traceback.print_exc()
            disable_render = True
            module.dispose_render()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    resources.dispose()

    glfw.terminate()
Example #58
0
# Vertex Buffer Object
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

# Element Buffer Object
EBO = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

glUseProgram(shader)
glClearColor(0, 0.1, 0.1, 1)

# the main application loop
while not glfw.window_should_close(window):
    glfw.poll_events()

    glClear(GL_COLOR_BUFFER_BIT)

    glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

    glfw.swap_buffers(window)

# terminate glfw, free up allocated resources
glfw.terminate()
Example #59
0
 def is_closing(self):
     """
     Checks if the window is scheduled for closing
     """
     return glfw.window_should_close(self.window)
Example #60
0
def main():
    if not glfw.init():
        return

    window = glfw.create_window(720, 600, "Pyopengl Drawing Rectangle", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    # Positions          # Colors
    rectangle = [
        -0.5, -0.5, 0.0, 1.00, 0.11, 0.68, 0.5, -0.5, 0.0, 1.00, 0.11, 0.68,
        0.5, 0.5, 0.0, 1.00, 0.11, 0.68, -0.5, 0.5, 0.0, 1.00, 0.11, 0.68
    ]

    # convert to 32bit float

    rectangle = np.array(rectangle, dtype=np.float32)

    # Creating Indices

    indices = [0, 1, 2, 2, 3, 0]

    indices = np.array(indices, dtype=np.uint32)

    VERTEX_SHADER = """
 
        #version 330
 
        in vec3 position;
        in vec3 color;
        out vec3 newColor;
 
        void main() {
 
         gl_Position = vec4(position, 1.0);
         newColor = color;
 
          }
 
 
    """

    FRAGMENT_SHADER = """
        #version 330
 
        in vec3 newColor;
        out vec4 outColor;
 
        void main() {
 
          outColor = vec4(newColor, 1.0f);
 
        }
 
    """

    # Compile The Program and shaders

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER))

    # Create Buffer object in gpu
    VBO = glGenBuffers(1)

    # Create EBO
    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW)

    # Bind the buffer
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 96, rectangle, GL_STATIC_DRAW)

    # get the position from  shader
    position = glGetAttribLocation(shader, 'position')
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    # get the color from  shader
    color = glGetAttribLocation(shader, 'color')
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(color)

    glUseProgram(shader)

    glClearColor(0, 0.1, 0.1, 1)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        # Draw Triangle

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()