def cursor_callback(win, x_pos, y_pos):
    if(x_pos != cartesian.x_pos_prev and y_pos != cartesian.y_pos_prev):

        glfw.set_cursor_pos(win, window_width/2, window_height/2);
        glfw.set_input_mode(win, glfw.CURSOR , glfw.CURSOR_NORMAL)

        horizontal_angle = matrixScene.horizontal_angle
        vertical_angle = matrixScene.vertical_angle
        mouse_speed = 4

        horizontal_angle += mouse_speed * time.GetTimeDelta() * float(window_width / 2.0 - x_pos);
        vertical_angle += mouse_speed * time.GetTimeDelta() * float(window_height / 2.0 - y_pos);
        if (vertical_angle < -1.57):
            vertical_angle = -1.57;
        if (vertical_angle > 1.57):
            vertical_angle = 1.57;


        direction = np.array([np.cos(vertical_angle) * np.sin(horizontal_angle), np.sin(vertical_angle), np.cos(vertical_angle) * np.cos(horizontal_angle)])
        right = np.array([-np.cos(horizontal_angle), 0, np.sin(horizontal_angle)]);
        up = np.cross(right, direction )

        matrixScene.direction = direction
        matrixScene.right = right
        matrixScene.up = up
        matrixScene.horizontal_angle = horizontal_angle
        matrixScene.vertical_angle = vertical_angle

        matrixScene.calculate_view_matrix()

        cartesian.x_pos_prev = x_pos
        cartesian.y_pos_prev = y_pos
Exemple #2
0
 def camera_off(self):
     '''
     Switch off camera mode
     '''
     self.cam_flag = False
     # Show cursor
     glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_NORMAL)
Exemple #3
0
    def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
        self.gl = gl
        if not glfw.init():
            raise Exception("GLFW init failed")

        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_ES_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 2)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.ALPHA_BITS, 0)
        if platform.system() == "Linux":
            try:
                glfw.window_hint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API)
            except:
                pass

        monitor = glfw.get_primary_monitor() if fullscreen else None
        self.window = glfw.create_window(width, height, "BlitzLoop Karaoke",
                                         monitor, None)
        self.x = 0
        self.y = 0
        glfw.make_context_current(self.window)
        BaseDisplay.__init__(self, width, height, fullscreen, aspect)
        self._on_reshape(self.window, width, height)
        if fullscreen:
            self.saved_size = (0, 0, width, height)
            glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_HIDDEN)

        glfw.set_key_callback(self.window, self._on_keyboard)
        glfw.set_window_pos_callback(self.window, self._on_move)
        glfw.set_window_size_callback(self.window, self._on_reshape)

        self._initialize()
Exemple #4
0
 def camera_on(self):
     '''
     Switch on camera mode (only for in game mode)
     '''
     if self.mode == MODE_GAME:
         self.cam_flag = True
         # Hide cursor
         glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_HIDDEN)
         # Move cursor to center
         glfw.set_cursor_pos(self.window, self.gui.window_width / 2, self.gui.window_height / 2)
Exemple #5
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        if not glfw.init():
            raise ValueError("Failed to initialize glfw")

        # Configure the OpenGL context
        glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API)
        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0])
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1])
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.window_hint(glfw.RESIZABLE, self.resizable)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.SAMPLES, self.samples)

        monitor = None
        if self.fullscreen:
            # Use the primary monitors current resolution
            monitor = glfw.get_primary_monitor()
            mode = glfw.get_video_mode(monitor)
            self.width, self.height = mode.size.width, mode.size.height

            # Make sure video mode switching will not happen by
            # matching the desktops current video mode
            glfw.window_hint(glfw.RED_BITS, mode.bits.red)
            glfw.window_hint(glfw.GREEN_BITS, mode.bits.green)
            glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue)
            glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate)

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

        if not self.window:
            glfw.terminate()
            raise ValueError("Failed to create window")

        if not self.cursor:
            glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)

        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)
        glfw.make_context_current(self.window)

        if self.vsync:
            glfw.swap_interval(1)

        glfw.set_key_callback(self.window, self.key_event_callback)
        glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback)
        glfw.set_mouse_button_callback(self.window, self.mouse_button_callback)
        glfw.set_window_size_callback(self.window, self.window_resize_callback)

        self.ctx = moderngl.create_context(require=self.gl_version_code)
        self.print_context_info()
        self.set_default_viewport()
Exemple #6
0
    def setMouseVisibility(self, visibility):
        """Set mouse cursor visibility.

        :param visibility: boolean
        :return:

        """
        if visibility:
            glfw.set_input_mode(self.winHandle, glfw.CURSOR, glfw.CURSOR_NORMAL)
        else:
            glfw.set_input_mode(self.winHandle, glfw.CURSOR, glfw.CURSOR_HIDDEN)
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()
Exemple #8
0
    def init(self):
        super(Window, self).init()

        # hide the cursor and lock it to this window. GLFW will then take care
        # of all the details of cursor re-centering and offset calculation and
        # providing the application with a virtual cursor position
        glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)

        self.cube = game_core.Mesh(smooth_cube.VERTICES, smooth_cube.NORMALS, smooth_cube.INDICES, smooth_cube.DRAW_METHOD)

        self.shaders = shaders.init()

        # set a default matrix for models, otherwise its nothing apparently
        self.light_direction = game_core.Vector(0.1, 1.0, 0.5)
        self.light_direction.normalize()
        model_mat = game_core.Matrix()
        for name, shader in self.shaders.iteritems():
            if 'modelToWorldMatrix' in shader.uniforms:
                with shader:
                    GL.glUniformMatrix4fv(
                        shader.uniforms['modelToWorldMatrix'],
                        1,
                        GL.GL_FALSE,
                        model_mat.tolist()
                    )
            if 'dirToLight' in shader.uniforms:
                with shader:
                    GL.glUniform4fv(shader.uniforms['dirToLight'], 1, list(self.light_direction))
            # if 'diffuseColor' in shader.uniforms:
            #     with shader:
            #         GL.glUniform4f(shader.uniforms['diffuseColor'], 0.5, 0.5, 0.5, 1.0)

        self.camera = Camera(position=[0.0, 32.0, 128.0])
        self.camera.init(*glfw.get_framebuffer_size(self.window))
        self._set_perspective_matrix()

        self.lod_tree = LodTestTree(size=64.0, max_depth=6)
        self.lod_tree.init()

        for depth in range(self.lod_tree.max_depth):
            fine_distance = self.lod_distances[depth]
            if depth == 0:
                coarse_distance = fine_distance * 2.0
            else:
                coarse_distance = self.lod_distances[depth - 1]
            with self.shaders['lod_test_{}'.format(depth)] as shader:
                GL.glUniform1f(shader.uniforms['fineDistance'], fine_distance)
                GL.glUniform1f(shader.uniforms['coarseDistance'], coarse_distance)
