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()
Пример #2
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()
Пример #3
0
 def swap_buffers(self):
     """
     Swap buffers, increment frame counter and pull events
     """
     glfw.swap_buffers(self.window)
     self.frames += 1
     glfw.poll_events()
Пример #4
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()
Пример #5
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()
Пример #6
0
Файл: main.py Проект: 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)
Пример #7
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()
Пример #8
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()
Пример #9
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()
Пример #10
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()
Пример #11
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()
Пример #12
0
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()
Пример #13
0
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()
Пример #14
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()
Пример #15
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
Пример #16
0
 def render_scene(self):
     "render scene one time"
     self.init_gl() # should be a no-op after the first frame is rendered
     glfw.make_context_current(self.window)
     self.renderer.render_scene()
     # Done rendering
     # glfw.swap_buffers(self.window) # avoid double buffering to avoid stalling
     glFlush() # single buffering
     glfw.poll_events()
Пример #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()
Пример #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()
Пример #19
0
 def run(self):
     self.setup()
     while not self.quit:
         self.clear_screen()
         self.update()
         self.render()
         glfw.swap_buffers(self.window)
         glfw.poll_events()
         # time.sleep(.03)
     self.teardown()
Пример #20
0
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()
Пример #21
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
Пример #22
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()
Пример #23
0
    def draw(x):                
        set_param(x)
        # Render here
        # Make the window's context current
        shaject_mat = shadow_proj_mat(vec3(0,1,0), vec3(0,-0.45,0), light_pos)
        
        glfw.make_context_current(window)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
                
        # draw the scene          
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_CULL_FACE)
        glViewport(0,0,width,height)
        glUseProgram(program_handle)   
        glUniform3f(light_pos_loc, light_pos.x, light_pos.y, light_pos.z)   
        model_view_inv = (view_mat * cube.model_mat).inverse()  
        glUniformMatrix4fv(MVint_loc, 1, GL_TRUE, model_view_inv.toList())
        glUniformMatrix4fv(M_loc, 1, GL_FALSE, cube.model_mat.toList())
        MVP = proj_mat * view_mat * cube.model_mat
        glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, MVP.toList())
        glDrawElements(GL_TRIANGLES, len(cube.obj.indices),
                        GL_UNSIGNED_SHORT, None);        
        glUniformMatrix4fv(MVint_loc, 1, GL_TRUE, floor_MVinv.toList())
        glUniformMatrix4fv(M_loc, 1, GL_FALSE, floor_model_mat.toList())
        glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, floor_MVP.toList())                        
        glDrawElements(GL_TRIANGLES, len(cube.obj.indices),
                        GL_UNSIGNED_SHORT, None)        
        glDisable(GL_CULL_FACE)
        glUseProgram(shadow_program_handle)
        glUniformMatrix4fv(shadow_MsVP_loc, 1, GL_FALSE, (VP_mat*shaject_mat*cube.model_mat).toList())              
        glDrawElements(GL_TRIANGLES, len(cube.obj.indices),
                        GL_UNSIGNED_SHORT, None)
        
        
        glViewport(width, 0, width, height)
        
        glDisable(GL_CULL_FACE)               
        glUseProgram(basic_program_handle)                       
        glDrawElements(GL_TRIANGLES, len(cube.obj.indices),
                        GL_UNSIGNED_SHORT, None)  
        glUseProgram(shadow_program_handle)
        glUniformMatrix4fv(shadow_MsVP_loc, 1, GL_FALSE, (VP_mat_top*shaject_mat*cube.model_mat).toList())              
        
#         glUniformMatrix4fv(shadow_M_loc, 1, GL_FALSE, model_mat.toList())
#         glUniformMatrix4fv(shadow_VP_loc, 1, GL_FALSE, VP_mat_top.toList())                 
        glDrawElements(GL_TRIANGLES, len(cube.obj.indices),
                        GL_UNSIGNED_SHORT, None)
        # Swap front and back buffers 
        glfw.swap_buffers(window)
        glfw.poll_events()
Пример #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()
Пример #25
0
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()
Пример #26
0
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()
Пример #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()
Пример #28
0
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()
Пример #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()
Пример #31
0
 def poll_events():
     glfw.poll_events()
Пример #32
0
def main():
    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(width, height, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

    gl.glEnable(gl.GL_DEPTH_TEST)
    shader = Shader(CURDIR / 'shaders/6.1.coordinate_systems.vs',
                    CURDIR / 'shaders/6.1.coordinate_systems.fs')

    vertices = [
        # positions      tex_coords
        -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,
        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,
        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,
        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,
        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,
        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,
        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,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0
    ]
    vertices = (c_float * len(vertices))(*vertices)

    vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(vao)

    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.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             5 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT,
                             gl.GL_FALSE, 5 * sizeof(c_float),
                             c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    # -- load texture 1
    texture1 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0,
                    gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    # -- load texture 2
    texture2 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('awesomeface.png')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0,
                    gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    shader.use()
    shader.set_int("texture1", 0)
    shader.set_int("texture2", 1)

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

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)

        shader.use()
        model = Matrix44.from_x_rotation(
            glfw.get_time() * 0.5) * Matrix44.from_y_rotation(glfw.get_time())
        view = Matrix44.from_translation([0, 0, -3])
        projection = Matrix44.perspective_projection(45, width / height, 0.1,
                                                     100.0)

        shader.set_mat4('view', view)
        shader.set_mat4('model', model)
        shader.set_mat4('projection', projection)
        gl.glBindVertexArray(vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Пример #33
0
def visualize_env(env, mode, max_steps=sys.maxsize, speedup=1):
    timestep = 0.05
    # step ahead with all-zero action
    if mode == 'noop':
        for _ in range(max_steps):
            env.render()
            time.sleep(timestep / speedup)
    elif mode == 'random':
        env.reset()
        env.render()
        for i in range(max_steps):
            action = env.action_space.sample()
            _, _, done, _ = env.step(action)
            # if i % 10 == 0:
            env.render()
            # import time as ttime
            time.sleep(timestep / speedup)
            if done:
                env.reset()
    elif mode == 'static':
        env.reset()
        while True:
            env.render()
            time.sleep(timestep / speedup)
    elif mode == 'human':
        if hasattr(env, 'start_interactive'):
            env.start_interactive()
        else:
            env.reset()
            env.render()
            tr = 0.
            from metaworlds.envs.box2d import Box2DEnv
            if isinstance(env, Box2DEnv):
                for _ in range(max_steps):
                    pygame.event.pump()
                    keys = pygame.key.get_pressed()
                    action = env.action_from_keys(keys)
                    ob, r, done, _ = env.step(action)
                    tr += r
                    env.render()
                    time.sleep(timestep / speedup)
                    if done:
                        tr = 0.
                        env.reset()
                return

            from metaworlds.envs.mujoco import MujocoEnv
            from metaworlds.envs.mujoco.maze import MazeEnv
            if isinstance(env, (MujocoEnv, MazeEnv)):
                trs = [tr]
                actions = [np.zeros(2)]
                import mujoco_py  # noqa: F401
                import glfw

                def cb(window, key, scancode, action, mods):
                    actions[0] = env.action_from_key(key)

                glfw.set_key_callback(env.viewer.window, cb)
                while True:
                    try:
                        actions[0] = np.zeros(2)
                        glfw.poll_events()
                        # if np.linalg.norm(actions[0]) > 0:
                        ob, r, done, info = env.step(actions[0])
                        trs[0] += r
                        env.render()
                        # time.sleep(env.timestep / speedup)
                        time.sleep(env.timestep / speedup)
                        if done:
                            trs[0] = 0.
                            env.reset()
                    except Exception as e:
                        print(e)
                return

            assert hasattr(
                env, "start_interactive"
            ), "The environment must implement method start_interactive"

            env.start_interactive()
        # Assume using matplotlib
        # TODO - make this logic more legit

        # env.render()
        # import matplotlib.pyplot as plt
        # def handle_key_pressed(event):
        #     action = env.action_from_key(event.key)
        #     if action is not None:
        #         _, _, done, _ = env.step(action)
        #         if done:
        #             plt.close()
        #             return
        #         env.render()
        #
        # env.matplotlib_figure.canvas.mpl_connect('key_press_event',
        #    handle_key_pressed)
        # plt.ioff()
        # plt.show()

    else:
        raise ValueError('Unsupported mode: %s' % mode)
Пример #34
0
def main():
    if not opengl_init():
        return

    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)

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

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)

    program_id = common.LoadShaders(
        ".\\shaders\\Tutorial2\\SimpleVertexShader.vertexshader",
        ".\\shaders\\Tutorial2\\SimpleFragmentShader.fragmentshader")

    vertex_data = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0]

    vertex_buffer = glGenBuffers(1)

    # GLFloat = c_types.c_float
    array_type = GLfloat * len(vertex_data)

    # array_type = c_types.c_float_array_9 so unpack values of vertex array
    x = array_type(*vertex_data)

    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(vertex_data) * 4, array_type(*vertex_data),
                 GL_STATIC_DRAW)

    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)

        # Bind vertex buffer data to the attribute 0 in our shader.
        # Note:  This can also be done in the VAO itself (see vao_test.py)

        # Enable the vertex attribute at element[0], in this case that's the triangle's vertices
        # this could also be color, normals, etc.  It isn't necessary to disable these
        #
        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*)
        )

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

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

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

        # Poll for and process events
        glfw.poll_events()

    # note braces around vertex_buffer and vertex_array_id.
    # These 2 functions expect arrays of values
    glDeleteBuffers(1, [vertex_buffer])
    glDeleteProgram(program_id)
    glDeleteVertexArrays(1, [vertex_array_id])
    glfw.terminate()
