Python之OpenGL笔记(24):正方体多纹理贴图

38 篇文章 64 订阅

一、目的

1、画一个旋转的立方体,对正方体的六个面进行多纹理贴图;

二、程序运行结果

cube2.gif

三、片元着色器

   顶点着色器是做出3D图像的轮廓框架(毛坯,进行空间与空间变化等与空间相关操作)
   片元 着色器让它变得好看一些,即上色(装修,进行颜色与纹理等操作)
#四、正方体多纹理贴图
   把图片映射到正方体的6个面上,有两种方法:

   1. 加载一个纹理图片,这个纹理图片包含6个面的信息,如图片2*3分割,每个块对应一个面。

   2. 加载六个纹理图片,图片独立,每张图片对应一个面。

   下面的例子采用第二种方法,使用多个纹理图片(不是多重纹理,多重纹理指纹理叠加,同一个面叠加多个纹理),绘制的时候,通过切换纹理图片的绑定来绘制不同的面,顶点坐标容易设计,正立方体的各个面都是规则的形状,纹理图片的4个顶点分别对应4个立方体表面顶点坐标即可。

   注意:这种情况下,同一个顶点坐标,绘制不同的面时,对应的顶点坐标是不一样的,如绘制顶面和前侧面,有两个顶点坐标是一致的,但绘制这两个面对应的纹理坐标却不一致,大家可以看例子中的点{-0.5f, -0.5f, 0.5f },绘制两个相邻的侧面,一个纹理坐标是{1.0f, 0.0f}, 一个是{0.0f, 0.0f},这种情况下使用glDrawElements的方式就要注意了,需处理好同一个顶点对应不同纹理坐标的情况。

   本例子需要6张png图片,名称分别为wall0.png~wall5.png。

四、源代码

"""
程序名称:GL_DrawCube2.py
编程: dalong10
功能: 画一个立方体,给6个面加图像纹理,绕轴(0,0.7071,0.7071)旋转 
"""

import myGL_Funcs       #通用 OpenGL 程序,见 myGL_Funcs.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 = myGL_Funcs.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,k):       
        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, k*6, 6)
        # 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=[]
    for k in range(6):
        texture0= myGL_Funcs.loadTexture("wall"+str(k)+".png")
        texid.append(texture0)
        
    # 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 
        for k in range(6):
            glBindTexture(GL_TEXTURE_2D, texid[k])              
            firstCube0.render(texid[k],k)

        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、大龙10的简书:https://www.jianshu.com/p/49dec482a291
2、他山随悟的博客:https://blog.csdn.net/t3swing/article/details/78734159

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值