Exemple #9
0
 def init(self):
     '''
     initialization that must be done in rendering thread
     '''
     # creating the opengl context
     self.handle = glfw.create_window(self.width, self.height, self.title, None, None);
     if self.handle == None:
         glfw.terminate()
         msg = "GLFW cannot create the window: width={width}, height={height}, title={title}".format(
                 width=self.width, height=self.height, title=self.title)
         raise RuntimeError(msg)
     glfw.set_window_pos(self.handle, *self.DF_POSITION)
     glfw.make_context_current(self.handle)
     glfw.set_input_mode(self.handle, glfw.STICKY_KEYS, 1)
     glfw.swap_interval(self.DF_INTERVAL)
     glClearColor(*self.background_color)
    def init(self):
        super(Window, self).init()

        # hide the cursor and lock it to this window. GLFW will then take care
        # of all the details of cursor re-centering and offset calculation and
        # providing the application with a virtual cursor position
        glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)

        # create a simple cube with smooth normals
        self.cube = game_core.Mesh(smooth_cube.VERTICES, smooth_cube.NORMALS, smooth_cube.INDICES, smooth_cube.DRAW_METHOD)

        # create a camera
        self.camera = game_core.AbstractCamera(position=[0.0, 0.0, 1.5])
        self.camera.init(*glfw.get_framebuffer_size(self.window))

        # compile a simple shader with MVP matrices
        frag_shader = compileShader(frag_shader_source, GL.GL_FRAGMENT_SHADER)
        vert_shader = compileShader(vert_shader_source, GL.GL_VERTEX_SHADER)
        self.shader = game_core.ShaderProgram(vert_shader, frag_shader)
        self.shader.store_uniform_location('modelToWorldMatrix')
        self.shader.store_uniform_location('worldToCameraMatrix')
        self.shader.store_uniform_location('cameraToClipMatrix')

        # populate the shader's MVP matrices and pull the "camera" back 1.5 units
        with self.shader:
            GL.glUniformMatrix4fv(
                self.shader.uniforms['cameraToClipMatrix'],
                1,
                GL.GL_FALSE,
                self.camera.projection_matrix.tolist(),
            )

            inverse_camera_matrix = self.camera.matrix.inverse()
            GL.glUniformMatrix4fv(
                self.shader.uniforms['worldToCameraMatrix'],
                1,
                GL.GL_FALSE,
                inverse_camera_matrix.tolist()
            )

            model_mat = game_core.Matrix()
            GL.glUniformMatrix4fv(
                self.shader.uniforms['modelToWorldMatrix'],
                1,
                GL.GL_FALSE,
                model_mat.tolist()
            )
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()
Exemple #12
0
    def init(self):
        super(Game, self).init()
        glfw.set_input_mode(self.window, glfw.CURSOR, False)

        self.cube = game_core.Mesh(data.cube.VERTICES, data.cube.NORMALS, data.cube.INDICES, data.cube.DRAW_METHOD)
        self.shaders = shaders.init()
        self.register_blocks()

        from .world import World
        self.world = World(self, 128)

        # from .player import Player
        # x=0.5
        # z=-3.5
        # y = self.world.get_height(x,z)
        # self.player = Player(self, [x, y, z])

        from .spectator import Spectator
        x = 0.0
        z = 0.0
        y = 64.0
        self.player = Spectator([x, y, z])
def main():
    if not glfw.init():
        print('Failed to initialize GLFW.')
        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, GL_TRUE)
    glfw.window_hint(glfw.SAMPLES, config['sampling_level'])
    
    if config['fullscreen']:
        global width, height
        mode = glfw.get_video_mode(glfw.get_primary_monitor())
        width, height = mode.size.width, mode.size.height
        window = glfw.create_window(mode.size.width, mode.size.height, config['app_name'], glfw.get_primary_monitor(), None)
    else:
        window = glfw.create_window(width, height, config['app_name'], None, None)
    if not window:
        print('Failed to create GLFW Window.')
        glfw.terminate()
        return

    # подключаем наши функции для эвентов 
    #
    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, ResizeCallback)
    glfw.set_cursor_pos_callback(window, MouseLookCallback)
    glfw.set_key_callback(window, KeyInputCallback) 
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    glEnable(GL_DEPTH_TEST)
    glEnable(GL_CULL_FACE)
    
    # подключаем фрагментный и вершинный шейдеры
    #
    program = Program()
    program.attachShader(Shader('resources/shaders/vert.vs', GL_VERTEX_SHADER))
    program.attachShader(Shader('resources/shaders/frag.fs', GL_FRAGMENT_SHADER))
    program.link()
    
    # подключаем шейдер для создания карты теней
    #  
    depthProgram = Program()
    depthProgram.attachShader(Shader('resources/shaders/depth.vs', GL_VERTEX_SHADER))
    depthProgram.attachShader(Shader('resources/shaders/depth.fs', GL_FRAGMENT_SHADER))
    depthProgram.attachShader(Shader('resources/shaders/depth.gs', GL_GEOMETRY_SHADER))
    depthProgram.link()

    # создаем depthBuffer и frameBuffer
    #
    shadow = Shadow(config['near_plane_depth'], config['far_plane_depth'])
    shadow.create(config['shadow_width'], config['shadow_height'])

    program.use()
    program.setInt("diffuseTexture", 0)
    program.setInt("depthMap", 1)

    # позиция источника света
    #
    lightPos = glm.vec3(0.0, 2.35, 0.0)
    
    # загрузка всех объектов сцены
    #
    room = Model('resources/models/dinning_room.json')
    
    # цикл обработки
    #
    while not glfw.window_should_close(window):
        if config['debug_mode']:
            print(glGetError())

        # обработка нажатий клавиатуры для камеры
        #
        DoMovement()
        
        # движение источника света
        #
        if light_movement:
            lightPos.z = math.sin(glfw.get_time() * 0.5) * 3.0

        glClearColor(0.1, 0.1, 0.1, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        
        # обработка с помощью depthProgram - карта теней
        #
        shadow.castShadow(depthProgram, lightPos)
        room.draw(depthProgram)
        shadow.endCastShadow(program)

        
        glViewport(0, 0, width, height)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # обработка с помощью program - на основе полученной карты теней
        #
        program.use()
        view = cam.get_view_matrix()
        viewPos = glm.vec3(cam.camera_pos[0],cam.camera_pos[1],cam.camera_pos[2])
        perspective = glm.perspective(45, width / height, config['near_plane'], config['far_plane'])
        program.setMat4('projection', perspective)
        program.setMat4('view', view)
        program.setVec3('lightPos', lightPos)
        program.setVec3('viewPos', viewPos)
        program.setInt('shadows', True)
        program.setFloat("far_plane", config["far_plane_depth"])
        glActiveTexture(GL_TEXTURE1)
        glBindTexture(GL_TEXTURE_CUBE_MAP, shadow.depthbuffer.texture)
        room.draw(program)

        glfw.swap_buffers(window)
        glfw.poll_events()
        

    glfw.terminate()
def main():

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

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

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

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

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

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray( vertex_array_id )

    # Create and compile our GLSL program from the shaders
    program_id = common.LoadShaders( ".\\shaders\\Tutorial9\\StandardShading.vertexshader",
        ".\\shaders\\Tutorial9\\StandardShading.fragmentshader" )
    
    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP")
    view_matrix_id = glGetUniformLocation(program_id, "V")
    model_matrix_id = glGetUniformLocation(program_id, "M")

    # Load the texture
    texture = textureutils.load_image(".\\content\\uvmap_suzanne.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\\suzanne.obj")
    vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors)

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

    indexed_vertices, indexed_uvs, indexed_normals, indices = vboindexer.indexVBO(vertex_data,uv_data,normal_data)
    
    indexed_vertices = c_type_fill(indexed_vertices,GLfloat)
    indexed_uvs = c_type_fill(indexed_uvs,GLfloat)
    indexed_normals = c_type_fill(indexed_normals,GLfloat)
    indices = c_type_fill_1D(indices,GLushort)


    # Load OBJ in to a VBO
    vertex_buffer = glGenBuffers(1);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_vertices) * 4 * 3, indexed_vertices, GL_STATIC_DRAW)

    uv_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_uvs) * 4 * 2, indexed_uvs, GL_STATIC_DRAW)

    normal_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_normals) * 4 * 3, indexed_normals, GL_STATIC_DRAW)

    # Generate a buffer for the indices as well
    elementbuffer = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 2, indices , GL_STATIC_DRAW);

    # vsync and glfw do not play nice.  when vsync is enabled mouse movement is jittery.
    common.disable_vsyc()
    
    # Get a handle for our "LightPosition" uniform
    glUseProgram(program_id);
    light_id = glGetUniformLocation(program_id, "LightPosition_worldspace");

    last_time = glfw.get_time()
    frames = 0

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

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

        glUseProgram(program_id)

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

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

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

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

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

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

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


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

        # Draw the triangles !
        glDrawElements(
            GL_TRIANGLES,           # mode
            len(indices),           # count
            GL_UNSIGNED_SHORT,      # type
            null                    # element array buffer offset
        )
        # Not strictly necessary because we only have 
        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)
    
    
        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

        frames += 1

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

    glfw.terminate()