Пример #35
0
def main():
    #inicia glfw
    if not glfw.init():
        return
    
    #crea la ventana, 
    # independientemente del SO que usemos
    window = glfw.create_window(800,800,"space invaders", None, None)

    #Configuramos OpenGL
    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)

    #Validamos que se cree la ventana
    if not window:
        glfw.terminate()
        return
    #Establecemos el contexto
    glfw.make_context_current(window)

    #Activamos la validación de 
    # funciones modernas de OpenGL
    glewExperimental = True

    #Inicializar GLEW
    if glewInit() != GLEW_OK:
        print("No se pudo inicializar GLEW")
        return

    #Obtenemos versiones de OpenGL y Shaders
    version = glGetString(GL_VERSION)
    print(version)

    version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION)
    print(version_shaders)
    glfw.set_key_callback(window, key_callback)
#-----------------#
    inicializarObstaculos()

    while not glfw.window_should_close(window):
        #Establece regiond e dibujo
        glViewport(0,0,800,800)
        #Establece color de borrado
        glClearColor(0.0,0.0,0.0,1)
        #Borra el contenido de la ventana
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        actualizar(window)
        #Dibujar
        dibujar()

        #Preguntar si hubo entradas de perifericos
        #(Teclado, mouse, game pad, etc.)
        glfw.poll_events()
        #Intercambia los buffers
        glfw.swap_buffers(window)

    #Se destruye la ventana para liberar memoria
    glfw.destroy_window(window)
    #Termina los procesos que inició glfw.init
    glfw.terminate()
Пример #36
0
def main():

    # 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)

    vertex_shader = """
    #version 330
    in vec3 position;    
    uniform mat4 transform;
    out vec3 newColor;
    void main()
    {
        gl_Position = transform * vec4(position, 1.0f);
        //newColor = vec3(1.0,0.0,0.0);
        newColor = vec3(position.x,0.0,0.0);
    }
    """

    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))

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)
    #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
    pers = glm.perspective(0.5, 1.0, 0.1, 10.0)

    #print pers
    trans = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -8.5))

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        #rot_x = glm.rotate(glm.mat4(1.0),0.5 * glfw.get_time(),glm.vec3(1.0,0.0,0.0))
        #rot_y = glm.rotate(glm.mat4(1.0),0.5 * glfw.get_time(),glm.vec3(0.0,1.0,0.0))

        transformLoc = glGetUniformLocation(shader, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE,
                           glm.value_ptr(pers * trans))

        qobj = gluNewQuadric()
        gluSphere(qobj, 1, 50, 50)

        glfw.swap_buffers(window)

    glfw.terminate()
