一、目的

1、使照相机围绕场景转动,看镜头里的立方体。

二、程序运行结果

python Wavefront打开obj python opengl obj_投影矩阵

三、坐标系统概述

  在流水线里面我们在将对象转换到屏幕空间之前会先将其转换到多个坐标系统(Coordinate System)。
1、局部坐标是对象相对于局部原点的坐标;也是对象开始的坐标。
2、将局部坐标转换为世界坐标,世界坐标是作为一个更大空间范围的坐标系统。这些坐标是相对于世界的原点的。
3、接下来我们将世界坐标转换为观察坐标,观察坐标是指以摄像机或观察者的角度观察的坐标。
4、在将坐标处理到观察空间之后,我们需要将其投影到裁剪坐标。裁剪坐标是处理-1.0到1.0范围内并判断哪些顶点将会出现在屏幕上。
5、最后,我们需要将裁剪坐标转换为屏幕坐标,我们将这一过程成为视口变换(Viewport Transform)。视口变换将位于-1.0到1.0范围的坐标转换到由glViewport函数所定义的坐标范围内。最后转换的坐标将会送到光栅器,由光栅器将其转化为片段。
  我们为上述的每一个步骤都创建了一个转换矩阵:模型矩阵、观察矩阵和投影矩阵。一个顶点的坐标与这三个矩阵连乘被转换到裁剪坐标;最后的顶点应该被赋予顶点着色器中的gl_Position且OpenGL将会自动进行透视划分和裁剪。

四、局部空间(Local Space,或者称为物体空间(Object Space))

  局部空间(Local Space)是指对象所在的坐标空间

五、世界空间(World Space)

  物体变换到的最终空间就是世界坐标系,并且你会想让这些物体分散开来摆放(从而显得更真实)。对象的坐标将会从局部坐标转换到世界坐标;该转换是由模型矩阵(Model Matrix)实现的。

六、观察空间(View Space,或者称为视觉空间(Eye Space))

  观察空间(View Space)经常被人们称之OpenGL的摄像机(Camera)(所以有时也称为摄像机空间(Camera Space)或视觉空间(Eye Space))。观察空间就是将对象的世界空间的坐标转换为观察者视野前面的坐标。因此观察空间就是从摄像机的角度观察到的空间。而这通常是由一系列的平移和旋转的组合来平移和旋转场景从而使得特定的对象被转换到摄像机前面。这些组合在一起的转换通常存储在一个观察矩阵(View Matrix)里,用来将世界坐标转换到观察空间。

七、裁剪空间(Clip Space)

  在一个顶点着色器运行的最后,OpenGL期望所有的坐标都能落在一个给定的范围内,且任何在这个范围之外的点都应该被裁剪掉(Clipped)。被裁剪掉的坐标就被忽略了,所以剩下的坐标就将变为屏幕上可见的片段。这也就是裁剪空间(Clip Space)名字的由来。
  因为将所有可见的坐标都放置在-1.0到1.0的范围内不是很直观,所以我们会指定自己的坐标集(Coordinate Set)并将它转换回标准化设备坐标系,就像OpenGL期望它做的那样。
  为了将顶点坐标从观察空间转换到裁剪空间,我们需要定义一个投影矩阵(Projection Matrix),它指定了坐标的范围,所有在在范围外的坐标都不会被绘制出来并且会被裁剪。
  由投影矩阵创建的观察区域(Viewing Box)被称为平截头体(Frustum),且每个出现在平截头体范围内的坐标都会最终出现在用户的屏幕上。将一定范围内的坐标转化到标准化设备坐标系的过程(而且它很容易被映射到2D观察空间坐标)被称之为投影(Projection),因为使用投影矩阵能将3维坐标投影(Project)到很容易映射的2D标准化设备坐标系中。
  投影矩阵将观察坐标转换为裁剪坐标的过程采用两种不同的方式,每种方式分别定义自己的平截头体。我们可以创建一个正射投影矩阵(Orthographic Projection Matrix)或一个透视投影矩阵(Perspective Projection Matrix)。