Exemple #15
0
    def __init__(self, width, height, title='', **kwargs):
        """
        Creates a new window.

        After the successful creation of a window the loop has
        to be manually started with *start_event_loop*.
        To draw, use *set_update_handler* with a *fn(window)* callback.

        Parameters
        ----------
        width: int
            Width of window.
        height: int
            Height of window.
        title: str
            Title to show in title bar.
        **kwargs
            vsync: bool
                Turn off or on vsync. default=False
            resizable: bool
                Indicate if the windows should be resizable. default=False
            x_scale: float
                Scaling in 'x' direction. default=1
            y_scale: float
                Scaling in 'y' direction. default=1
            scale: float
                Sets 'x_scale' and 'y_scale' to the same value.
            hdpi: bool
                Use HDPI if available. Default=False
            color: tuple of float
                Set the background color. RGB or RGBA supported
        """
        if not glfw.init():
            raise UserWarning('Unable to initialize glfw')
        self.fps = 0
        self._handler = None
        self._title = title
        self.width = width
        self.height = height
        self.context = {}

        resizable = glfw.FALSE
        if 'resizable' in kwargs:
            resizable = glfw.TRUE if kwargs['resizable'] else glfw.FALSE
        glfw.window_hint(glfw.RESIZABLE, resizable)

        # switch to newer OpenGL version...
        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)  # mac only
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        hdpi = glfw.FALSE
        if 'hdpi' in kwargs:
            hdpi = glfw.TRUE if kwargs['hdpi'] else glfw.FALSE
        glfw.window_hint(glfw.COCOA_RETINA_FRAMEBUFFER, hdpi)

        vsync = False
        if 'vsync' in kwargs:
            vsync = bool(kwargs['vsync'])

        self.x_scale = kwargs['x_scale'] if 'x_scale' in kwargs else 1
        self.y_scale = kwargs['y_scale'] if 'y_scale' in kwargs else 1
        if 'scale' in kwargs:
            self.x_scale = self.y_scale = kwargs['scale']

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

        self._color = (0, 0, 0, 1)
        if 'color' in kwargs:
            self._color = kwargs['color']

        if not self._window:
            glfw.terminate()
            raise UserWarning('Unable to create window')

        glfw.set_input_mode(self._window, glfw.STICKY_KEYS, glfw.TRUE)
        glfw.make_context_current(self._window)
        glfw.swap_interval(1 if vsync else 0)

        gl_version = glGetString(GL_VERSION).decode('utf-8')
        print(f'OpenGL Version string: {gl_version}')

        self._spaces = pxng.Spaces(self.width, self.height)
        self._spaces.projection.m = glm.ortho(0, width, height, 0, -1, 1)
        self._spaces.view.scale((self.x_scale, self.y_scale, 1))

        self._text_renderer = pxng.TextRenderer(self.create_default_font())
        self._elapsed_time = 0
        self._current_tint = WHITE
        self._key_poller = pxng.keys.KeyPoller()
        self._mouse_poller = pxng.mouse.Mouse(self._window)

        self._quad = Quad()
        self._grid = Grid(self.width, self.height)
def main():
    # initialize glfw
    if not glfw.init():
        return

    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_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    cube = ObjLoader()
    cube.load_model("res/cube/cube.obj")
    cube_tex = TextureLoader.load_texture("res/cube/cube_texture.jpg")
    cube_texture_offset = len(cube.vertex_index) * 12

    monkey = ObjLoader()
    monkey.load_model("res/monkey/monkey.obj")
    monkey_tex = TextureLoader.load_texture("res/monkey/monkey.jpg")
    monkey_texture_offset = len(monkey.vertex_index) * 12

    monster = ObjLoader()
    monster.load_model("res/monster/monster.obj")
    monster_tex = TextureLoader.load_texture("res/monster/monster.jpg")
    monster_texture_offset = len(monster.vertex_index) * 12

    generic_shader = ShaderLoader.compile_shader("shaders/generic_vertex_shader.vs", "shaders/generic_fragment_shader.fs")

    cube_vao = glGenVertexArrays(1)
    glBindVertexArray(cube_vao)
    cube_vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, cube_vbo)
    glBufferData(GL_ARRAY_BUFFER, cube.model.itemsize * len(cube.model), cube.model, GL_STATIC_DRAW)
    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.model.itemsize * 3, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.model.itemsize * 2, ctypes.c_void_p(cube_texture_offset))
    glEnableVertexAttribArray(1)
    glBindVertexArray(0)

    monkey_vao = glGenVertexArrays(1)
    glBindVertexArray(monkey_vao)
    monkey_vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, monkey_vbo)
    glBufferData(GL_ARRAY_BUFFER, monkey.model.itemsize * len(monkey.model), monkey.model, GL_STATIC_DRAW)
    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 3, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 2, ctypes.c_void_p(monkey_texture_offset))
    glEnableVertexAttribArray(1)
    glBindVertexArray(0)

    monster_vao = glGenVertexArrays(1)
    glBindVertexArray(monster_vao)
    monster_vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, monster_vbo)
    glBufferData(GL_ARRAY_BUFFER, monster.model.itemsize * len(monster.model), monster.model, GL_STATIC_DRAW)
    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monster.model.itemsize * 3, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monster.model.itemsize * 2, ctypes.c_void_p(monster_texture_offset))
    glEnableVertexAttribArray(1)
    glBindVertexArray(0)

    glClearColor(0.13, 0.2, 0.15, 1.0)
    glEnable(GL_DEPTH_TEST)

    projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0)
    cube_model = matrix44.create_from_translation(Vector3([-4.0, 0.0, -3.0]))
    monkey_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -3.0]))
    monster_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -10.0]))

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

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

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

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

        glBindVertexArray(cube_vao)
        glBindTexture(GL_TEXTURE_2D, cube_tex)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * cube_model)
        glDrawArrays(GL_TRIANGLES, 0, len(cube.vertex_index))
        glBindVertexArray(0)

        glBindVertexArray(monkey_vao)
        glBindTexture(GL_TEXTURE_2D, monkey_tex)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_model)
        glDrawArrays(GL_TRIANGLES, 0, len(monkey.vertex_index))
        glBindVertexArray(0)

        glBindVertexArray(monster_vao)
        glBindTexture(GL_TEXTURE_2D, monster_tex)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, monster_model)
        glDrawArrays(GL_TRIANGLES, 0, len(monster.vertex_index))
        glBindVertexArray(0)

        glfw.swap_buffers(window)

    glfw.terminate()