Пример #37
0
def main():
    vertex_src = """
    # version 330

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

    out vec3 v_color;

    void main()
    {
        gl_Position = 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(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)

    # 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.0, 1.0, 0.0, 0.0,
                 0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
                -0.5,  0.5, 0.0, 0.0, 0.0, 1.0,
                 0.5,  0.5, 0.0, 1.0, 1.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)

    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)
    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_TRIANGLE_STRIP, 0, 4)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Пример #38
0
    shapeDice = createDice()
    gpuDice = es.GPUShape().initBuffers()
    textureShaderProgram.setupVAO(gpuDice)
    gpuDice.fillBuffers(shapeDice.vertices, shapeDice.indices, GL_STATIC_DRAW)
    gpuDice.texture = es.textureSimpleSetup(getAssetPath("dice_blue.jpg"),
                                            GL_REPEAT, GL_REPEAT, GL_LINEAR,
                                            GL_LINEAR)

    cpuAxis = bs.createAxis(2)
    gpuAxis = es.GPUShape().initBuffers()
    colorShaderProgram.setupVAO(gpuAxis)
    gpuAxis.fillBuffers(cpuAxis.vertices, cpuAxis.indices, GL_STATIC_DRAW)

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

        # Filling or not the shapes depending on the controller state
        if (controller.fillPolygon):
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
        else:
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

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

        projection = tr.ortho(-1, 1, -1, 1, 0.1, 100)

        view = tr.lookAt(np.array([10, 10, 5]), np.array([0, 0, 0]),
                         np.array([0, 0, 1]))
def main():
    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(800, 600, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

    shader = Shader(CURDIR / 'shaders/5.1.transform.vs', CURDIR / 'shaders/5.1.transform.fs')

    vertices = [
     # positions      tex_coords
     0.5,  0.5, 0.0,  1.0, 1.0,  # top right
     0.5, -0.5, 0.0,  1.0, 0.0,  # bottom right
    -0.5, -0.5, 0.0,  0.0, 0.0,  # bottom left
    -0.5,  0.5, 0.0,  0.0, 1.0,  # top left
    ]
    vertices = (c_float * len(vertices))(*vertices)

    indices = [
        0, 1, 3,
        1, 2, 3
    ]
    indices = (c_uint * len(indices))(*indices)

    vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(vao)

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

    ebo = gl.glGenBuffers(1)
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo)
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, gl.GL_STATIC_DRAW)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    # -- load texture 1
    texture1 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    # -- load texture 2
    texture2 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('awesomeface.png')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    shader.use()
    shader.set_int("texture1", 0)
    shader.set_int("texture2", 1)

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

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)

        translation = Matrix44.from_translation([0.5, -0.5, 0.0])
        rotation = Matrix44.from_z_rotation(glfw.get_time())
        transform = translation * rotation

        shader.use()
        shader.set_mat4('transform', transform)
        gl.glBindVertexArray(vao)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0))

        # -- second container
        translation = Matrix44.from_translation([-0.5, 0.5, 0.0])
        scale = Matrix44.from_scale([math.sin(glfw.get_time())]*3)
        transform = translation * scale

        shader.set_mat4('transform', transform)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0))

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    gl.glDeleteBuffers(1, id(ebo))
    glfw.terminate()
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)

    w_width, w_height = 800, 600

    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)

    obj = ObjLoader()
    obj.load_model("res/monkey_smooth.obj")

    texture_offset = len(obj.vertex_index) * 12
    normal_offset = (texture_offset + len(obj.texture_index) * 8)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = ShaderLoader.compile_shader("shaders/video_18_vert.vs",
                                         "shaders/video_18_frag.fs")

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

    #positions
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, obj.model.itemsize * 2,
                          ctypes.c_void_p(texture_offset))
    glEnableVertexAttribArray(1)
    #normals
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3,
                          ctypes.c_void_p(normal_offset))
    glEnableVertexAttribArray(2)

    glBindVertexArray(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/monkey.jpg")
    flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM)
    img_data = numpy.array(list(flipped_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)

    view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0,
                                                               -3.0]))
    projection = pyrr.matrix44.create_perspective_projection_matrix(
        65.0, w_width / w_height, 0.1, 100.0)
    model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0,
                                                                0.0]))

    glUseProgram(shader)
    view_loc = glGetUniformLocation(shader, "view")
    proj_loc = glGetUniformLocation(shader, "projection")
    model_loc = glGetUniformLocation(shader, "model")
    transform_loc = glGetUniformLocation(shader, "transform")
    light_loc = glGetUniformLocation(shader, "light")

    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
    glUseProgram(0)

    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(transform_loc, 1, GL_FALSE, rot_y)
        glUniformMatrix4fv(light_loc, 1, GL_FALSE, rot_y)

        glBindVertexArray(VAO)
        glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index))
        glBindVertexArray(0)

        glUseProgram(0)

        glfw.swap_buffers(window)

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

    glfw.terminate()
Пример #41
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.1.light_casters.vs",
                             CURDIR / "shaders/5.1.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.direction", Vector3([-0.2, -1.0,
                                                             -0.3]))
        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]))

        # -- 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 cube
        # gl.glBindVertexArray(cube_vao)
        # gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        # -- 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)

        # a lamp object is weird when we only have a directional light, don't render the light object
        # -- 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()
Пример #42
0
def monkey_jump(structure):
    if __name__ == '__main__':

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

        width = 700
        height = 700

        window = glfw.create_window(width, height, 'Saltarin', None, None)

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

        glfw.make_context_current(window)

        # Creamos el controlador
        controlador = Controller()

        # Connecting the callback function 'on_key' to handle keyboard events
        glfw.set_key_callback(window, controlador.on_key)

        # Creating shader programs for textures and for colors
        texture = es.SimpleTextureTransformShaderProgram()
        color = es.SimpleTransformShaderProgram()
    

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

   
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_BLEND )

        # Creamos los objetos
        fondo = Fondobaja()
        mono = Mono("parado.png")
        pasto=Pasto()
        
        # Leemos el csv
        def leer(estructura):
                with open(estructura) as csv_file:
                    csv_reader = csv.reader(csv_file, delimiter=',')
                    r=[]
                    for row in csv_reader:
                        r.append(row[0])
                return r
        r=leer(structure)
        #creamos las barras a partir del csv
        barra = BarraCreator(r, mono)
            
        controlador.set_model(mono)
        controlador.set_barra(barra)
        controlador.set_fondo(fondo)

    
        t0=0
        while not glfw.window_should_close(window):

            # Using GLFW to check for input events
            glfw.poll_events()
            
            # Filling or not the shapes depending on the controller state
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
            
            
            # Clearing the screen in both, color and depth
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            # Dibujamos
            ti = glfw.get_time()
            dt = ti - t0
            t0 = ti
            
            #dibujamos el fondo y hacemos que se mueva
            fondo.create_fondo()
            fondo.update(0.2 * dt)
            fondo.draw(texture)
            
            #Dibujamos el pasto al al comienzo y se comienza a mover
            pasto.update(0.2*dt)
            pasto.draw(texture)
            
            #Dibujamos las barras
            barra.create_barra()  
            barra.update(0.4 * dt)
            
            #se revisan las barras creadas para que el mono salte en ellas y se dibuja el mono
            mono.jump(barra) 
            mono.draw(texture)
            
            #se dibujan las barras
            barra.draw(color)
            
            #si el mono perdió, se pone la pantalla como game over 
            if mono.loser:
                mono=Mono("gameover.png")
                mono.loser=True
                monoTransform=  tr.uniformScale(1.7)
                mono.tra = monoTransform
            
            #si el mono ganó, se indica la victoria 
            elif mono.winner :
                mono=Mono("victory2.png")
                monoTransform=  tr.uniformScale(1.7)
                mono.tra = monoTransform
            
        

            # Once the drawing is rendered, buffers are swap so an uncomplete drawing is never seen.
            glfw.swap_buffers(window)

        glfw.terminate()
Пример #43
0
def main():
    rows = 0
    columns = 0
    height = 0
    while rows < 5 or columns < 5 or height < 5:
        print(
            "The board should be at least 5 x 5 x 5 !  Make sure your inputs are numeric"
        )
        try:
            rows = int(input("Enter an odd number of rows: "))
            columns = int(input("Enter an odd number of columns: "))
            height = int(input("Enter an odd number of layers: "))
        except ValueError:
            rows = 0
            columns = 0
            height = 0
    if rows % 2 == 0:
        rows += 1
    if columns % 2 == 0:
        columns += 1
    if height % 2 == 0:
        height += 1
    print("Game initiated with size " + str(rows) + " x " + str(columns) +
          " x " + str(height))
    print("")
    print(
        "Use the mouse whilst holding the left click button to rotate the arena"
    )
    print("Use the WASD keys to control movement of the arena")
    print(
        "When selecting a place for your counter, type the row number first, and click enter, then type the column number next, and click enter. If the rows and"
        " columns chosen are valid, then the counter will be placed in the bottom layer"
    )
    print(
        "If a counter is already placed in that position in the layer, then the counter will be placed one layer higher than it"
    )
    print(
        "Connect 4's can be found in all 3 dimensions, so watch out for diagonal connects between layers!"
    )
    print(
        "Once a connect has been made, the game will end and a white line will display the positions of the connected counters on the screen"
    )
    print("Good luck and remember to have fun!")

    print(
        "Graphics by Kasim Rehman Bhatti, game mechanics by Atharva Vadeyar, server hosting by Tillega Narayanan"
    )
    print(
        "This game was created using Python for both the machnics and graphics of the game. The graphics work by using Modern OpenGL"
    )
    NewGame = Game3D(rows, columns, height)

    WindowName = "OpenGL Testing"
    if not glfw.init():
        return
    ScreenWidth = 1920
    ScreenHeight = 1080
    window = glfw.create_window(ScreenWidth, ScreenHeight, WindowName, None,
                                None)
    Scale = 0.5
    Ratio = ScreenWidth / ScreenHeight
    ScaledRatio = Scale * Ratio
    if not window:
        glfw.terminate()
    glfw.make_context_current(window)
    glfw.swap_interval(1)

    NewRender = Renderer()

    NewRender.AddShader("Shaders\Complete Shader")
    textureNumber = NewRender.attachTextures("Textures")
    vertexSize = NewRender.returnVertexSize()
    NewObjectLibrary = ObjectLibrary(textureNumber, vertexSize)

    oxpos = 0
    oypos = 0

    Change = 0.05
    ChangeTX = 0.00
    ChangeTY = 0.00
    ChangeTZ = 0.00

    CurrentQuaternion = [0, 0, 0, 1]
    First = True

    multiplier = (rows * columns) / 40
    if (rows * columns) < 40:
        multiplier = 1

    radius = 0.27
    depth = 0.05
    accuracy = 60
    length = 0.7
    objectCentre = [0, 0, -4]
    rotationCentre = [0, 0, -4]
    texture = 2
    color = [0, 0, 0.4]
    counterTexture = 3
    counterColor1 = [0.7, 0, 0]
    counterColor2 = [0.7, 0.7, 0]

    bltc = [
        objectCentre[0] + (-(rows / 2)) * length,
        objectCentre[2] + (-(columns / 2)) * length
    ]
    trtc = [
        objectCentre[0] + (rows / 2) * length,
        objectCentre[2] + (columns / 2) * length
    ]
    for k in range(0, int(height)):
        for j in range(-int(rows / 2), int(rows / 2) + 1):
            for i in range(-int(columns / 2), int(columns / 2) + 1):
                NewObjectLibrary.CreateCounterHolder(
                    radius, depth, accuracy, length, bltc, trtc,
                    objectCentre[0] + j * length,
                    objectCentre[1] + (k * multiplier),
                    objectCentre[2] + i * length, rotationCentre[0],
                    rotationCentre[1], rotationCentre[2], color, texture)
                a = [
                    objectCentre[0] - ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] - ((columns * length) / 2)
                ]
                b = [
                    objectCentre[0] + ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] - ((columns * length) / 2)
                ]
                c = [
                    objectCentre[0] + ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] - ((columns * length) / 2)
                ]
                d = [
                    objectCentre[0] - ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] - ((columns * length) / 2)
                ]
                NewObjectLibrary.CreateRectangle(a, b, c, d, objectCentre[0],
                                                 objectCentre[1],
                                                 objectCentre[2], color,
                                                 texture)
                a = [
                    objectCentre[0] - ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] + ((columns * length) / 2)
                ]
                b = [
                    objectCentre[0] + ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] + ((columns * length) / 2)
                ]
                c = [
                    objectCentre[0] + ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] + ((columns * length) / 2)
                ]
                d = [
                    objectCentre[0] - ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] + ((columns * length) / 2)
                ]
                NewObjectLibrary.CreateRectangle(a, b, c, d, objectCentre[0],
                                                 objectCentre[1],
                                                 objectCentre[2], color,
                                                 texture)
                a = [
                    objectCentre[0] + ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] + ((columns * length) / 2)
                ]
                b = [
                    objectCentre[0] + ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] - ((columns * length) / 2)
                ]
                c = [
                    objectCentre[0] + ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] - ((columns * length) / 2)
                ]
                d = [
                    objectCentre[0] + ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] + ((columns * length) / 2)
                ]
                NewObjectLibrary.CreateRectangle(a, b, c, d, objectCentre[0],
                                                 objectCentre[1],
                                                 objectCentre[2], color,
                                                 texture)
                a = [
                    objectCentre[0] - ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] + ((columns * length) / 2)
                ]
                b = [
                    objectCentre[0] - ((rows * length) / 2),
                    objectCentre[1] + (k * multiplier) + depth,
                    objectCentre[2] - ((columns * length) / 2)
                ]
                c = [
                    objectCentre[0] - ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] - ((columns * length) / 2)
                ]
                d = [
                    objectCentre[0] - ((rows * length) / 2), (k * multiplier),
                    objectCentre[2] + ((columns * length) / 2)
                ]
                NewObjectLibrary.CreateRectangle(a, b, c, d, objectCentre[0],
                                                 objectCentre[1],
                                                 objectCentre[2], color,
                                                 texture)

    color = [[0, 0, 0.4], [0, 0, 0.4], [0, 0, 0.4], [0, 0, 0.4], [0, 0, 0.4],
             [0, 0, 0.4]]
    texture = [2, 2, 2, 2, 2, 2]
    NewObjectLibrary.CreateCuboid(rows * length + 2, depth, columns * length,
                                  objectCentre[0], objectCentre[1] - 1,
                                  objectCentre[2], rotationCentre[0],
                                  rotationCentre[1], rotationCentre[2], color,
                                  texture)
    NewObjectLibrary.CreateCuboid(0.1, 2 * depth, columns * length,
                                  objectCentre[0] - ((rows * length) / 2),
                                  objectCentre[1] - 1 + depth, objectCentre[2],
                                  rotationCentre[0], rotationCentre[1],
                                  rotationCentre[2], color, texture)
    NewObjectLibrary.CreateCuboid(0.1, 2 * depth, columns * length,
                                  objectCentre[0] + ((rows * length) / 2),
                                  objectCentre[1] - 1 + depth, objectCentre[2],
                                  rotationCentre[0], rotationCentre[1],
                                  rotationCentre[2], color, texture)

    for i in range(-int(columns / 2), int(columns / 2) + 1):
        NewObjectLibrary.CreateCylinder(
            radius, depth, accuracy,
            objectCentre[0] - ((rows * length) / 2) - 0.5,
            objectCentre[1] - 1 + depth, objectCentre[2] + i * length,
            rotationCentre[0], rotationCentre[1], rotationCentre[2],
            counterColor1, counterTexture)

    for i in range(-int(columns / 2), int(columns / 2) + 1):
        NewObjectLibrary.CreateCylinder(
            radius, depth, accuracy,
            objectCentre[0] + ((rows * length) / 2) + 0.5,
            objectCentre[1] - 1 + depth, objectCentre[2] + i * length,
            rotationCentre[0], rotationCentre[1], rotationCentre[2],
            counterColor2, counterTexture)

    NewObjectLibrary.sortVertices()

    FOVradians = 1
    Near = 3
    Far = -1

    Done = False

    currentNumber = -1
    currentNumberBuffer = [-1, -1]

    lastBackspace = False
    lastEnter = False
    currentIndex = 0
    last = [
        False, False, False, False, False, False, False, False, False, False
    ]
    lastclicked = False

    connectFound = False
    startBuffer = [-1, -1, -1]
    endBuffer = [-1, -1, -1]

    NewGame.show_state()

    override = False

    while not glfw.window_should_close(window) and not Done:
        NewRender.ProjectAndStretch(FOVradians, Near, Far, Scale, ScaledRatio)

        if glfw.get_key(window, glfw.KEY_Q) == glfw.PRESS:
            Done = True
        if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS:
            ChangeTX += Change
        if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS:
            ChangeTY += Change
        if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS:
            ChangeTX -= Change
        if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS:
            ChangeTY -= Change
        if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS:
            ChangeTZ -= Change
        if glfw.get_key(window, glfw.KEY_L) == glfw.PRESS:
            ChangeTZ += Change

        enterList = clicked(window, glfw.KEY_ENTER, lastEnter, override)
        lastEnter = enterList[1]
        enter = enterList[0]

        enterList = clicked(window, glfw.KEY_BACKSPACE, lastBackspace,
                            override)
        lastBackspace = enterList[1]
        backspace = enterList[0]
        if backspace:
            if currentNumber == 0:
                currentNumber = -1
            elif currentNumber != -1:
                currentNumber /= 10
                currentNumber = int(currentNumber)

        for i in range(0, 10):
            enterList = receiveInputCounter(window, 0 + i, glfw.KEY_0 + i,
                                            last[i], currentNumber, override)
            currentNumber = enterList[2]
            last[i] = enterList[1]

        if enter:
            if currentNumber != -1:
                currentNumberBuffer[currentIndex] = currentNumber
                currentIndex += 1
                currentNumber = -1

        if currentIndex == 2:
            currentIndex = 0

        if currentNumberBuffer[0] != -1 and currentNumberBuffer[
                1] != -1 and not connectFound:
            EnteredRow = False
            EnteredColumn = False
            if currentNumberBuffer[0] > rows - 1:
                print("invalid row")
            else:
                EnteredRow = True
            if currentNumberBuffer[1] > columns - 1:
                print("invalid column")
            else:
                EnteredColumn = True

            initialPlayer = NewGame.return_player()
            if EnteredRow and EnteredColumn:
                added = NewGame.add(currentNumberBuffer[0],
                                    currentNumberBuffer[1], initialPlayer)
                newHeight = height - (added + 1)

                (turn, arrays) = NewGame.newTurn(currentNumberBuffer[0],
                                                 currentNumberBuffer[1],
                                                 newHeight)
                if turn == 1:
                    connectFound = True
                    startBuffer = arrays[0]
                    startBuffer[2] = -(startBuffer[2] + 1)
                    endBuffer = arrays[1]
                    endBuffer[2] = -(endBuffer[2] + 1)
                    print(startBuffer)
                    print(endBuffer)

                if added != -1 and added != -2:
                    if initialPlayer == 1:
                        counterColor = counterColor1
                    else:
                        counterColor = counterColor2

                    NewObjectLibrary.CreateCylinder(
                        radius, depth, accuracy, objectCentre[0] +
                        ((currentNumberBuffer[0] - int(rows / 2)) * length),
                        objectCentre[1] + (newHeight * multiplier),
                        objectCentre[2] +
                        ((currentNumberBuffer[1] - int(columns / 2)) * length),
                        rotationCentre[0], rotationCentre[1],
                        rotationCentre[2], counterColor, counterTexture)
                    NewObjectLibrary.sortVertices()

                    NewGame.player_switch()

                    print("")
                    print("New state")
                    NewGame.show_state()

                    currentNumber = -1
                    currentNumberBuffer = [-1, -1]

                else:
                    currentNumberBuffer = [-1, -1]
            else:
                currentNumber = -1
                currentNumberBuffer = [-1, -1]

        if connectFound:
            if startBuffer[0] != -1 and startBuffer[1] != -1 and startBuffer[
                    2] != -1:
                if startBuffer[0] > rows - 1:
                    startBuffer[0] = rows - 1
                if startBuffer[1] > columns - 1:
                    startBuffer[1] = columns - 1
                if startBuffer[2] > height - 1:
                    startBuffer[2] = height - 1

                if endBuffer[0] != -1 and endBuffer[1] != -1 and endBuffer[
                        2] != -1:
                    if endBuffer[0] > rows - 1:
                        endBuffer[0] = rows - 1
                    if endBuffer[1] > columns - 1:
                        endBuffer[1] = columns - 1
                    if endBuffer[2] > height - 1:
                        endBuffer[2] = height - 1

                a = [
                    objectCentre[0] +
                    ((startBuffer[0] - int(rows / 2)) * length),
                    objectCentre[1] + (startBuffer[2] * multiplier) + 0.2,
                    objectCentre[2] +
                    ((startBuffer[1] - int(columns / 2)) * length + 0.05)
                ]
                b = [
                    objectCentre[0] +
                    ((startBuffer[0] - int(rows / 2)) * length),
                    objectCentre[1] + (startBuffer[2] * multiplier) + 0.2,
                    objectCentre[2] +
                    ((startBuffer[1] - int(columns / 2)) * length - 0.05)
                ]
                d = [
                    objectCentre[0] +
                    ((endBuffer[0] - int(rows / 2)) * length),
                    objectCentre[1] + (endBuffer[2] * multiplier) + 0.2,
                    objectCentre[2] +
                    ((endBuffer[1] - int(columns / 2)) * length + 0.05)
                ]
                c = [
                    objectCentre[0] +
                    ((endBuffer[0] - int(rows / 2)) * length),
                    objectCentre[1] + (endBuffer[2] * multiplier) + 0.2,
                    objectCentre[2] +
                    ((endBuffer[1] - int(columns / 2)) * length - 0.05)
                ]
                NewObjectLibrary.CreateRectangle(a, b, c, d, objectCentre[0],
                                                 objectCentre[1],
                                                 objectCentre[2], [1, 1, 1],
                                                 counterTexture)

                NewObjectLibrary.sortVertices()
                connectFound = False

        xypos = glfw.get_cursor_pos(window)
        xpos = xypos[0]
        ypos = xypos[1]
        click = glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_LEFT)

        if click == glfw.PRESS:
            clickbool = True
        else:
            clickbool = False

        if clickbool and lastclicked:
            Deltay = xpos - oxpos
            Deltax = ypos - oypos

            AngleX = 0.00
            AngleY = 0.00

            if Deltay < 0:
                AngleY = Change * 120 * (-Deltay / ScreenHeight)
            elif Deltay > 0:
                AngleY = Change * 120 * (-Deltay / ScreenHeight)
            if Deltax < 0:
                AngleX = Change * 240 * (-Deltax / ScreenWidth)
            elif Deltax > 0:
                AngleX = Change * 240 * (-Deltax / ScreenWidth)

            Quat = [
                m.sin(AngleX / 2) * m.cos(AngleY / 2),
                m.sin(AngleY / 2) * m.cos(AngleX / 2),
                m.sin(AngleX / 2) * m.sin(AngleY / 2),
                m.cos(AngleX / 2) * m.cos(AngleY / 2)
            ]

            if First:
                CurrentQuaternion = Quat
                CurrentQuaternion = normalizeQuaternion(CurrentQuaternion)
                First = False
            else:
                CurrentQuaternion = multiplyQuaternions(
                    Quat, CurrentQuaternion)
                CurrentQuaternion = normalizeQuaternion(CurrentQuaternion)

        NewRender.RotateQuaternion(CurrentQuaternion)
        NewRender.Translate(ChangeTX, ChangeTY, ChangeTZ)
        NewRender.Lighting(0, 2, 2)
        NewRender.Draw3D(NewObjectLibrary.returnVertices())

        oxpos = xpos
        oypos = ypos
        lastclicked = clickbool

        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
Пример #44
0
 def PollEvents():
     glfw.poll_events()
Пример #45
0
    def run(self):
        glfw_native.glfwGetCocoaWindow.argtypes = [
            ctypes.POINTER(glfw._GLFWwindow)
        ]
        glfw_native.glfwGetCocoaWindow.restype = ctypes.c_void_p
        glfw_native.glfwCreateWindow.argtypes = [
            ctypes.c_int,
            ctypes.c_int,
            ctypes.c_char_p,
        ]
        glfw_native.glfwCreateWindow.restype = ctypes.POINTER(glfw._GLFWwindow)
        glfw_native.glfwMakeContextCurrent.argtypes = [
            ctypes.POINTER(glfw._GLFWwindow)
        ]
        glfw_native.glfwWindowShouldClose.argtypes = [
            ctypes.POINTER(glfw._GLFWwindow)
        ]
        glfw_native.glfwWindowShouldClose.restype = ctypes.c_int

        glfw.init()

        glfw.window_hint(glfw.CLIENT_API, glfw.NO_API)
        glfw.window_hint(glfw.COCOA_RETINA_FRAMEBUFFER, glfw.TRUE)

        self.window = glfw.create_window(self.width, self.height, self.title,
                                         None, None)

        self.fb_width, self.fb_height = glfw.get_framebuffer_size(self.window)

        self.hidpi = self.fb_width != self.width or self.fb_height != self.height

        glfw.set_window_size_callback(self.window, self._handle_window_resize)

        handle, display = None, None

        if sys.platform == "darwin":
            glfw_native.glfwGetCocoaWindow.argtypes = [
                ctypes.POINTER(glfw._GLFWwindow)
            ]
            glfw_native.glfwGetCocoaWindow.restype = ctypes.c_void_p
            handle = glfw_native.glfwGetCocoaWindow(self.window)
        elif sys.platform == "windows":
            glfw_native.glfwGetWin32Window.argtypes = [
                ctypes.POINTER(glfw._GLFWwindow)
            ]
            glfw_native.glfwGetWin32Window.restype = ctypes.c_void_p
            handle = glfw_native.glfwGetWin32Window(self.window)
        elif sys.platform == "linux":
            glfw_native.glfwGetX11Window.argtypes = [
                ctypes.POINTER(glfw._GLFWwindow)
            ]
            glfw_native.glfwGetX11Window.restype = ctypes.c_void_p
            handle = glfw_native.glfwGetX11Window(self.window)
            display = glfw_native.glfwGetX11Display()

        data = bgfx.PlatformData()
        data.ndt = display
        data.nwh = as_void_ptr(handle)
        data.context = None
        data.backBuffer = None
        data.backBufferDS = None

        self.init(data)

        last_time = None

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

            now = time.perf_counter()
            if not last_time:
                last_time = now

            frame_time = now - last_time
            last_time = now

            self.update(frame_time)

        self.shutdown()
        glfw.terminate()
Пример #46
0
def main():

    # declare draw method so it can be reused during resizing
    def draw():
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glUseProgram(shaderProgram)

        gl.glBindVertexArray(VAO)
        gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices.shape[0],
                          gl.GL_UNSIGNED_INT, None)
        gl.glBindVertexArray(0)

        glfw.swap_buffers(window)

    # declaring resize callback in main to allow access to variables
    def window_size_callback(window, width, height):
        gl.glViewport(0, 0, width, height)
        # calling draw to allow drawing while resizing
        draw()

    # 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)  # No deprecated functions
    glfw.window_hint(glfw.RESIZABLE, gl.GL_TRUE)

    # checking if run on Mac OS X
    if sys.platform == 'darwin':
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # glfw window creation
    window = glfw.create_window(WIDTH, HEIGHT, 'LearnOpenGL', None,
                                None)  # tutorial: (800, 600...
    if window is None:
        glfw.terminate()
        raise Exception("ERROR: Failed to create GLFW window")

    glfw.make_context_current(window)

    glfw.set_key_callback(window, key_callback)

    width, height = glfw.get_framebuffer_size(window)
    glfw.set_window_size_callback(window, window_size_callback)

    # build and compile shader program

    # vertex shader
    vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertexShader, vertexShaderSource)
    gl.glCompileShader(vertexShader)
    if not gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS):
        infoLog = gl.glGetShaderInfoLog(vertexShader).decode()
        raise Exception("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" +
                        infoLog)

    # fragment shader
    fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragmentShader, fragmentShaderSource)
    gl.glCompileShader(fragmentShader)
    if not gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS):
        infoLog = gl.glGetShaderInfoLog(fragmentShader).decode()
        raise Exception("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" +
                        infoLog)

    # link shaders
    shaderProgram = gl.glCreateProgram()
    gl.glAttachShader(shaderProgram, vertexShader)
    gl.glAttachShader(shaderProgram, fragmentShader)
    gl.glLinkProgram(shaderProgram)
    if not gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS):
        infoLog = gl.glGetProgramInfoLog(shaderProgram).decode()
        raise Exception("ERROR::SHADER::PROGRAM::LINKING_FAILED\n" + infoLog)
    gl.glDeleteShader(vertexShader)
    gl.glDeleteShader(fragmentShader)

    # set up vertex data (and buffer(s)) and configure vertex attributes

    vertices = np.array(
        [
            [0.5, 0.5, 0.0],  # Left  
            [0.5, -0.5, 0.0],  # Right 
            [-0.5, -0.5, 0.0],
            [-0.5, 0.5, 0.0],
            [1.0, -0.5, 0.0]
        ],  # Top   
        dtype=np.float32)

    indices = np.array(
        [
            [3, 2, 1],  # first triangle
            [0, 1, 4]
        ],  # second triangle
        dtype=np.int32)

    VBO, VAO, EBO = gl.GLuint(), gl.GLuint(), gl.GLuint()

    gl.glGenVertexArrays(1, VAO)  # 1 -> 1 buffer to be generated
    gl.glGenBuffers(1, VBO)
    gl.glGenBuffers(1, EBO)

    # 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)  # bind = make active/current for subsequent ops
    gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices, gl.GL_STATIC_DRAW)

    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, EBO)
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices, gl.GL_STATIC_DRAW)

    stride = vertices.itemsize * vertices.shape[1]
    offset = gl.ctypes.c_void_p(vertices.itemsize * 0)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, stride, offset)
    gl.glEnableVertexAttribArray(0)  # location = 0

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
    gl.glBindVertexArray(0)

    # to put in wireframe mode
    # gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)

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

        draw()

    glfw.terminate()

    return 0
Пример #47
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(2 * size_x, 2 * size_y, "lab", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, moveevent)

    glClearColor(0.3, 0.3, 0.3, 1)
    glEnable(GL_DEPTH_TEST)

    glLoadIdentity()
    glMultMatrixd([
        1,
        0,
        0,
        0,  # move back
        0,
        1,
        0,
        0,
        0,
        0,
        1,
        0,
        -0.9,
        -0.9,
        0.2,
        1
    ])
    cos45 = math.sqrt(2) / 2
    glMultMatrixd([
        1,
        0,
        0,
        0,  # ox 45
        0,
        cos45,
        cos45,
        0,
        0,
        -cos45,
        cos45,
        0,
        0,
        0,
        0,
        1
    ])
    glMultMatrixd([
        cos45,
        cos45,
        0,
        0,  # oz 45
        -cos45,
        cos45,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        1
    ])
    glMultMatrixd([
        1,
        0,
        0,
        0,  # move to center
        0,
        1,
        0,
        0,
        0,
        0,
        1,
        0,
        0.9,
        0.9,
        -0.2,
        1
    ])
    glPushMatrix()

    def mainbox():
        glMultMatrixd([
            scale * xscale,
            0,
            0,
            0,  # back center + scale
            0,
            scale * yscale,
            0,
            0,
            0,
            0,
            scale * zscale,
            0,
            0,
            0,
            0.5,
            1
        ])
        glMultMatrixd([
            math.cos(oztr),
            math.sin(oztr),
            0,
            0,  # z rotate
            -math.sin(oztr),
            math.cos(oztr),
            0,
            0,
            0,
            0,
            1,
            0,
            0,
            0,
            0,
            1
        ])
        glMultMatrixd([
            math.cos(oytr),
            0,
            math.sin(oytr),
            0,  # y rotate
            0,
            1,
            0,
            0,
            -math.sin(oytr),
            0,
            math.cos(oytr),
            0,
            0,
            0,
            0,
            1
        ])
        glMultMatrixd([
            1,
            0,
            0,
            0,  # x rotate
            0,
            math.cos(oxtr),
            -math.sin(oxtr),
            0,
            0,
            math.sin(oxtr),
            math.cos(oxtr),
            0,
            0,
            0,
            0,
            1
        ])
        glMultMatrixd([
            1,
            0,
            0,
            0,  # move to center
            0,
            1,
            0,
            0,
            0,
            0,
            1,
            0,
            0,
            0,
            -0.5,
            1
        ])
        glBegin(GL_QUADS if colormode else GL_LINES)
        glColor3f(1, 0, 0)
        glVertex3f(-0.5, -0.5, -0.5)
        glVertex3f(0.5, -0.5, -0.5)
        glVertex3f(0.5, 0.5, -0.5)
        glVertex3f(-0.5, 0.5, -0.5)
        glColor3f(0, 1, 0)
        glVertex3f(-0.5, -0.5, 0.5)
        glVertex3f(0.5, -0.5, 0.5)
        glVertex3f(0.5, 0.5, 0.5)
        glVertex3f(-0.5, 0.5, 0.5)
        glColor3f(0, 0, 1)
        glVertex3f(-0.5, -0.5, -0.5)
        glVertex3f(-0.5, 0.5, -0.5)
        glVertex3f(-0.5, 0.5, 0.5)
        glVertex3f(-0.5, -0.5, 0.5)
        glColor3f(0, 0.5, 0.5)
        glVertex3f(0.5, -0.5, -0.5)
        glVertex3f(0.5, 0.5, -0.5)
        glVertex3f(0.5, 0.5, 0.5)
        glVertex3f(0.5, -0.5, 0.5)
        glColor3f(0.5, 0.2, 0.7)
        glVertex3f(0.5, -0.5, -0.5)
        glVertex3f(0.5, -0.5, 0.5)
        glVertex3f(-0.5, -0.5, 0.5)
        glVertex3f(-0.5, -0.5, -0.5)
        glColor3f(0.5, 0.5, 0)
        glVertex3f(0.5, 0.5, -0.5)
        glVertex3f(0.5, 0.5, 0.5)
        glVertex3f(-0.5, 0.5, 0.5)
        glVertex3f(-0.5, 0.5, -0.5)
        glEnd()

    def minibox():
        glPopMatrix()
        glBegin(GL_QUADS)
        glColor3f(0.8, 0.2, 0.2)
        glVertex3f(-0.9, -0.9, 0.2)
        glVertex3f(-0.8, -0.9, 0.2)
        glVertex3f(-0.8, -0.8, 0.2)
        glVertex3f(-0.9, -0.8, 0.2)
        glColor3f(0.2, 0.8, 0.2)
        glVertex3f(-0.9, -0.9, 0.2)
        glVertex3f(-0.9, -0.9, 0.3)
        glVertex3f(-0.9, -0.8, 0.3)
        glVertex3f(-0.9, -0.8, 0.2)
        glColor3f(0.2, 0.2, 0.8)
        glVertex3f(-0.9, -0.9, 0.2)
        glVertex3f(-0.8, -0.9, 0.2)
        glVertex3f(-0.8, -0.9, 0.3)
        glVertex3f(-0.9, -0.9, 0.3)
        glEnd()
        glPushMatrix()

    def ortograph():
        # front view
        glViewport(0, size_y, size_x, size_y)
        glLoadIdentity()
        glMultMatrixd([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1])
        mainbox()
        # top view
        glViewport(0, 0, size_x, size_y)
        glLoadIdentity()
        glMultMatrixd([1, 0, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1])
        mainbox()
        # side view
        glViewport(size_x, size_y, size_x, size_y)
        glLoadIdentity()
        glMultMatrixd([0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1])
        mainbox()
        # main view
        glViewport(size_x, 0, size_x, size_y)
        glLoadIdentity()
        glMultMatrixd([
            0.87,
            0,
            1,
            0.5,  # double point perspective
            0,
            1,
            0,
            0,
            0.5,
            0,
            -1.73,
            -0.87,
            0,
            0,
            1,
            2
        ])
        glMultMatrixd(
            [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, xpos, ypos, zpos, 1])
        mainbox()

    while not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        ortograph()
        minibox()
        glfw.swap_buffers(window)
        glfw.poll_events()
        time.sleep(0.01)

    glfw.destroy_window(window)
    glfw.terminate()
Пример #48
0
def display(window):
    global triangles
    global shift_x, shift_y
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glPushMatrix()
    #glRotatef(angle, 0, 0, 1)
    glBegin(GL_TRIANGLES)

    if mode:
        colors = colors_1
    else:
        colors = colors_2

    for i in range(len(triangles) - 2):
        glColor3f(*colors[0])
        glVertex2f(triangles[i][0], triangles[i][1])
        glColor3f(*colors[1])
        glVertex2f(triangles[i + 1][0], triangles[i + 1][1])
        glColor3f(*colors[2])
        glVertex2f(triangles[i + 2][0], triangles[i + 2][1])
    glEnd()

    if mode:
        to_x = triangles[-1][0] + shift_x + random() * size * 7
        to_y = triangles[-1][1] + shift_y + random() * size * 7
    else:
        to_x = triangles[0][0] + shift_x + random() * size * 7
        to_y = triangles[0][1] + shift_y + random() * size * 7

    shift_x += (random() * size - size / 2)
    shift_y += (random() * size - size / 2)

    if 1 - to_x < 0.2:
        shift_x -= random() * size * 1.5
    if to_x - (-1) < 0.2:
        shift_x += random() * size * 1.5

    if 1 - to_y < 0.3:
        shift_y -= random() * size * 1.5
    if to_y - (-1) < 0.3:
        shift_y += random() * size * 1.5

    if to_x > 1:
        if mode:
            to_x = triangles[-1][0] - random() * size
        else:
            to_x = triangles[0][0] - random() * size
    if to_x < -1:
        if mode:
            to_x = triangles[-1][0] + random() * size
        else:
            to_x = triangles[0][0] + random() * size

    if to_y > 1:
        if mode:
            to_y = triangles[-1][1] - random() * size
        else:
            to_y = triangles[0][1] - random() * size
    if to_y < -1:
        if mode:
            to_y = triangles[-1][1] + random() * size
        else:
            to_y = triangles[0][1] + random() * size

    if mode:
        triangles.append((to_x, to_y))
    else:
        triangles.insert(0, (to_x, to_y))

    #triangles.append((random()*size - size/2, random()*size - size/2))
    if len(triangles) > max_len:
        if mode:
            triangles = triangles[1:]
        else:
            triangles = triangles[:-1]

    time.sleep(0.1)

    glPopMatrix()
    glfw.swap_buffers(window)
    glfw.poll_events()
def main():
    global shader

    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec2 a_texture;
    layout(location = 2) in vec3 a_normal;

    uniform mat4 model;
    uniform mat4 projection;
    uniform mat4 view;

    out vec2 v_texture;

    void main()
    {
        gl_Position = projection * view * model * vec4(a_position, 1.0);
        v_texture = a_texture;
    }
    """

    fragment_src = """
    # version 330

    in vec2 v_texture;

    out vec4 out_color;

    uniform sampler2D s_texture;

    void main()
    {
        out_color = texture(s_texture, v_texture);
    }
    """

    # 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)

    # set the callback function for window resize
    glfw.set_window_size_callback(window, window_resize_clb)
    # set the mouse position callback
    glfw.set_cursor_pos_callback(window, mouse_look_clb)
    # set the keyboard input callback
    glfw.set_key_callback(window, key_input_clb)
    # capture the mouse cursor
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)
    # make the context current
    glfw.make_context_current(window)

    # load here the 3d meshes
    chibi_indices, chibi_buffer = ObjLoader.load_model("meshes/chibi.obj")

    plane_buffer = [
        0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0,
        1.0, 1.0, 0.0, 10.0, 0.0, 0.0, 1.0
    ]

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

    plane_indices = [0, 1, 2, 2, 3, 0]
    plane_indices = np.array(plane_indices, dtype=np.uint32)

    # VAO and VBO
    VAO = glGenVertexArrays(2)
    VBO = glGenBuffers(2)
    EBO = glGenBuffers(1)

    # Chibi VAO
    glBindVertexArray(VAO[0])

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
                            compileShader(fragment_src, GL_FRAGMENT_SHADER))
    # Chibi Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0])
    glBufferData(GL_ARRAY_BUFFER, chibi_buffer.nbytes, chibi_buffer,
                 GL_STATIC_DRAW)

    # chibi vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8,
                          ctypes.c_void_p(0))
    # chibi textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8,
                          ctypes.c_void_p(12))
    # chibi normals
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8,
                          ctypes.c_void_p(20))
    glEnableVertexAttribArray(2)

    # Plane VAO
    glBindVertexArray(VAO[1])
    # Plane Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[1])
    glBufferData(GL_ARRAY_BUFFER, plane_buffer.nbytes, plane_buffer,
                 GL_STATIC_DRAW)

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane_indices.nbytes, plane_indices,
                 GL_STATIC_DRAW)

    # plane vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, plane_buffer.itemsize * 5,
                          ctypes.c_void_p(0))
    # plane textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, plane_buffer.itemsize * 5,
                          ctypes.c_void_p(12))

    textures = glGenTextures(2)
    load_texture("meshes/chibi.png", textures[0])

    # create texture for the plane
    glBindTexture(GL_TEXTURE_2D, textures[1])
    # 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)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1280, 720, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, None)
    glBindTexture(GL_TEXTURE_2D, 0)

    depth_buff = glGenRenderbuffers(1)
    glBindRenderbuffer(GL_RENDERBUFFER, depth_buff)
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1280, 720)

    FBO = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, FBO)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           textures[1], 0)
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                              GL_RENDERBUFFER, depth_buff)
    glBindFramebuffer(GL_FRAMEBUFFER, 0)

    glUseProgram(shader)
    glClearColor(0, 0.1, 0.1, 1)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    projection = pyrr.matrix44.create_perspective_projection_matrix(
        45, 1280 / 720, 0.1, 100)
    chibi_pos_main = pyrr.matrix44.create_from_translation(
        pyrr.Vector3([0, 0, -5]))
    plane_pos = pyrr.matrix44.create_from_translation(
        pyrr.Vector3([-20, -3, -10]))

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

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

    glUseProgram(0)

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

        glClearColor(0, 0.1, 0.1, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        view = cam.get_view_matrix()

        glUseProgram(shader)
        glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())
        model = pyrr.matrix44.multiply(rot_y, chibi_pos_main)

        # draw the chibi character
        glBindVertexArray(VAO[0])
        glBindTexture(GL_TEXTURE_2D, textures[0])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
        glDrawArrays(GL_TRIANGLES, 0, len(chibi_indices))

        # draw the chibi to the custom frame buffer
        glBindFramebuffer(GL_FRAMEBUFFER, FBO)
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glDrawArrays(GL_TRIANGLES, 0, len(chibi_indices))
        glBindVertexArray(0)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        # draw the plane
        glBindVertexArray(VAO[1])
        glBindTexture(GL_TEXTURE_2D, textures[1])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, plane_pos)
        glDrawElements(GL_TRIANGLES, len(plane_indices), GL_UNSIGNED_INT, None)

        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Пример #50