八、屏幕空间(Screen Space)

  为了将坐标从一个坐标系转换到另一个坐标系,我们需要用到几个转换矩阵,最重要的几个分别是模型(Model)、视图(View)、投影(Projection)三个矩阵。首先,顶点坐标开始于局部空间(Local Space),称为局部坐标(Local Coordinate),然后经过世界坐标(World Coordinate),观察坐标(View Coordinate),裁剪坐标(Clip Coordinate),并最后以屏幕坐标(Screen Coordinate)结束。

九、摄像机(Camera)

  观察矩阵把所有的世界坐标变换到观察坐标,这些新坐标是相对于摄像机的位置和方向的。定义一个摄像机,我们需要一个摄像机在世界空间中的位置、观察的方向、一个指向它的右测的向量以及一个指向它上方的向量。参见参考文献1。

十、源代码

"""
glfw_cube04.py
Author: dalong10
Description: Draw 4 Cube, learning OPENGL 
"""
import glutils    #Common OpenGL utilities,see glutils.py
import sys, random, math
import OpenGL
from  import *
from .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 mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform float a;
uniform float b;
uniform float c;
uniform float scale;
uniform float theta;

void main(){
	mat4 rot1=mat4(vec4(1.0, 0.0,0.0,0),
				vec4(0.0, 1.0,0.0,0),
				vec4(0.0,0.0,1.0,0.0),
				vec4(a,b,c,1.0));
	mat4 rot2=mat4(vec4(scale, 0.0,0.0,0.0),
					vec4(0.0, scale,0.0,0.0),
					vec4(0.0,0.0,scale,0.0),
					vec4(0.0,0.0,0.0,1.0));
	mat4 rot3=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=uPMatrix * uMVMatrix * rot2 *rot1 *rot3 * 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,pMatrix,mvMatrix,texid,a,b,c,scale,r):       
        self.texid = texid
        # enable texture
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self.texid)
        # use shader
        # set proj matrix
        glUniformMatrix4fv(glGetUniformLocation(self.program, 'uPMatrix'), 
                          1, GL_FALSE, pMatrix)       
        # set modelview matrix
        glUniformMatrix4fv(glGetUniformLocation(self.program, 'uMVMatrix'), 
                          1, GL_FALSE, mvMatrix)
        glUseProgram(self.program)
        glUniform1f(glGetUniformLocation(self.program, "a"), a)
        glUniform1f(glGetUniformLocation(self.program, "b"), b)
        glUniform1f(glGetUniformLocation(self.program, "c"), c)
        glUniform1f(glGetUniformLocation(self.program, "scale"), scale)
        theta = r*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  as gl
    camera = glutils.Camera([0.0, 0.0, 5.0],
                             [0.0, 0.0, 0.0],
                             [0.0, 1.0, 0.0])
    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.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(-ratio, ratio, -1, 1, 1, -1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glClearColor(0.0,0.0,4.0,0.0)                
        i=a 
        camera.eye=[5*math.sin(a*PI/180.0),0,5*math.cos(a*PI/180.0)]
        pMatrix = glutils.perspective(100.0, 1, 0.1, 100.0)
        # modelview matrix
        mvMatrix = glutils.lookAt(camera.eye, camera.center, camera.up)
        glBindTexture(GL_TEXTURE_2D, texid)              
        firstCube0.render(pMatrix, mvMatrix,texid,0.0,1,0,0.4,i)
        firstCube0.render(pMatrix, mvMatrix,texid,1.0,0,0.4,0.5,i)
        firstCube0.render(pMatrix, mvMatrix,texid,0.0,-1,-0.5,0.3,i)
        firstCube0.render(pMatrix, mvMatrix,texid,-1.0,0,0.2,0.2,i)
        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()