openGL系列文章目录
前言
如前所述,天空盒容易受到图像畸变和接缝的影响。接缝指两个纹理图像接触的地方(比 如沿着立方体的边缘)有时出现的可见线条。图9.8 展示了一个图像上半部分出现接缝的示 例,它是运行程序9.1 时出现的伪影。为了避免接缝,需要仔细构建立方体贴图图像,并分 配精确的纹理坐标
一、pandas是什么?
构建天空盒的另一种方法是使用OpenGL 纹理立方体贴图。OpenGL 立方体贴图比我们 在上一节中看到的简单方法稍微复杂一点。但是,使用OpenGL 立方体贴图有自己的优点, 例如减少接缝以及支持环境贴图。 OpenGL 纹理立方体贴图类似于稍后将要研究的3D 纹理,它们都使用3 个纹理坐标访 问——通常标记为(s, t, r)——而不是我们目前为止用到的两个。OpenGL 纹理立方体贴图 的另一个特性是,其中的图像以纹理图像的左上角(而不是通常的左下角)作为纹理坐标 (0, 0, 0),这通常是混乱产生的源头。 程序9.1 中展示的方法通过读入单个图像来为立方体贴图添加纹理,而程序9.2 中展示 的loadCubeMap()函数则读入6 个单独的立方体面图像文件。正如我们在第5 章中所学的, 有许多方法可以读取纹理图像,我们选择使用SOIL2 库。在这里,SOIL2 用于实例化和加 载OpenGL 立方体贴图也非常方便。我们先找到需要读入的文件, 然后调用 SOIL_load_OGL_cubemap(),其参数包括6 个图像文件和一些其他参数,类似于我们在第5 章中看到的SOIL_load_OGL_texture()。在使用OpenGL 立方体贴图时,无须垂直翻转纹理, OpenGL 会自动进行处理,注意,loadCubeMap()函数放在“Utils.cpp”文件中。 init()函数现在包含一个函数调用以启用GL_TEXTURE_CUBE_MAP_SEAMLESS,它告 诉OpenGL 尝试混合立方体相邻的边以减少或消除接缝。在display()中,立方体的顶点像以 前一样沿管线向下发送,但这次不需要发送立方体的纹理坐标。我们将会看到,OpenGL 纹 理立方体贴图通常使用立方体的顶点位置作为其纹理坐标。之后禁用深度测试并绘制立方 体。然后为场景的其余部分重新启用深度测试。 完成后的OpenGL 纹理立方体贴图使用了int 类型的标识符进行引用。与阴影贴图时一 样,通过将纹理包裹模式设置为“夹紧到边缘”,可以减少沿边框的伪影。在这种情况下, 它还可以帮助进一步缩小接缝。请注意,这里需要为3 个纹理坐标s、t 和r 都设置纹理包 裹模式。 在片段着色器中使用名为samplerCube 的特殊类型的采样器访问纹理。在纹理立方体贴 图中,从采样器返回的值是沿着方向向量(s, t, r)从原点“看到”的纹素。因此,我们通常可 以简单地使用传入的插值顶点位置作为纹理坐标。在顶点着色器中,我们将立方体顶点位 置分配到输出纹理坐标属性中,以便在它们到达片段着色器时进行插值。另外需要注意, 在顶点着色器中,我们将传入的视图矩阵转换为3×3,然后再转换回4×4。这个“技巧” 有效地移除了平移分量,同时保留了旋转(回想一下,平移值在转换矩阵的第四列中)。这 样,就将立方体贴图固定在了摄像机位置,同时仍允许合成相机“环顾四周”。
二、实现步骤
1.主程序
#include "glew/glew.h"
#include "glfw/glfw3.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "Torus.h"
#include "Utils.h"
#include "Sphere.h"
#include "camera.h"
#include "SOIL2/SOIL2.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
static const float pai = 3.1415926f;
float toRadins(float degrees) { return degrees * 2.f * pai / (float)360.f; }
static const int screenWidth = 1920;
static const int screenHeight = 1080;
GLuint renderingProgram = 0;
static const int numVAOs = 1;
static const int numVBOs = 6;
float cameraX = 0.f, cameraY = 0.f, cameraZ = 5.f;
float torLocX = 0.f, torLocY = 0.f, torLocZ = 0.f;
GLuint vao[numVAOs] = { 0 };
GLuint vbo[numVBOs] = { 0 };
GLuint brickTexture = 0, skyboxTexture = 0;
float rotAmt = 0.f;
GLuint mvLoc = 0, projLoc = 0;
int width = 0;
int height = 0;
float aspect = 0.f;
glm::mat4 mMat(1.f), vMat(1.f), pMat(1.f), mvMat(1.f);
Torus myTorus(0.5f, 0.2f, 48);
int numTorusVertices = 0, numTorusIndices = 0;
float sunLocX = 0.f, sunLocY = 0.f, sunLocZ = 0.f;
float earthLocX = 0.f, earthLocY = 0.f, earthLocZ = 0.f;
float moonLocX = 0.f, moonLocY = 0.f, moonLocZ = 0.f;
GLuint sunTextureId = 0, earthTextureId = 0, moonTextureId = 0;
Sphere sun = Sphere(48);
Sphere earth = Sphere(48);
Sphere moon = Sphere(48);
std::stack<glm::mat4> mvStack;
Camera camera(glm::vec3(0.f, 0.f, 5.f));
GLboolean keys[1024] = { GL_FALSE };
GLboolean b_firstMouse = GL_TRUE;
float deltaTime = 0.f;
float lastFrame = 0.f;
float lastLocX = 0.f;
float lastLocY = 0.f;
void do_movement()
{
if (keys[GLFW_KEY_W])
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (keys[GLFW_KEY_S])
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (keys[GLFW_KEY_A])
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (keys[GLFW_KEY_D])
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
}
void key_press_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if ((key == GLFW_KEY_ESCAPE) && (action == GLFW_PRESS))
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (action == GLFW_PRESS)
{
keys[key] = GLFW_TRUE;
}
else if (action == GLFW_RELEASE)
{
keys[key] = GLFW_FALSE;
}
}
void mouse_move_callback(GLFWwindow* window, double xPos, double yPos)
{
if (b_firstMouse)
{
lastLocX = xPos;
lastLocY = yPos;
b_firstMouse = GL_FALSE;
}
float xOffset = xPos - lastLocX;
float yOffset = lastLocY - yPos;
lastLocX = xPos;
lastLocY = yPos;
camera.ProcessMouseMovement(xOffset, yOffset);
}
void mouse_scroll_callback(GLFWwindow* window, double xPos, double yPos)
{
camera.ProcessMouseScroll(yPos);
}
void setupVertices(void)
{
float cubeVertexPosition[108] =
{
-1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f
};
float cubeTextureCoords[72] =
{
1.00f, 0.6666666f, 1.00f, 0.3333333f, 0.75f, 0.3333333f,
0.75f, 0.3333333f, 0.75f, 0.6666666f, 1.00f, 0.6666666f,
0.75f, 0.3333333f, 0.50f, 0.3333333f, 0.75f, 0.6666666f,
0.50f, 0.3333333f, 0.50f, 0.6666666f, 0.75f, 0.6666666f,
0.50f, 0.3333333f, 0.25f, 0.3333333f, 0.50f, 0.6666666f,
0.25f, 0.3333333f, 0.25f, 0.6666666f, 0.50f, 0.6666666f,
0.25f, 0.3333333f, 0.00f, 0.3333333f, 0.25f, 0.6666666f,
0.00f, 0.3333333f, 0.00f, 0.6666666f, 0.25f, 0.6666666f,
0.25f, 0.3333333f, 0.50f, 0.3333333f, 0.50f, 0.0000000f,
0.50f, 0.0000000f, 0.25f, 0.0000000f, 0.25f, 0.3333333f,
0.25f, 1.0000000f, 0.50f, 1.0000000f, 0.50f, 0.6666666f,
0.50f, 0.6666666f, 0.25f, 0.6666666f, 0.25f, 1.0000000f
};
vector<int> ind = sun.getIndices();
vector<glm::vec3> vert = sun.getVertices();
vector<glm::vec2> text = sun.getTexCoords();
vector<glm::vec3> norm = sun.getNormals();
vector<glm::vec3> tang = sun.getTangents();
vector<float> pValues;
vector<float> tValues;
vector<float> nValues;
int numIndices = sun.getNumIndices();
for (int i = 0; i < numIndices; i++)
{
pValues.push_back((vert[ind[i]]).x);
pValues.push_back((vert[ind[i]]).y);
pValues.push_back((vert[ind[i]]).z);
tValues.push_back((text[ind[i]]).s);
tValues.push_back((text[ind[i]]).t);
nValues.push_back((norm[ind[i]]).x);
nValues.push_back((norm[ind[i]]).y);
nValues.push_back((norm[ind[i]]).z);
}
glGenVertexArrays(numVAOs, vao);
glBindVertexArray(vao[0]);
glGenBuffers(numVBOs, vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertexPosition) * sizeof(float), cubeVertexPosition, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeTextureCoords) * sizeof(float), cubeTextureCoords, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
size_t sizeFloat = sizeof(float);
glBufferData(GL_ARRAY_BUFFER, pValues.size() * sizeof(float), &(pValues[0]), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo[3]);
glBufferData(GL_ARRAY_BUFFER, tValues.size() * sizeof(float), &(tValues[0]), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo[4]);
glBufferData(GL_ARRAY_BUFFER, nValues.size() * sizeof(float), &(nValues[0]), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[5]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ind.size() * sizeof(int), &ind[0], GL_STATIC_DRAW);
}
void init(GLFWwindow* window)
{
renderingProgram = Utils::createShaderProgram("vertShader.vert", "fragShader.frag");
glfwGetFramebufferSize(window, &width, &height);
aspect = (float)width / (float)height;
pMat = glm::perspective(toRadins(45.f), aspect, 0.01f, 1000.f);
setupVertices();
brickTexture = Utils::loadTexture("brick1.jpg");
skyboxTexture = Utils::loadTexture("alien.jpg");
sunTextureId = Utils::loadTexture("resource/shining.jpg");
earthTextureId = Utils::loadTexture("resource/earth.jpg");
moonTextureId = Utils::loadTexture("resource/moon.jpg");
torLocX = 0.f, torLocY = -0.75f, torLocZ = 0.f;
cameraX = 0.f, cameraY = 0.f, cameraZ = 5.f;
}
void display(GLFWwindow* window, double currentTime)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.f, 0.5f, 1.f, 1.f);
vMat = glm::translate(glm::mat4(1.f), glm::vec3(-cameraX, -cameraY, -cameraZ));
glUseProgram(renderingProgram);
deltaTime = currentTime - lastFrame;
lastFrame = currentTime;
do_movement();
pMat = glm::perspective(camera.Zoom, aspect, 0.01f, 1000.f);
mMat = glm::translate(glm::mat4(1.f), glm::vec3(cameraX, cameraY, 4.5f));
vMat = camera.GetViewMatrix();
mMat = glm::rotate(mMat, glm::radians(35.f), glm::vec3(1.f, 0.f, 0.f));
mvMat = vMat * mMat;
mvStack.push(vMat);
mvLoc = glGetUniformLocation(renderingProgram, "mv_matrix");
projLoc = glGetUniformLocation(renderingProgram, "proj_matrix");
glUniformMatrix4fv(mvLoc, 1, GL_FALSE, glm::value_ptr(mvMat));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(pMat));
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, skyboxTexture);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glDisable(GL_DEPTH_TEST);
glDrawArrays(GL_TRIANGLES, 0, 36);
glEnable(GL_DEPTH_TEST);
glUseProgram(renderingProgram);
mvLoc = glGetUniformLocation(renderingProgram, "mv_matrix");
projLoc = glGetUniformLocation(renderingProgram, "proj_matrix");
vMat = camera.GetViewMatrix();
mMat = glm::translate(glm::mat4(1.f), glm::vec3(sunLocX, sunLocY, sunLocZ));
mMat = glm::rotate(glm::mat4(1.f), (float)currentTime * 0.1f, glm::vec3(0.f, 1.f, 0.f));
pMat = glm::perspective(camera.Zoom, (GLfloat)screenWidth / (GLfloat)screenHeight, 0.01f, 1000.f);
mvMat = vMat * mMat;
mvStack.push(vMat);
glUniformMatrix4fv(mvLoc, 1, GL_FALSE, glm::value_ptr(mvMat));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(pMat));
mvStack.push(mvStack.top());
mvStack.top() *= glm::translate(glm::mat4(1.f), glm::vec3(0.f, 0.f, 0.f));
mvStack.push(mvStack.top());
mvStack.top() *= glm::rotate(glm::mat4(1.f), (float)glfwGetTime() * 0.4f, glm::vec3(0.f, 1.f, 0.f));
glUniformMatrix4fv(mvLoc, 1, GL_FALSE, glm::value_ptr(mvStack.top()));
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, sunTextureId);
glBindBuffer(GL_ARRAY_BUFFER, vbo[4]);
glDrawArrays(GL_TRIANGLES, 0, sun.getNumVertices());
mvStack.pop();
}
void window_size_callback(GLFWwindow* window, int newWidth, int newHeight)
{
aspect = (float)newWidth / (float)newHeight;
glViewport(0, 0, newWidth, newHeight);
pMat = glm::perspective(toRadins(45.f), aspect, 0.01f, 1000.f);
}
int main(int argc, char** argv)
{
int glfwState = glfwInit();
if (GLFW_FALSE == glfwState)
{
cout << "GLFW initialize failed,invoke glfwInit()......Error file:" << __FILE__ << "......Error line:" << __LINE__ << endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "sky box simple", nullptr, nullptr);
if (!window)
{
cout << "GLFW create window failed,invoke glfwCreateWindow()......Error file:" << __FILE__ << "......Error line:" << __LINE__ << endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetCursorPosCallback(window, mouse_move_callback);
glfwSetScrollCallback(window, mouse_scroll_callback);
glfwSetKeyCallback(window, key_press_callback);
int glewState = glewInit();
if (GLEW_OK != glewState)
{
cout << "GLEW initialize failed,invoke glewInit()......Error file:" << __FILE__ << "......Error line:" << __LINE__ << endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSwapInterval(1);
init(window);
while (!glfwWindowShouldClose(window))
{
display(window, glfwGetTime());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
return 0;
}
2.着色器
1.顶点着色器
#version 460 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 texCoord;
out vec2 tc;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
layout(binding = 0) uniform sampler2D samp;
void main(void)
{
tc = texCoord;
gl_Position = proj_matrix * mv_matrix * vec4(position, 1.f);
}
2.片元着色器
#version 460 core
in vec2 tc;
out vec4 fragColor;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
layout(binding = 0) uniform sampler2D samp;
void main(void)
{
fragColor = texture(samp, tc);
}
运行效果
源码下载
源码下载地址
|