0
def main():
    width = 1920
    height = 1080
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(width, height, "OpenCV", None, None)
    if not window:
        glfw.terminate()
        return

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

    fullscreen_quad = Quad()
    quad = Quad(width=8, height=5, center=False)
    fullscreen_shader = Shader()
    fullscreen_shader.set_shader(vert='canvas.vert', frag='canvas.frag')
    quad_shader = Shader()
    quad_shader.set_shader(vert='quad.vert', frag='quad.frag')
    fullscreen_texture = Texture()
    quad_texture = Texture()
    quad_texture.set_texture('D:/Documents/projects/PyTools/PyTools/inner_chessboard.jpg')

    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
    objp = np.zeros((6 * 9, 3), np.float32)
    objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)
    axis = np.float32([[3, 0, 0], [0, 3, 0], [0, 0, -3]]).reshape(-1, 3)

    objp = np.array([
        objp[0],
        objp[8],
        objp[45],
        objp[53]
    ])

    cap = cv2.VideoCapture('D:/Documents/projects/PyTools/PyTools/chessboard2.mp4')

    projection = projection_matrix_from_intrinsic_julian(camera_matrix=PIXEL_3_XL_CAMERA_MATRIX, near=0.1,
                                                         far=1000.0, width=width, height=height)

    view = pyrr.matrix44.create_look_at(eye=np.array([0, 0, 50]), target=np.array([0, 0, 0]), up=np.array([0, 1, 0]))
    model = pyrr.matrix44.create_identity()
    i = 0
    while cap.isOpened():
        # Capture frame-by-frame
        ret, img = cap.read()
        cv2.imwrite('frames/img{}.jpg'.format(i), img)
        i += 1
        if ret:
            # cv2.imwrite("img.jpg", img)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)
            corners = np.array([
                corners[0],
                corners[8],
                corners[45],
                corners[53]
            ])
            if ret:
                corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
                # Find the rotation and translation vectors.
                ret, rvecs, tvecs = cv2.solvePnP(objp, corners2, PIXEL_3_XL_CAMERA_MATRIX, None)
                # convert rvecs and tvecs
                if ret:
                    view = view_matrix_from_rvec_tvec(rvec=rvecs, tvec=tvecs)
                    # project 3D points to image plane
                    imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, PIXEL_3_XL_CAMERA_MATRIX, None)
                    img = draw(img, corners2, imgpts)
            cv2.flip(img, 0, img)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            img = np.true_divide(img, 255.0)

            # fullscreen
            fullscreen_texture.set_texture_from_buffer(img)
            fullscreen_shader.use_shader()
            glActiveTexture(GL_TEXTURE0)
            fullscreen_texture.use_texture()
            glUniform1i(glGetUniformLocation(fullscreen_shader.programId, "draw_texture"), 0)
            fullscreen_quad.draw()

            # quad
            quad_shader.use_shader()
            glActiveTexture(GL_TEXTURE0)
            quad_texture.use_texture()

            glUniform1i(glGetUniformLocation(quad_shader.programId, "draw_texture"), 0)
            glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "P"), 1, GL_FALSE, projection)
            glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "V"), 1, GL_FALSE, view)
            glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "M"), 1, GL_FALSE, model)
            quad.draw()

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

            # Poll for and process events
            glfw.poll_events()
        else:
            break
    cv2.destroyAllWindows()