Exemple #17
0
def main():
    init()

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

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

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)
    program_id = load_shaders('res/glsl/chapter8.vs', 'res/glsl/chapter8.fs')
    tex = texture.load('res/texture/eye.bmp')
    #tex = texture.load('res/texture/earth.bmp')
    texture_id = glGetUniformLocation(program_id, 'TextureSampler')

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

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

    scene = load('res/model/sphere.obj')
    mesh = scene.meshes[0]
    vertex = mesh.vertices
    uv = mesh.texturecoords
    normal = mesh.normals
    index = mesh.faces

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

    uv_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
    glBufferData(GL_ARRAY_BUFFER, uv.nbytes, uv, GL_STATIC_DRAW)

    normal_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
    glBufferData(GL_ARRAY_BUFFER, normal.nbytes, normal, GL_STATIC_DRAW)

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

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

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

        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, tex)
        glUniform1i(texture_id, 0)

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

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

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

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

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Exemple #18
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()
def main():
	if not opengl_init():
		return

	# Enable key events
	glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) 
	
	# Enable key event callback
	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)
	
	vertex_array_id = glGenVertexArrays(1)
	glBindVertexArray( vertex_array_id )

	program_id = common.LoadShaders( "Shaders/Tutorial4/TransformVertexShader.vertexshader",
		"Shaders/Tutorial4/ColorFragmentShader.fragmentshader" )
	
	# Get a handle for our "MVP" uniform
	matrix_id= glGetUniformLocation(program_id, "MVP");

	# Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)
	
	# Camera matrix
	view = mat4.lookat(vec3(4,3,-3), # Camera is at (4,3,3), in World Space
					vec3(0,0,0), # and looks at the origin
					vec3(0,1,0)) 
	
	# Model matrix : an identity matrix (model will be at the origin)
	model = mat4.identity()

	# Our ModelViewProjection : multiplication of our 3 matrices
	mvp = projection * view * model

	# Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
	# A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
	vertex_data = [ 
		-1.0,-1.0,-1.0,
		-1.0,-1.0, 1.0,
		-1.0, 1.0, 1.0,
		 1.0, 1.0,-1.0,
		-1.0,-1.0,-1.0,
		-1.0, 1.0,-1.0,
		 1.0,-1.0, 1.0,
		-1.0,-1.0,-1.0,
		 1.0,-1.0,-1.0,
		 1.0, 1.0,-1.0,
		 1.0,-1.0,-1.0,
		-1.0,-1.0,-1.0,
		-1.0,-1.0,-1.0,
		-1.0, 1.0, 1.0,
		-1.0, 1.0,-1.0,
		 1.0,-1.0, 1.0,
		-1.0,-1.0, 1.0,
		-1.0,-1.0,-1.0,
		-1.0, 1.0, 1.0,
		-1.0,-1.0, 1.0,
		 1.0,-1.0, 1.0,
		 1.0, 1.0, 1.0,
		 1.0,-1.0,-1.0,
		 1.0, 1.0,-1.0,
		 1.0,-1.0,-1.0,
		 1.0, 1.0, 1.0,
		 1.0,-1.0, 1.0,
		 1.0, 1.0, 1.0,
		 1.0, 1.0,-1.0,
		-1.0, 1.0,-1.0,
		 1.0, 1.0, 1.0,
		-1.0, 1.0,-1.0,
		-1.0, 1.0, 1.0,
		 1.0, 1.0, 1.0,
		-1.0, 1.0, 1.0,
		 1.0,-1.0, 1.0]

	# One color for each vertex. They were generated randomly.
	color_data = [ 
		0.583,  0.771,  0.014,
		0.609,  0.115,  0.436,
		0.327,  0.483,  0.844,
		0.822,  0.569,  0.201,
		0.435,  0.602,  0.223,
		0.310,  0.747,  0.185,
		0.597,  0.770,  0.761,
		0.559,  0.436,  0.730,
		0.359,  0.583,  0.152,
		0.483,  0.596,  0.789,
		0.559,  0.861,  0.639,
		0.195,  0.548,  0.859,
		0.014,  0.184,  0.576,
		0.771,  0.328,  0.970,
		0.406,  0.615,  0.116,
		0.676,  0.977,  0.133,
		0.971,  0.572,  0.833,
		0.140,  0.616,  0.489,
		0.997,  0.513,  0.064,
		0.945,  0.719,  0.592,
		0.543,  0.021,  0.978,
		0.279,  0.317,  0.505,
		0.167,  0.620,  0.077,
		0.347,  0.857,  0.137,
		0.055,  0.953,  0.042,
		0.714,  0.505,  0.345,
		0.783,  0.290,  0.734,
		0.722,  0.645,  0.174,
		0.302,  0.455,  0.848,
		0.225,  0.587,  0.040,
		0.517,  0.713,  0.338,
		0.053,  0.959,  0.120,
		0.393,  0.621,  0.362,
		0.673,  0.211,  0.457,
		0.820,  0.883,  0.371,
		0.982,  0.099,  0.879]

	vertex_buffer = glGenBuffers(1);
	array_type = GLfloat * len(vertex_data)
	glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
	glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW)

	color_buffer = glGenBuffers(1);
	array_type = GLfloat * len(color_data)
	glBindBuffer(GL_ARRAY_BUFFER, color_buffer)
	glBufferData(GL_ARRAY_BUFFER, len(color_data) * 4, array_type(*color_data), GL_STATIC_DRAW)



	while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window):
		# Enable depth test
		glEnable(GL_DEPTH_TEST)
		# Accept fragment if it closer to the camera than the former one
		glDepthFunc(GL_LESS)
        
		glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT)

		glUseProgram(program_id)

		# Send our transformation to the currently bound shader, 
		# in the "MVP" uniform
		glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data)
		# 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
		#
		#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, color_buffer);
		glVertexAttribPointer(
			1,                  # 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, 12*3) #3 indices starting at 0 -> 1 triangle

		# 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 vertex_array_id.  
	# These 2 functions expect arrays of values
	glDeleteBuffers(1, [vertex_buffer])
	glDeleteBuffers(1, [color_buffer])
	glDeleteProgram(program_id)
	glDeleteVertexArrays(1, [vertex_array_id])

	glfw.terminate()
Exemple #20
0
 def setup_window(self, parent):
     glfw.set_input_mode(parent.window, glfw.CURSOR, glfw.CURSOR_DISABLED)
     glfw.set_cursor_pos_callback(parent.window, self.mouse_callback)
Exemple #21
0
def main():
    if not opengl_init():
        return

    load_gedung("itb_coordinate.txt")

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

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

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray( vertex_array_id )

    program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" )

    vertex_data = createAllBuilding()

    # Two UV coordinatesfor each vertex. They were created withe Blender.
    uv_data = createUVData()

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

    texture = []
    texture_id = []

    texture_id.append(glGetUniformLocation(program_id, "myTextureSampler"))
    texture_id.append(glGetUniformLocation(program_id, "myTextureSampler2"))

    tex1 = TextureLoader.load_texture("res/crate.jpg")
    tex2 = TextureLoader.load_texture("res/metal.jpg")
    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices



    vertex_buffer = glGenBuffers(1);
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW)

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

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

    glUseProgram(program_id)

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

    glActiveTexture(GL_TEXTURE0);

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

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

        ##################################################################### SET TEXTURE 1

        # Send our transformation to the currently bound shader,
        # in the "MVP" uniform
        # draws Aula barat, timur ; CC barat, timur

        glBindTexture(GL_TEXTURE_2D, tex1);
        glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data)
