Python之OpenGL笔记(13):给立方体加纹理

一、目的

1、给旋转的立方体加纹理。

二、程序运行结果

Python之OpenGL笔记(13):给立方体加纹理_第1张图片

三、Z缓冲区

  OpenGL存储它的所有深度信息于Z缓冲区(Z-buffer)中,也被称为深度缓冲区(Depth Buffer)。GLFW会自动为你生成这样一个缓冲区 (就如它有一个颜色缓冲区来存储输出图像的颜色)。深度存储在每个片段里面(作为片段的z值)当片段像输出它的颜色时,OpenGL会将它的深度值和z缓冲进行比较然后如果当前的片段在其它片段之后它将会被丢弃,然后重写。这个过程称为深度测试(Depth Testing)并且它是由OpenGL自动完成的。
  opengl把每个像素点的z轴存放在深度缓冲中,当我们画一个像素点的时候,如果这个点的在之前相同位置点的z之后,那么则丢弃这个点,这个过程就是所谓的深度测试。
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  使用glEnable(GL_DEPTH_TEST)启用深度测试。

四、源代码

"""
glfw_cube02.py
Author: dalong10
Description: Draw a Cube, learning OPENGL 
"""
import glutils    #Common OpenGL utilities,see glutils.py
import sys, random, math
import OpenGL
from OpenGL.GL import *
from OpenGL.GL.shaders import *
import numpy 
import numpy as np
import glfw

strVS = """
#version 330 core
layout(location = 0) in vec3 position;
layout (location = 1) in vec2 inTexcoord;
out vec2 outTexcoord;
uniform float theta;

void main(){
	mat4 rot=mat4( vec4(0.5+0.5*cos(theta),  0.5-0.5*cos(theta), -0.707106781*sin(theta), 0),
				   vec4(0.5-0.5*cos(theta),0.5+0.5*cos(theta), 0.707106781*sin(theta),0),
				vec4(0.707106781*sin(theta), -0.707106781*sin(theta),cos(theta), 0.0),
				vec4(0.0,         0.0,0.0, 1.0));
	gl_Position=rot *vec4(position.x, position.y, position.z, 1.0);
    outTexcoord = inTexcoord;
	}
"""

strFS = """
#version 330 core
out vec4 FragColor;
in vec2 outTexcoord;
uniform sampler2D texture1;
void main(){
    FragColor = texture(texture1, outTexcoord);
	}
"""

class FirstCube:
    def __init__(self, side):
        self.side = side

        # load shaders
        self.program = glutils.loadShaders(strVS, strFS)
        glUseProgram(self.program)
        # attributes
        self.vertIndex = glGetAttribLocation(self.program, b"position")
        self.texIndex = glGetAttribLocation(self.program, b"inTexcoord")
        
        s = side/2.0
        cube_vertices = [
            -s, -s, -s, 
             s, -s, -s,
             s, s, -s,
             s, s, -s,
             -s, s, -s,
             -s, -s, -s,
             
             -s, -s, s, 
             s, -s, s,
             s, s, s,
             s, s, s,
             -s, s, s,
             -s, -s, s,

             -s, s, s, 
             -s, s, -s,
             -s, -s, -s,
             -s, -s, -s,
             -s, -s, s,
             -s, s, s,

             s, s, s, 
             s, s, -s,
             s, -s, -s,
             s, -s, -s,
             s, -s, s,
             s, s, s,

             -s, -s, -s, 
             s, -s, -s,
             s, -s, s,
             s, -s, s,
             -s, -s, s,
             -s, -s, -s,

             -s, s, -s, 
             s, s,-s,
             s, s, s,
             s, s, s,
             -s, s, s,
             -s, s,-s
             ]
        # texture coords
        t=1.0
        quadT = [
            0,0, t,0, t,t, t,t, 0,t, 0,0, 
            0,0, t,0, t,t, t,t, 0,t, 0,0, 
            t,0, t,t, 0,t, 0,t, 0,0, t,0, 
            t,0, t,t, 0,t, 0,t, 0,0, t,0,  
            0,t, t,t, t,0, t,0, 0,0, 0,t, 
            0,t, t,t, t,0, t,0, 0,0, 0,t
            ]               
        # set up vertex array object (VAO)
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)
            
        # set up VBOs
        vertexData = numpy.array(cube_vertices, numpy.float32)
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData, GL_STATIC_DRAW)
        
        tcData = numpy.array(quadT, numpy.float32)
        self.tcBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.tcBuffer)
        glBufferData(GL_ARRAY_BUFFER, 4*len(tcData), tcData,GL_STATIC_DRAW)
        # enable arrays
        glEnableVertexAttribArray(self.vertIndex)
        glEnableVertexAttribArray(self.texIndex)
        # Position attribute
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glVertexAttribPointer(self.vertIndex, 3, GL_FLOAT, GL_FALSE, 0,None)
        
        # TexCoord attribute
        glBindBuffer(GL_ARRAY_BUFFER, self.tcBuffer)        
        glVertexAttribPointer(self.texIndex, 2, GL_FLOAT, GL_FALSE, 0,None)
        
        # unbind VAO
        glBindVertexArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, 0)    

    def render(self,texid):       
        self.texid = texid
        # enable texture
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self.texid)
        # use shader
        glUseProgram(self.program)
        theta = i*PI/180.0
        glUniform1f(glGetUniformLocation(self.program, "theta"), theta)
        # bind VAO
        glBindVertexArray(self.vao)
        glEnable(GL_DEPTH_TEST)
        # draw
        glDrawArrays(GL_TRIANGLES, 0, 36)
        # unbind VAO
        glBindVertexArray(0)

if __name__ == '__main__':
    import sys
    import glfw
    import OpenGL.GL as gl
    def on_key(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.set_window_should_close(window,1)

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

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(300, 300, "draw Cube ", None, None)
    if not window:
        glfw.terminate()
        sys.exit()

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

    # Install a key handler
    glfw.set_key_callback(window, on_key)
    PI = 3.14159265358979323846264
    texid = glutils.loadTexture("wall.png")
    # Loop until the user closes the window
    a=0
    firstCube0 = FirstCube(1.0)
    while not glfw.window_should_close(window):
        # Render here
        width, height = glfw.get_framebuffer_size(window)
        ratio = width / float(height)
        gl.glViewport(0, 0, width, height)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glClearColor(0.0,0.0,4.0,0.0)                
        i=a 
        glBindTexture(GL_TEXTURE_2D, texid)              
        firstCube0.render(texid)
        a=a+1
        if a>360:
            a=0                    
        # Swap front and back buffers
        glfw.swap_buffers(window)       
        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()

五、参考文献

1、learnopengl教程 https://learnopengl-cn.readthedocs.io/zh/latest/01%20Getting%20started/08%20Coordinate%20Systems/
2、大龙10简书 https://www.jianshu.com/p/8e8730071ddf

你可能感兴趣的:(OpenGL)