Пример #51
0
def render_snippet(
    source,
    file_path,
    title="",
    width=200,
    height=200,
    auto_layout=False,
    output_dir='.',
    click=None,
):
    _patch_imgui()
    source = find_fonts(source)

    init_source, frame_source = split_sources(source)

    init_code = compile(init_source, '<str>', 'exec')
    frame_code = compile(frame_source, '<str>', 'exec')
    window_name = "minimal ImGui/GLFW3 example"

    if not glfw.init():
        print("Could not initialize OpenGL context")
        exit(1)

    # OS X supports only forward-compatible core profiles from 3.2
    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, gl.GL_TRUE)
    # note: creating context without window is tricky so made window invisible
    glfw.window_hint(glfw.VISIBLE, False)

    window = glfw.create_window(int(width), int(height), window_name, None,
                                None)

    glfw.make_context_current(window)

    if not window:
        glfw.terminate()
        print("Could not initialize Window")
        exit(1)

    impl = GlfwRenderer(window)

    if init_source:
        exec(init_code, locals(), globals())

    glfw.poll_events()

    # render target for framebuffer
    texture = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0,
                    gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                       gl.GL_NEAREST)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                       gl.GL_NEAREST)

    # create new framebuffer
    offscreen_fb = gl.glGenFramebuffers(1)
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb)
    # attach texture to framebuffer
    gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0,
                              gl.GL_TEXTURE_2D, texture, 0)

    # note: Clicking simulation is hacky as f**k and it
    #       requires at least three frames to be rendered:
    #       * 1st with mouse in position but without button pressed.
    #       * 2nd in roughly same posiotion of mouse to turn on hover
    #         mouse button starts to press but still does not trigger click.
    #       * 3rd in the same position with button pressed still to finally
    #         trigger the "clicked" state.
    # note: If clicking simulation is not required we draw only one frame.
    for m_state in ([None, None, None] if not click else [False, True, True]):

        # note: Mouse click MUST be simulated before new_frame call!
        if click:
            impl.io.mouse_draw_cursor = True
            simulate_click(click[0], click[1], m_state)
        else:
            # just make sure mouse state is clear
            _clear_mouse()

        impl.process_inputs()
        imgui.new_frame()

        with imgui.styled(imgui.STYLE_ALPHA, 1):
            imgui.core.set_next_window_size(0, 0)

            if auto_layout:
                imgui.set_next_window_size(width - 10, height - 10)
                imgui.set_next_window_position(impl.io.display_size.x * 0.5,
                                               impl.io.display_size.y * 0.5,
                                               pivot_x=0.5,
                                               pivot_y=0.5)

            exec(frame_code, locals(), globals())

        gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb)

        gl.glClearColor(1, 1, 1, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())

    # retrieve pixels from framebuffer and write to file
    pixels = gl.glReadPixels(0, 0, width, height, gl.GL_RGBA,
                             gl.GL_UNSIGNED_BYTE)

    image = Image.frombytes('RGBA', (width, height), pixels)
    # note: glReadPixels returns lines "bottom to top" but PIL reads bytes
    #       top to bottom
    image = image.transpose(Image.FLIP_TOP_BOTTOM)
    image.save(os.path.join(output_dir, file_path))

    glfw.terminate()