Exemple #22
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.4.light_casters.vs", CURDIR / "shaders/5.4.light_casters.fs")

    vertices = [
        # positions        normals           texture coords
        -0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  0.0,
         0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  0.0,
         0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  1.0,
         0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  1.0,
        -0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  1.0,
        -0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  0.0,

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

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

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

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

        -0.5,  0.5, -0.5,  0.0,  1.0,  0.0,  0.0,  1.0,
         0.5,  0.5, -0.5,  0.0,  1.0,  0.0,  1.0,  1.0,
         0.5,  0.5,  0.5,  0.0,  1.0,  0.0,  1.0,  0.0,
         0.5,  0.5,  0.5,  0.0,  1.0,  0.0,  1.0,  0.0,
        -0.5,  0.5,  0.5,  0.0,  1.0,  0.0,  0.0,  0.0,
        -0.5,  0.5, -0.5,  0.0,  1.0,  0.0,  0.0,  1.0
    ]
    vertices = (c_float * len(vertices))(*vertices)

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

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

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

    gl.glBindVertexArray(cube_vao)

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

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

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

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

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

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

        # -- input
        process_input(window)

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

        lighting_shader.use()
        lighting_shader.set_vec3("light.position", camera.position)
        lighting_shader.set_vec3("light.direction", camera.front)
        lighting_shader.set_float("light.cutOff", math.cos(math.radians(12.5)))
        lighting_shader.set_float("light.outerCutOff", math.cos(math.radians(17.5)))
        lighting_shader.set_vec3("viewPos", camera.position)

        # -- light properties
        lighting_shader.set_vec3("light.ambient", Vector3([0.1, 0.1, 0.1]))
        # we configure the diffuse intensity slightly higher; the right lighting conditions differ with each lighting method and environment.
        # each environment and lighting type requires some tweaking to get the best out of your environment.
        lighting_shader.set_vec3("light.diffuse", Vector3([0.8, 0.8, 0.8]))
        lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0]))
        lighting_shader.set_float("light.constant", 1.0)
        lighting_shader.set_float("light.linear", 0.09)
        lighting_shader.set_float("light.quadratic", 0.032)

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

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

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

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

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

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

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

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

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

        glfw.swap_buffers(window)
        glfw.poll_events()

    gl.glDeleteVertexArrays(1, id(cube_vao))
    gl.glDeleteVertexArrays(1, id(light_vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Exemple #23
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()
Exemple #24
0
	camera = glutils.Camera([0.0, 0.0, 5.0],[0.0, 0.0, 0.0],[0.0, 1.0, 0.0])
	cameraPos  =np.array([0,0,1], np.float32)
	cameraFront=np.array([1,0.0], np.float32)
	cameraUp   =np.array([0,0,1], np.float32)
	# Initialize the library
	if not glfw.init():
		sys.exit()
	# Create a windowed mode window and its OpenGL context
	window = glfw.create_window(screen_size[0],screen_size[1], "draw Cube ", None, None)
	if not window:
		glfw.terminate()
		sys.exit()
	# Make the window's context current
	glfw.make_context_current(window)
	#glfw.set_input_mode(window, glfw.cursor, glfw.GLFW_CURSOR_HIDDEN)
	glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_HIDDEN)
	# Install a key handler
	glfw.set_key_callback(window, on_key)
	glfw.set_mouse_button_callback(window,on_mouse_button)
	# set window  mouse callbacks
	glfw.set_cursor_pos_callback(window,  mouse_callback)
	build()
	glEnable(GL_MULTISAMPLE)
	glEnable(GL_DEPTH_TEST)
	glShadeModel(GL_SMOOTH)  # most obj files expect to be smooth-shaded	
	while not glfw.window_should_close(window):
		currentFrame = glfw.get_time()
		deltaTime = currentFrame - lastFrame		   
		lastFrame = currentFrame
		glfw.poll_events()
		do_movement()
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(WIDTH, HEIGHT, "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
    cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj")
    monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj")
    floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj")

    # VAO and VBO
    VAO = glGenVertexArrays(3)
    VBO = glGenBuffers(3)

    # cube VAO
    glBindVertexArray(VAO[0])

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

    # cube Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0])
    glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)

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

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

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

    # floor VAO
    glBindVertexArray(VAO[2])
    # floor Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[2])
    glBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer, GL_STATIC_DRAW)

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


    textures = glGenTextures(3)
    load_texture("meshes/cube.jpg", textures[0])
    load_texture("meshes/monkey.jpg", textures[1])
    load_texture("meshes/floor.jpg", textures[2])

    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, WIDTH / HEIGHT, 0.1, 100)
    cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0]))
    monkey_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([-4, 4, -4]))
    floor_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0]))

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

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

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

        # draw the monkey
        glBindVertexArray(VAO[1])
        glBindTexture(GL_TEXTURE_2D, textures[1])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_pos)
        glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices))

        # draw the floor
        glBindVertexArray(VAO[2])
        glBindTexture(GL_TEXTURE_2D, textures[2])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, floor_pos)
        glDrawArrays(GL_TRIANGLES, 0, len(floor_indices))

        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Exemple #26
0
def main():
    init()

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

    glfw.make_context_current(window)
    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)
    glClearColor(0.3, 0.3, 0.3, 1)

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

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

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

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

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

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

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

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

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

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

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

        glDrawArrays(GL_TRIANGLES, 0, int(len(vertex)/3))

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
def main():
    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);
    glEnable(GL_CULL_FACE)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray( vertex_array_id )

    program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" )
    
    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP");

    texture = load_image(".\\content\\uvtemplate.bmp")
    texture_id  = glGetUniformLocation(program_id, "myTextureSampler")

    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    vertex_data = [ 
        -1.0,-1.0,-1.0,
        -1.0,-1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0,-1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0,-1.0, 1.0]

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

    vertex_buffer = glGenBuffers(1);
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW)

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

    # 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 triangle !
        glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle

        # 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()
def main():
    if not opengl_init():
        return

    # Enable key events
    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.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)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)

    program_id = common.LoadShaders(
        ".\\shaders\\Tutorial5\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial5\\TextureFragmentShader.fragmentshader")

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

    # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)

    # Camera matrix
    view = mat4.lookat(
        vec3(4, 3, -3),  # Camera is at (4,3,3), in World Space
        vec3(0, 0, 0),  # and looks at the origin
        vec3(0, 1, 0))

    # Model matrix : an identity matrix (model will be at the origin)
    model = mat4.identity()

    # Our ModelViewProjection : multiplication of our 3 matrices
    mvp = projection * view * model

    texture = load_image(".\\content\\uvtemplate.bmp")
    texture_id = glGetUniformLocation(program_id, "myTextureSampler")

    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    koordinat = 0.01
    koordinat2 = 0.5
    koordinat3 = 1.7
    koordinat4 = 1.0
    koordinat5 = 1.7
    koordinat6 = 0.1

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

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

    vertex_buffer = glGenBuffers(1)
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(vertex_data) * 4, array_type(*vertex_data),
                 GL_STATIC_DRAW)

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

    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)

        # 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 0. No particular reason for 0, 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 triangle !
        glDrawArrays(GL_TRIANGLES, 0,
                     12 * 3)  #3 indices starting at 0 -> 1 triangle

        # 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 vertex_array_id.
    # These 2 functions expect arrays of values
    glDeleteBuffers(1, [vertex_buffer])
    glDeleteBuffers(1, [uv_buffer])
    glDeleteProgram(program_id)
    glDeleteTextures([texture_id])
    glDeleteVertexArrays(1, [vertex_array_id])

    glfw.terminate()
Exemple #29
0
    def init(self):
        super(Risk, self).init()
        glfw.set_input_mode(self.window, glfw.CURSOR, False)

        self.shaders = shaders.init()
def main():
    if not opengl_init():
        return

    # Enable key events
    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.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); 

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray( vertex_array_id )


    program_id = common.LoadShaders( ".\\shaders\\Tutorial5\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial5\\TextureFragmentShader.fragmentshader" )
    
    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP");

    # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)
    
    # Camera matrix
    view = mat4.lookat(vec3(4,3,-3), # Camera is at (4,3,3), in World Space
                    vec3(0,0,0), # and looks at the origin
                    vec3(0,1,0)) 
    
    # Model matrix : an identity matrix (model will be at the origin)
    model = mat4.identity()

    # Our ModelViewProjection : multiplication of our 3 matrices
    mvp = projection * view * model


    texture = load_image(".\\content\\uvtemplate.bmp")
    texture_id  = glGetUniformLocation(program_id, "myTextureSampler")

    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    vertex_data = [ 
        -1.0,-1.0,-1.0,
        -1.0,-1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0,-1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0,-1.0, 1.0]

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

    vertex_buffer = glGenBuffers(1);
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW)

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



    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)

        # 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 0. No particular reason for 0, 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 triangle !
        glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle

        # 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 vertex_array_id.  
    # These 2 functions expect arrays of values
    glDeleteBuffers(1, [vertex_buffer])
    glDeleteBuffers(1, [uv_buffer])
    glDeleteProgram(program_id)
    glDeleteTextures([texture_id])
    glDeleteVertexArrays(1, [vertex_array_id])

    glfw.terminate()
Exemple #31
0
def main():
    global hdrbuffer, blurbuffer, cube

    if not glfw.init():
        print('Failed to initialize GLFW.')
        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, GL_TRUE)
    glfw.window_hint(glfw.SAMPLES, config['sampling_level'])

    if config['fullscreen']:
        global width, height
        mode = glfw.get_video_mode(glfw.get_primary_monitor())
        width, height = mode.size.width, mode.size.height
        window = glfw.create_window(mode.size.width, mode.size.height,
                                    config['app_name'],
                                    glfw.get_primary_monitor(), None)
    else:
        window = glfw.create_window(width, height, config['app_name'], None,
                                    None)
    if not window:
        print('Failed to create GLFW Window.')
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)
    glfw.set_framebuffer_size_callback(window, resizeCallback)
    glfw.set_cursor_pos_callback(window, mouseMove)
    glfw.set_key_callback(window, keyCallback)

    glEnable(GL_DEPTH_TEST)
    glEnable(GL_MULTISAMPLE)
    glEnable(GL_CULL_FACE)
    glCullFace(GL_BACK)

    program = getLinkedProgram('resources/shaders/vert.vs',
                               'resources/shaders/frag.fs')
    depthProgram = getLinkedProgram('resources/shaders/shadow_depth.vs',
                                    'resources/shaders/shadow_depth.fs')
    blurProgram = getLinkedProgram('resources/shaders/blur.vs',
                                   'resources/shaders/blur.fs')
    hdrProgram = getLinkedProgram('resources/shaders/hdr.vs',
                                  'resources/shaders/hdr.fs')

    blurProgram.use()
    blurProgram.setInt('image', 0)

    hdrProgram.use()
    hdrProgram.setInt('sceneMap', 0)
    hdrProgram.setInt('bloomMap', 1)

    hdrbuffer = HDRbuffer()
    hdrbuffer.create(width, height)
    blurbuffer = Blurbuffer()
    blurbuffer.create(width, height)

    bloom = Bloom(hdrbuffer, hdrProgram, blurbuffer, blurProgram)

    lightPos = glm.vec3(10, 100, 0)
    perspective = glm.perspective(45, width / height, config['near_plane'],
                                  config['far_plane'])

    shadow = Shadow(lightPos, config['near_plane'], config['far_plane'])
    shadow.create(config['shadow_width'], config['shadow_height'])

    cube = Model('resources/models/cube.json')
    texture = loadTexture2D('resources/textures/diffuse.jpg')
    normal = loadTexture2D('resources/textures/normal.jpg')
    specular = loadTexture2D('resources/textures/specular.jpg')
    depth = loadTexture2D('resources/textures/depth.jpg')

    blockPositions = generateVoxelPositions(config['world_width'],
                                            config['world_height'],
                                            config['world_width'])
    cube.setMultiplePositions(blockPositions)
    blockPositions.clear()

    lastTime = glfw.get_time()
    while not glfw.window_should_close(window):
        if config['debug_mode']:
            print(glGetError())

        currentTime = glfw.get_time()
        deltaTime = currentTime - lastTime
        lastTime = currentTime

        lightPos.x = config['world_width'] / 2
        lightPos.z = math.sin(currentTime * 0.1) * config['world_depth'] * 2
        lightPos.y = config['world_height'] * 2
        shadow.updateMatrix(lightPos, config['near_plane'],
                            config['far_plane'])

        moveInput(window, deltaTime)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glClearColor(0.1, 0.2, 0.8, 1)

        shadow.castShadow(depthProgram)
        cube.drawMultiple(depthProgram)
        shadow.endCastShadow(program)

        hdrbuffer.bind()
        glViewport(0, 0, width, height)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        program.use()
        program.setMat4('viewProject', perspective * camera.getViewMatrix())
        program.setVec3('viewPos', camera.position)
        program.setVec3('lightPos', lightPos)

        glActiveTexture(GL_TEXTURE1)
        program.setInt('mat.diffuseMap', 1)
        texture.bind()

        glActiveTexture(GL_TEXTURE2)
        program.setInt('mat.normalMap', 2)
        normal.bind()

        glActiveTexture(GL_TEXTURE3)
        program.setInt('mat.specularMap', 3)
        specular.bind()

        glActiveTexture(GL_TEXTURE4)
        program.setInt('mat.depthMap', 4)
        depth.bind()
        program.setFloat('mat.shininess', 128)
        program.setFloat('mat.heightScale', 0.12)

        cube.drawMultiple(program)
        hdrbuffer.unbind()
        hdrbuffer.finalize()

        bloom.drawProcessedScene()

        glfw.poll_events()
        glfw.swap_buffers(window)

    glfw.terminate()
Exemple #32
0
 def stop_drag(self):
     glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_NORMAL)
     self.is_drag = False
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.0,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\\common\\StandardShading.vertexshader",
        ".\\shaders\\common\\StandardShading.fragmentshader" )

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

    # Read our OBJ file
    vertices,faces,uvs,normals,colors = objloader.load(".\\content\\male_apose_closed2.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)
    normal_data = objloader.generate_2d_ctypes(normal_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)

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

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

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

    last_time = glfw.get_time()
    frames = 0

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

        current_time = glfw.get_time()
        glUseProgram(program_id)

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

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

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

        #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 : normals
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, normal_buffer);
        glVertexAttribPointer(
            1,                                  # attribute
            3,                                  # size
            GL_FLOAT,                           # type
            GL_FALSE,                           # ormalized?
            0,                                  # stride
            null                                # array buffer offset (c_type == void*)
        )


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

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


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


        # Take screenshot of active buffer
        if glfw.get_key( window, glfw.KEY_P ) == glfw.PRESS:
            print("Saving screenshot as 'test.bmp'")
            screenshot('test.bmp',1024,768)

        # Dump MVP matrix to the command line
        if glfw.get_key( window, glfw.KEY_M ) == glfw.PRESS:
            print(mvp)
            
        # Poll for and process events
        glfw.poll_events()

        frames += 1

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

    glfw.terminate()
Exemple #34
0
def main():
    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);
    glEnable(GL_CULL_FACE)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray( vertex_array_id )

    program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" )
    
    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP");

    texture = load_image(".\\content\\uvtemplate.bmp")
    texture_id  = glGetUniformLocation(program_id, "myTextureSampler")

    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    vertex_data = [ 
        -1.0,-1.0,-1.0,
        -1.0,-1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
         1.0,-1.0, 1.0,
        -1.0,-1.0, 1.0,
        -1.0,-1.0,-1.0,
        -1.0, 1.0, 1.0,
        -1.0,-1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0,-1.0,
         1.0,-1.0,-1.0,
         1.0, 1.0, 1.0,
         1.0,-1.0, 1.0,
         1.0, 1.0, 1.0,
         1.0, 1.0,-1.0,
        -1.0, 1.0,-1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0,-1.0,
        -1.0, 1.0, 1.0,
         1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
         1.0,-1.0, 1.0]

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

    vertex_buffer = glGenBuffers(1);
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW)

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

    # 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 triangle !
        glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle

        # 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()
def main():

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

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

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

    # Enable depth test
    glEnable(GL_DEPTH_TEST)

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

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

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    last_time = glfw.get_time()
    frames = 0

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

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

        glUseProgram(program_id)

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

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

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

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

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

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

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

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

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

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

        # Poll for and process events
        glfw.poll_events()

        frames += 1

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

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

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

##CALLBACK FUNCTIONS
##set the callback func for window resize
glfw.set_window_size_callback(window, window_resize)
##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)
##call back for mouse scroll
glfw.set_scroll_callback(window, scroll_clb)

##make the context current
glfw.make_context_current(window)

##load here the 3d meshes

dh_indices, dh_buffer = ObjLoader.load_model("meshes/final.obj")
##dh_indices, dh_buffer=ObjLoader.load_model("meshes/cube.obj")
shader = ShaderLoader.compile_shader("shaders/shader_vert.vs",
                                     "shaders/shader_frag.fs")
##VAO AND VBO
VAO = glGenVertexArrays(1)
VBO = glGenBuffers(1)
Exemple #37
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\\Tutorial3\\SimpleTransform.vertexshader",
        ".\\shaders\\Tutorial3\\SingleColor.fragmentshader")

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

    # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)

    # Camera matrix
    view = mat4.lookat(
        vec3(4, 3, 3),  # Camera is at (4,3,3), in World Space
        vec3(0, 0, 0),  # and looks at the origin
        vec3(0, 1, 0))

    # Model matrix : an identity matrix (model will be at the origin)
    model = mat4.identity()

    # Our ModelViewProjection : multiplication of our 3 matrices
    mvp = projection * view * model

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

        # Send our transformation to the currently bound shader,
        # in the "MVP" uniform
        glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data)
        # 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()