Пример #52
0
def main():

    # initialize glfw
    if not glfw.init():
        return
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    #creating the window
    window = glfw.create_window(800, 600, "My OpenGL window", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    imgui.create_context()
    impl = GlfwRenderer(window)
    #           positions        colors          texture coords
    quad = [
        -1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0,
        0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0,
        1.0, 1.0, 1.0, 0.0, 1.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 430
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec3 color;
    in layout(location = 2) vec2 inTexCoords;
    out vec3 newColor;
    out vec2 outTexCoords;
    void main()
    {
        gl_Position = vec4(position, 1.0f);
        newColor = color;
        outTexCoords = vec2(inTexCoords.x, 1.0f - inTexCoords.y);
    }
    """

    fragment_shader = """
    #version 430
    in vec3 newColor;
    in vec2 outTexCoords;
    out vec4 outColor;
	
    uniform sampler2DArray samplerTex;

	uniform int sliderR;
	uniform int sliderG;
	uniform int sliderB;

    void main()
    {
		// newcolor just shows you how to pass values through the shader stages
		//outColor = vec4(newColor, 1.0f);
        float texDataR = texture(samplerTex, vec3(outTexCoords, float(sliderR))).x;
		float texDataG = texture(samplerTex, vec3(outTexCoords, float(sliderG))).x;
        float texDataB = texture(samplerTex, vec3(outTexCoords, float(sliderB))).x;

		outColor = vec4(texDataR * 100.0f, texDataG * 100.0f, texDataB * 100.0f, 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))

    compute_shader = """
    #version 430

    layout(local_size_x = 32, local_size_y = 32) in;

    layout(binding= 0, r8ui) uniform uimage2DArray imageArray;
    layout(binding= 1, rgba32f) uniform image2D outputImage;

    void main()
    {
        uvec2 pix = gl_GlobalInvocationID.xy;
        ivec3 imSize = imageSize(imageArray);
		
		float sumPixel = 0.0f;

        if (pix.x < imSize.x && pix.y < imSize.y)
        {
            for (int z = 0; z < imSize.z; z++)
            {
                sumPixel += float(imageLoad(imageArray, ivec3(pix, z)).z);
            }


        }
		
		imageStore(outputImage, ivec2(pix), vec4(sumPixel, sumPixel / float(imSize.z), 69.0f, 8008135.0f));
		
    }

    """

    computeShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(compute_shader, GL_COMPUTE_SHADER))

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 128, quad, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 24, indices, 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)

    sliderR_loc = glGetUniformLocation(shader, "sliderR")
    sliderG_loc = glGetUniformLocation(shader, "sliderG")
    sliderB_loc = glGetUniformLocation(shader, "sliderB")

    images, lambdas = get_data("D:\data\hysperspectral\snapscan_data_png")
    #image = Image.open("./maybotDance.JPG")
    #for index, image in enumerate(images):

    numberOfImages = len(images)
    #print(numberOfImages)
    height, width = images[0].shape[0:2]

    # GENERATE TEXTURES
    hyperspectralDataTexture = createTexture(GL_TEXTURE_2D_ARRAY, GL_R8, 1,
                                             width, height, numberOfImages,
                                             GL_LINEAR, GL_LINEAR)
    outputTexture = createTexture(GL_TEXTURE_2D, GL_RGBA32F, 1, width, height,
                                  1, GL_LINEAR, GL_LINEAR)

    #img_data = numpy.array(list(image.getdata()), numpy.uint8)
    #print(width)
    #print(height)
    #print(images[0])
    # Allocate the immutable GPU memory storage -more efficient than mutable memory if you are not going to change image size after creation
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glPixelStorei(GL_UNPACK_ROW_LENGTH, width)
    # fill each image in the array with the same img_data
    for i in range(numberOfImages):
        #cv2.imshow('image', images[i]*1000.0)
        #cv2.waitKey(0)
        #print(images[i].strides)
        img_data = np.array(images[i].data, np.uint8)
        #print(img_data.shape[0:2])
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, width, height, 1,
                        GL_RED, GL_UNSIGNED_BYTE, img_data)
    #cv2.destroyAllWindows()
    #print("reached here")

    glClearColor(0.2, 0.3, 0.2, 1.0)

    sliderRValue = 0
    sliderGValue = 0
    sliderBValue = 0

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()
        glUseProgram(shader)

        w, h = glfw.get_framebuffer_size(window)
        glViewport(0, 0, int(w / 2), h)
        glClear(GL_COLOR_BUFFER_BIT)

        glUniform1i(sliderR_loc, sliderRValue)
        glUniform1i(sliderG_loc, sliderGValue)
        glUniform1i(sliderB_loc, 50)

        #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE );
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        glUniform1i(sliderB_loc, sliderBValue)
        glViewport(int(w / 2), 0, int(w / 2), h)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        imgui.begin("My first imgui success!", True)
        changedR, sliderRValue = imgui.slider_int("sliceR",
                                                  sliderRValue,
                                                  min_value=0,
                                                  max_value=numberOfImages)
        changedG, sliderGValue = imgui.slider_int("sliceG",
                                                  sliderGValue,
                                                  min_value=0,
                                                  max_value=numberOfImages)
        changedB, sliderBValue = imgui.slider_int("sliceB",
                                                  sliderBValue,
                                                  min_value=0,
                                                  max_value=numberOfImages)

        if imgui.button("do some compute"):
            do_some_compute(computeShader, hyperspectralDataTexture,
                            outputTexture, width, height)

        if imgui.button("get memory back"):
            read_texture_memory(outputTexture, width, height)

        imgui.end()

        imgui.render()
        impl.render(imgui.get_draw_data())

        glfw.swap_buffers(window)

    glfw.terminate()