Exemple #38
0
    def __init__(
        self,
        module,
        width,
        height,
        caption,
        scale,
        palette,
        fps,
        border_width,
        border_color,
    ):
        if glfw.get_version() < tuple(map(int, GLFW_VERSION.split("."))):
            raise RuntimeError(
                "glfw version is lower than {}".format(GLFW_VERSION))

        if width > APP_SCREEN_MAX_SIZE or height > APP_SCREEN_MAX_SIZE:
            raise ValueError("screen size is larger than {}x{}".format(
                APP_SCREEN_MAX_SIZE, APP_SCREEN_MAX_SIZE))

        global pyxel
        pyxel = module

        self._palette = palette[:]
        self._fps = fps
        self._border_width = border_width
        self._border_color = border_color
        self._next_update_time = 0
        self._one_frame_time = 1 / fps
        self._key_state = {}
        self._is_mouse_visible = False
        self._update = None
        self._draw = None
        self._capture_start = 0
        self._capture_count = 0
        self._capture_images = [None] * APP_GIF_CAPTURE_COUNT

        self._perf_monitor_is_enabled = False
        self._perf_fps_count = 0
        self._perf_fps_start_time = 0
        self._perf_fps = 0
        self._perf_update_count = 0
        self._perf_update_total_time = 0
        self._perf_update_time = 0
        self._perf_draw_count = 0
        self._perf_draw_total_time = 0
        self._perf_draw_time = 0

        # exports variables
        pyxel._app = self
        pyxel.width = width
        pyxel.height = height
        pyxel.mouse_x = 0
        pyxel.mouse_y = 0
        pyxel.frame_count = 0

        # initialize window
        if not glfw.init():
            exit()

        monitor = glfw.get_primary_monitor()
        display_width, display_height = glfw.get_video_mode(monitor)[0]

        if scale == 0:
            scale = max(
                min(
                    (display_width // width) - APP_SCREEN_SCALE_CUTDOWN,
                    (display_height // height) - APP_SCREEN_SCALE_CUTDOWN,
                ),
                APP_SCREEN_SCALE_MINIMUM,
            )

        window_width = width * scale + border_width
        window_height = height * scale + border_width
        self._window = glfw.create_window(window_width, window_height, caption,
                                          None, None)

        if not self._window:
            glfw.terminate()
            exit()

        glfw.set_window_pos(
            self._window,
            (display_width - window_width) // 2,
            (display_height - window_height) // 2,
        )

        glfw.make_context_current(self._window)
        glfw.set_window_size_limits(self._window, width, height,
                                    glfw.DONT_CARE, glfw.DONT_CARE)
        self._hidpi_scale = (glfw.get_framebuffer_size(self._window)[0] /
                             glfw.get_window_size(self._window)[0])
        self._update_viewport()

        glfw.set_key_callback(self._window, self._key_callback)
        glfw.set_mouse_button_callback(self._window,
                                       self._mouse_button_callback)

        glfw.set_window_icon(self._window, 1, [get_icon_image()])
        glfw.set_input_mode(self._window, glfw.CURSOR, glfw.CURSOR_HIDDEN)

        # initialize renderer
        self._renderer = Renderer(width, height)

        # initialize audio player
        self._audio_player = AudioPlayer()

        # export module functions
        pyxel.btn = self.btn
        pyxel.btnp = self.btnp
        pyxel.btnr = self.btnr
        pyxel.mouse = self.mouse
        pyxel.run = self.run
        pyxel.run_with_profiler = self.run_with_profiler
        pyxel.quit = self.quit
        pyxel.save = self.save
        pyxel.load = self.load
        pyxel.image = self._renderer.image
        pyxel.tilemap = self._renderer.tilemap
        pyxel.clip = self._renderer.draw_command.clip
        pyxel.pal = self._renderer.draw_command.pal
        pyxel.cls = self._renderer.draw_command.cls
        pyxel.pix = self._renderer.draw_command.pix
        pyxel.line = self._renderer.draw_command.line
        pyxel.rect = self._renderer.draw_command.rect
        pyxel.rectb = self._renderer.draw_command.rectb
        pyxel.circ = self._renderer.draw_command.circ
        pyxel.circb = self._renderer.draw_command.circb
        pyxel.blt = self._renderer.draw_command.blt
        pyxel.bltm = self._renderer.draw_command.bltm
        pyxel.text = self._renderer.draw_command.text
        pyxel.sound = self._audio_player.sound
        pyxel.music = self._audio_player.music
        pyxel.play = self._audio_player.play
        pyxel.playm = self._audio_player.playm
        pyxel.stop = self._audio_player.stop

        # initialize mouse cursor
        pyxel.image(3,
                    system=True).set(MOUSE_CURSOR_IMAGE_X,
                                     MOUSE_CURSOR_IMAGE_Y, MOUSE_CURSOR_DATA)
Exemple #39
0
def main():
    if not opengl_init():
        return

    # Enable key events
    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)

    # Enable key event callback
    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)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)

    program_id = common.LoadShaders(
        ".\\shaders\\Tutorial4\\TransformVertexShader.vertexshader",
        ".\\shaders\\Tutorial4\\ColorFragmentShader.fragmentshader")

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

    # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)

    # Camera matrix
    view = mat4.lookat(
        vec3(4, 3, -3),  # Camera is at (4,3,3), in World Space
        vec3(0, 0, 0),  # and looks at the origin
        vec3(0, 1, 0))

    # Model matrix : an identity matrix (model will be at the origin)
    model = mat4.identity()

    # Our ModelViewProjection : multiplication of our 3 matrices
    mvp = projection * view * model

    # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    vertex_data = [
        -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
        -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0,
        -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0,
        -1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0,
        -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
        -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0
    ]

    # One color for each vertex. They were generated randomly.
    color_data = [
        0.583, 0.771, 0.014, 0.609, 0.115, 0.436, 0.327, 0.483, 0.844, 0.822,
        0.569, 0.201, 0.435, 0.602, 0.223, 0.310, 0.747, 0.185, 0.597, 0.770,
        0.761, 0.559, 0.436, 0.730, 0.359, 0.583, 0.152, 0.483, 0.596, 0.789,
        0.559, 0.861, 0.639, 0.195, 0.548, 0.859, 0.014, 0.184, 0.576, 0.771,
        0.328, 0.970, 0.406, 0.615, 0.116, 0.676, 0.977, 0.133, 0.971, 0.572,
        0.833, 0.140, 0.616, 0.489, 0.997, 0.513, 0.064, 0.945, 0.719, 0.592,
        0.543, 0.021, 0.978, 0.279, 0.317, 0.505, 0.167, 0.620, 0.077, 0.347,
        0.857, 0.137, 0.055, 0.953, 0.042, 0.714, 0.505, 0.345, 0.783, 0.290,
        0.734, 0.722, 0.645, 0.174, 0.302, 0.455, 0.848, 0.225, 0.587, 0.040,
        0.517, 0.713, 0.338, 0.053, 0.959, 0.120, 0.393, 0.621, 0.362, 0.673,
        0.211, 0.457, 0.820, 0.883, 0.371, 0.982, 0.099, 0.879
    ]

    vertex_buffer = glGenBuffers(1)
    array_type = GLfloat * len(vertex_data)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(vertex_data) * 4, array_type(*vertex_data),
                 GL_STATIC_DRAW)

    color_buffer = glGenBuffers(1)
    array_type = GLfloat * len(color_data)
    glBindBuffer(GL_ARRAY_BUFFER, color_buffer)
    glBufferData(GL_ARRAY_BUFFER,
                 len(color_data) * 4, array_type(*color_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 | GL_DEPTH_BUFFER_BIT)

        glUseProgram(program_id)

        # Send our transformation to the currently bound shader,
        # in the "MVP" uniform
        glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data)
        # 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
        #
        #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, color_buffer)
        glVertexAttribPointer(
            1,  # 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,
                     12 * 3)  #3 indices starting at 0 -> 1 triangle

        # 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 vertex_array_id.
    # These 2 functions expect arrays of values
    glDeleteBuffers(1, [vertex_buffer])
    glDeleteBuffers(1, [color_buffer])
    glDeleteProgram(program_id)
    glDeleteVertexArrays(1, [vertex_array_id])

    glfw.terminate()
Exemple #40
0
            if key == glfw.KEY_1:
                ogTexture = False
                newTexture = "polka.jpg"
            if key == glfw.KEY_2:
                ogTexture = False
                newTexture = "grunge_wall.jpg"
            if key == glfw.KEY_3:
                ogTexture = False
                newTexture = "old_rock.jpg"
            if key == glfw.KEY_4:
                ogTexture = False
                newTexture = "solar.jpg"

while not glfw.window_should_close(window):
	# Enable key events
    glfw.set_input_mode(window,glfw.STICKY_KEYS,gl.GL_TRUE) 
	# Enable key event callback
    glfw.set_key_callback(window,camera_handle)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT|gl.GL_DEPTH_BUFFER_BIT)

    gl.glUseProgram(shader)
    view = glm.lookAt(camera, center, up)

    glize(scene.rootnode)

    glfw.swap_buffers(window)
    glfw.poll_events()

#cerrar y eliminar todo para un cierre correcto
gl.glDeleteBuffers(1, [vertex_buffer_object])
gl.glDeleteBuffers(1, [element_buffer_object])
Exemple #41
0
 def cursor_hide(self):
     glfw.set_input_mode(self.__gl_handle, glfw.CURSOR, glfw.CURSOR_HIDDEN)
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()
Exemple #43
0
 def cursor_disable(self):
     glfw.set_input_mode(self.__gl_handle, glfw.CURSOR, glfw.CURSOR_DISABLED)
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()
Exemple #45
0
def main():
	if not glfw.init():
		return
	w_width = 800
	w_height = 600
	glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
	glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
	glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1)
	glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

	glfw.window_hint(glfw.RESIZABLE, GL_TRUE)
	window = glfw.create_window(w_width, w_height, "MY OPENGL", None, None)

	

	if not window:
		glfw.terminate()
		return

	glfw.make_context_current(window)
	# Enable key events
	glfw.set_input_mode(window, glfw.STICKY_KEYS,GL_TRUE) 
	# Enable key event callback
	glfw.set_key_callback(window, key_event)

	#when window resize
	# glfw.set_window_size_callback(window, window_resize)

	#adding colors
	#     x,    y,     z,   r,    g,   b    tx   ty
	cube = [
		-0.5, -0.5,  0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
		 0.5, -0.5,  0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
		 0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
		-0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

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

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

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

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

		 0.5,  0.5, -0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
		-0.5,  0.5, -0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
		-0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
		 0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0
	]
	cube = numpy.array(cube, dtype=numpy.float32)

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

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

	VAO = glGenVertexArrays(1)
	glBindVertexArray(VAO)

	shader = shaderLoader.compile_shader("./shaders/vertex_shader.vs", "./shaders/fragment_shader.fs")

	VBO = glGenBuffers(1) # vertex buffer object for GPU
	glBindBuffer(GL_ARRAY_BUFFER, VBO)
	#upload data to array buffer
	#                 buf type   byte  point     type
	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)

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

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

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

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

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

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

	glUseProgram(shader)

	glClearColor(.2, .3, .2, 1.0)
	glEnable(GL_DEPTH_TEST)
	# glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)


	#perspective part
	# view matrix
	view = pyrr.matrix44.create_from_translation(pyrr.Vector3([.0, .0, -3.0]))
	# global view
	# projection matrix
	projection = pyrr.matrix44.create_perspective_projection(45.0, w_width / w_height, 0.1, 100.0)
	# model position matrix
	model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0]))


	view_location = glGetUniformLocation(shader, "view")
	projection_location = glGetUniformLocation(shader, "projection")
	model_location = glGetUniformLocation(shader, "model")

	glUniformMatrix4fv(view_location, 1, GL_FALSE, view)
	glUniformMatrix4fv(model_location, 1, GL_FALSE, model)
	glUniformMatrix4fv(projection_location, 1, GL_FALSE, projection)

	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(.5 * glfw.get_time())
		rot_y = pyrr.Matrix44.from_y_rotation(.8 * glfw.get_time())

		transform_location = glGetUniformLocation(shader, "transform")
		glUniformMatrix4fv(transform_location, 1, GL_FALSE, rot_x * rot_y)
		glUniformMatrix4fv(model_location, 1, GL_FALSE, model)
		glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
		glfw.swap_buffers(window)
	
	glfw.terminate()
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\\Tutorial3\\SimpleTransform.vertexshader", 
		".\\shaders\\Tutorial3\\SingleColor.fragmentshader" )
	
	# Get a handle for our "MVP" uniform
	matrix_id= glGetUniformLocation(program_id, "MVP");

	# Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0)
	
	# Camera matrix
	view = mat4.lookat(vec3(4,3,3), # Camera is at (4,3,3), in World Space
					vec3(0,0,0), # and looks at the origin
					vec3(0,1,0)) 
	
	# Model matrix : an identity matrix (model will be at the origin)
	model = mat4.identity()

	# Our ModelViewProjection : multiplication of our 3 matrices
	mvp = projection * view * model
	
	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)
	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)

		# Send our transformation to the currently bound shader, 
		# in the "MVP" uniform
		glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data)
		# 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()
Exemple #47
0
def main():
    global delta_time, last_frame

    if not glfw.init():
        raise ValueError("Failed to initialize glfw")

    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/4.1.lighting_maps.vs",
                             CURDIR / "shaders/4.1.lighting_maps.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_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")

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

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

        # -- input
        process_input(window)

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

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

        # -- light properties
        lighting_shader.set_vec3("light.ambient", Vector3([0.2, 0.2, 0.2]))
        lighting_shader.set_vec3("light.diffuse", Vector3([0.5, 0.5, 0.5]))
        lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0]))

        # -- material properties
        lighting_shader.set_vec3("material.specular", Vector3([0.5, 0.5, 0.5]))
        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)

        # -- render cube
        gl.glBindVertexArray(cube_vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

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

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

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

        glfw.swap_buffers(window)
        glfw.poll_events()

    gl.glDeleteVertexArrays(1, id(cube_vao))
    gl.glDeleteVertexArrays(1, id(light_vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Exemple #48
0
 def capture_mouse(self):
     glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)
     self.mouse_captured = True
Exemple #49
0
 def release_mouse(self):
     glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_NORMAL)
     self.mouse_captured = False
Exemple #50
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\\Tutorial9\\StandardShading.vertexshader",
        ".\\shaders\\Tutorial9\\StandardShading.fragmentshader" )
    
    # Get a handle for our "MVP" uniform
    matrix_id = glGetUniformLocation(program_id, "MVP")
    view_matrix_id = glGetUniformLocation(program_id, "V")
    model_matrix_id = glGetUniformLocation(program_id, "M")

    # Load the texture
    texture = textureutils.load_image(".\\content\\uvmap_suzanne.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\\suzanne.obj")
    vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors)

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

    indexed_vertices, indexed_uvs, indexed_normals, indices = vboindexer.indexVBO(vertex_data,uv_data,normal_data)
    
    indexed_vertices = c_type_fill(indexed_vertices,GLfloat)
    indexed_uvs = c_type_fill(indexed_uvs,GLfloat)
    indexed_normals = c_type_fill(indexed_normals,GLfloat)
    indices = c_type_fill_1D(indices,GLushort)


    # Load OBJ in to a VBO
    vertex_buffer = glGenBuffers(1);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_vertices) * 4 * 3, indexed_vertices, GL_STATIC_DRAW)

    uv_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_uvs) * 4 * 2, indexed_uvs, GL_STATIC_DRAW)

    normal_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
    glBufferData(GL_ARRAY_BUFFER, len(indexed_normals) * 4 * 3, indexed_normals, GL_STATIC_DRAW)

    # Generate a buffer for the indices as well
    elementbuffer = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 2, indices , GL_STATIC_DRAW);

    # vsync and glfw do not play nice.  when vsync is enabled mouse movement is jittery.
    common.disable_vsyc()
    
    # Get a handle for our "LightPosition" uniform
    glUseProgram(program_id);
    light_id = glGetUniformLocation(program_id, "LightPosition_worldspace");

    last_time = glfw.get_time()
    frames = 0

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

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

        glUseProgram(program_id)

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

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

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

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

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

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

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


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

        # Draw the triangles !
        glDrawElements(
            GL_TRIANGLES,           # mode
            len(indices),           # count
            GL_UNSIGNED_SHORT,      # type
            null                    # element array buffer offset
        )
        # Not strictly necessary because we only have 
        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)
    
    
        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

        frames += 1

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

    glfw.terminate()
def main():
    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()