Пример #53
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()
Пример #54
0
def main():
    if len(sys.argv) < 2:
        print('I need a path to the project\'s root')
        return 1

    project_path = Path(sys.argv[1])
    if not os.path.isdir(project_path):
        print('Invalid path')
        return 1

    project_file = project_path / 'project.plik'
    if os.path.isfile(project_file):
        printf(HTML(f'<gray>Found project file at {project_file}</gray>'))

    # Init graphics
    imgui.create_context()
    window = _glfw_init(500, 1000)
    renderer = GlfwRenderer(window)

    __main_locals_marker = None

    def on_glfw_key(window, key, scancode, action, mods):
        renderer.keyboard_callback(window, key, scancode, action, mods)

        if action == glfw.RELEASE:
            if key in (glfw.KEY_PAUSE, glfw.KEY_SCROLL_LOCK):
                # Pretty slow I assume, but reliable
                frame = inspect.currentframe()
                while frame:
                    if '__main_locals_marker' in frame.f_locals:
                        break
                    frame = frame.f_back

                ipshell(local_ns=frame.f_locals)

    # Need to set this after creating the renderer because by default it does its own hooks
    glfw.set_key_callback(window, on_glfw_key)

    #  TODO
    state = State()
    state.project_path = project_path
    state.project_file = project_file

    app.prompt.start(state)

    running = True
    while not glfw.window_should_close(window) and running:

        glfw.poll_events()
        renderer.process_inputs()

        # TODO Render only when any events are detected to lower CPU usage
        imgui.new_frame()

        imgui.show_test_window()

        # state.window_width, state.window_height = glfw.get_window_size(window)
        # TODO Just set the font at the beginning!
        # with imgui.font(font):
        running = app.prompt.process_next_entry(state)

        gl.glClearColor(.1, .1, .1, .1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        renderer.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    renderer.shutdown()
    glfw.terminate()
Пример #55
0
def main():
    # initialize glfw
    if not glfw.init():
        return

    screen_width = 800
    screen_height = 600
    window = glfw.create_window(screen_width, screen_height, "LearnOpenGL",
                                None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    vertices = [
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        1.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,
        1.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        1.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,
        1.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.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,
        1.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.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,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        1.0,
    ]
    vertices = np.array(vertices, dtype=np.float32)

    view = glm.mat4(1.0)
    view = glm.translate(view, glm.vec3(0.0, 0.0, -3.0))

    projection = glm.perspective(glm.radians(45.0),
                                 screen_width / screen_height, 0.1, 100.0)

    vertex_shader = """
    #version 330 core
    layout (location = 0) in vec3 aPos;   // the position variable has attribute position 0
    layout (location = 1) in vec3 aColor; // the color variable has attribute position 1
      
    out vec3 ourColor; // output a color to the fragment shader
    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;
    
    void main()
    {
        gl_Position = projection * view * model * vec4(aPos, 1.0);
        ourColor = aColor; // set ourColor to the input color we got from the vertex data
    }  
    """

    fragment_shader = """
    #version 330 core
    out vec4 FragColor;  
    in vec3 ourColor;
      
    void main()
    {
        FragColor = vec4(ourColor, 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))

    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(
        1)  # vertex buffer object, which stores vertices in the GPU's memory.
    glBindVertexArray(VAO)

    glBindBuffer(GL_ARRAY_BUFFER, VBO)  # now, all calls will configure VBO
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                 GL_STATIC_DRAW)  # copy user-defined data into VBO

    # position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT,
                          GL_FALSE, 6 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
                          6 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(3 * np.dtype(np.float32).itemsize))
    glEnableVertexAttribArray(1)

    glBindBuffer(GL_ARRAY_BUFFER, 0)

    glBindVertexArray(0)

    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    glEnable(GL_DEPTH_TEST)

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

        # rendering commands here

        glClearColor(0.2, 0.3, 0.3, 1.0)  # state-setting function
        glClear(GL_COLOR_BUFFER_BIT
                | GL_DEPTH_BUFFER_BIT)  # state-using function

        # render triangle
        glUseProgram(shader)

        model = glm.mat4(1.0)
        model = glm.rotate(model, glm.radians(float(glfw.get_time()) * 50.0),
                           glm.vec3(0.5, 1.0, 0.0))
        modelLoc = glGetUniformLocation(shader, "model")
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm.value_ptr(model))

        viewLoc = glGetUniformLocation(shader, "view")
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm.value_ptr(view))

        projectionLoc = glGetUniformLocation(shader, "projection")
        glUniformMatrix4fv(projectionLoc, 1, GL_FALSE,
                           glm.value_ptr(projection))

        glBindVertexArray(VAO)
        glDrawArrays(GL_TRIANGLES, 0, 36)

        # check and call events and swap the buffers
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
Пример #56
0
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\\Tutorial7\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial7\\TextureFragmentShader.fragmentshader")

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

    # Load the texture
    texture = load_image(".\\content\\uvmap.bmp")

    # 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\\cube.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)

    # Load OBJ in to a VBO
    vertex_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(vertex_data) * 4 * 3, 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 * 2, uv_data, GL_STATIC_DRAW)

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

    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)

        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)

        # 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*)
        )

        # 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)

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

        # Poll for and process events
        glfw.poll_events()

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

    glfw.terminate()
Пример #57
0
def main2():
    img = cv2.imread('img.jpg', cv2.IMREAD_COLOR)
    # cv2.imwrite("img.jpg", img)
    img = cv2.resize(img, (2305, 1297))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    (height, width, channels) = img.shape

    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(width, height, "OpenCV", None, None)
    if not window:
        glfw.terminate()
        return

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

    fullscreen_quad = Quad()
    quad = Quad(width=8, height=5, center=False)
    fullscreen_shader = Shader()
    fullscreen_shader.set_shader(vert='canvas.vert', frag='canvas.frag')
    quad_shader = Shader()
    quad_shader.set_shader(vert='quad.vert', frag='quad.frag')
    fullscreen_texture = Texture()
    quad_texture = Texture()
    quad_texture.set_texture('D:/Documents/projects/PyTools/PyTools/inner_chessboard.jpg')

    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
    objp = np.zeros((6 * 9, 3), np.float32)
    objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)
    axis = np.float32([[3, 0, 0], [0, 3, 0], [0, 0, -3]]).reshape(-1, 3)

    objp = np.array([
        objp[0],
        objp[8],
        objp[45],
        objp[53]
    ])

    projection = projection_pixel_3xl(width, height)
    view = pyrr.matrix44.create_look_at(np.array([-20,0,-10]), np.array([0,0,0]), np.array([0,1,0]))
    model = pyrr.matrix44.create_identity()

    ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)
    corners = np.array([
        corners[0],
        corners[8],
        corners[45],
        corners[53]
    ])
    if ret:
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        # Find the rotation and translation vectors.
        ret, rvecs, tvecs = cv2.solvePnP(objp, corners2, PIXEL_3_XL_CAMERA_MATRIX, None)
        # convert rvecs and tvecs
        if ret:
            #view = view_matrix_from_rvec_tvec(rvec=rvecs, tvec=tvecs)
            print(projection)
            print(view)
            # project 3D points to image plane
            imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, PIXEL_3_XL_CAMERA_MATRIX, None)
            img = draw(img, corners2, imgpts)
    cv2.flip(img, 0, img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = np.true_divide(img, 255.0)

    while not glfw.window_should_close(window):
        # fullscreen
        fullscreen_texture.set_texture_from_buffer(img)
        fullscreen_shader.use_shader()
        glActiveTexture(GL_TEXTURE0)
        fullscreen_texture.use_texture()
        glUniform1i(glGetUniformLocation(fullscreen_shader.programId, "draw_texture"), 0)
        fullscreen_quad.draw()

        # quad
        quad_shader.use_shader()
        glActiveTexture(GL_TEXTURE0)
        quad_texture.use_texture()

        glUniform1i(glGetUniformLocation(quad_shader.programId, "draw_texture"), 0)
        glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "P"), 1, GL_FALSE, projection)
        glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "V"), 1, GL_FALSE, view)
        glUniformMatrix4fv(glGetUniformLocation(quad_shader.programId, "M"), 1, GL_FALSE, model)
        quad.draw()

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

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Пример #58
0
 def loop_once(self):
     self.render()
     # Swap front and back buffers
     glfw.swap_buffers(self.window)
     # Poll for and process events
     glfw.poll_events()
Пример #59
0
def main():
    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(800, 600, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

    shader = Shader(CURDIR / 'shaders/4.1.texture.vs',
                    CURDIR / 'shaders/4.1.texture.fs')
    shader_mix = Shader(CURDIR / 'shaders/4.1.texture.vs',
                        CURDIR / 'shaders/4.1.texture_mix.fs')

    vertices = [
        # positions         colors          tex_coords
        0.5,
        0.5,
        0.0,
        1.0,
        0.0,
        0.0,
        1.0,
        1.0,  # top right
        0.5,
        -0.5,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,  # bottom right
        -0.5,
        -0.5,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,  # bottom left
        -0.5,
        0.5,
        0.0,
        1.0,
        1.0,
        0.0,
        0.0,
        1.0,  # top left
    ]
    vertices = (c_float * len(vertices))(*vertices)

    indices = [0, 1, 3, 1, 2, 3]
    indices = (c_uint * len(indices))(*indices)

    vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(vao)

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

    ebo = gl.glGenBuffers(1)
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo)
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,
                    gl.GL_STATIC_DRAW)

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

    gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT,
                             gl.GL_FALSE, 8 * sizeof(c_float),
                             c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT,
                             gl.GL_FALSE, 8 * sizeof(c_float),
                             c_void_p(6 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(2)

    # -- load texture
    texture = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                      gl.GL_LINEAR_MIPMAP_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('container.jpg'))
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0,
                    gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

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

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glBindTexture(gl.GL_TEXTURE_2D, texture)
        shader.use()
        # -- uncomment to see mixture of vertex color and texture color
        # shader_mix.use()
        gl.glBindVertexArray(vao)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0))

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    gl.glDeleteBuffers(1, id(ebo))
    glfw.terminate()
def visualize(shapes_list):
    """
    Displays the 3D shape within the visualization window.
    ----------------------------
    Args:
        shapes_list (obj: 'list' of obj: 'Shape'): The list of shapes
    """
    global xrot, yrot, shapes, vertices, indices

    # create window to render 3d mesh
    window = create_window()
    InitGL(1280, 720)

    shapes = shapes_list
    vertices = np.array(shapes[i].vertices)
    indices = np.array(shapes[i].faces)
    # set background color of window
    glClearColor(0.9, 0.9, 0.9, 1)

    # the main application loop
    while not glfw.window_should_close(window):
        # create vertices and indices from imported data
        glfw.poll_events()

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-1.0, 1.0, -1.0, 1.0, 2.5, 20.0)

        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glEnable(GL_POLYGON_OFFSET_FILL)
        glPolygonOffset(1.0, 2)
        # Translate based on the xas, yas, and z values.
        glTranslatef(xas, yas, z)

        glRotatef(xrot, 1.0, 0.0, 0.0)  # Rotate On The X Axis
        glRotatef(yrot, 0.0, 1.0, 0.0)  # Rotate On The Y Axis
        for index in indices:
            # Allows handling of quads and triangles
            glBegin(GL_TRIANGLES)
            glColor3f(0.5, 0.5, 0.5)
            for number in index[1:]:
                glVertex3f(vertices[number][0], vertices[number][1],
                           vertices[number][2])
            glEnd()

        if DRAW_EDGES:
            for index in indices:
                # Draws the lines for the vertices
                glBegin(GL_LINES)
                glColor3f(0.0, 0.0, 0.0)
                for number in index[1:]:
                    glVertex3f(vertices[number][0], vertices[number][1],
                               vertices[number][2])
                glEnd()
        glDisable(GL_POLYGON_OFFSET_FILL)
        glPopMatrix()

        # Add the speed to the rotation value, is increased by keypressing.
        xrot += xspeed
        yrot += yspeed

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    print(saves)
    glfw.terminate()