文章目录
1.欧拉变换与万向锁
欧拉变换:将一个变换拆分成以三个基底(x,y,z)方向为轴的变换
万向锁:当变换过程中,两个方向基底的轴重合之后,使得在另一个方向上无法变换
目前变换矩阵无法处理该问题,但是可以尽量避免,该部分讲解参考视频——欧拉变换与万向锁
2.glm
glm(OpenGL Mathematics):OpenGL进行矩阵变换计算使用的一个库,具体下载与使用见——OpenGL.变换
3.变换矩阵
矩阵变换为左乘,变换顺序一般为缩放——旋转——平移
在使用glm时应注意设置变换矩阵transform的顺序,下图中设置顺序为平移、旋转、缩放(因为设置左乘矩阵是从左往右设置,我们要的变换顺序是缩放、旋转、平移,因此按下面代码顺序设置后,实际上的顶点变换可以看成 pos = translaterotatescale*pos)
4.练习
基本代码:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stb_image.h>
#include <iostream>
#include <filesystem>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
float mixValue = 0.2f;
//GLSL(OpenGL Shader Language)
const char* vertexShaderSource =
"#version 330 core\n" //OpenGL版本与模式设置
"layout (location = 0) in vec3 aPos;\n" //定义顶点属性的位置值
"layout (location = 1) in vec3 aColor;\n"//定义颜色属性的位置值
"layout (location = 2) in vec2 aTexCoord;\n"//
"out vec3 ourColor;\n"//要输出的颜色
"out vec2 TexCoord;\n"
"uniform mat4 transform;\n"
"void main()\n"
"{\n"
"gl_Position = transform * vec4(aPos, 1.0);\n" //进行顶点变换后设置位置
"ourColor = aColor;\n"//设置输出的颜色
"TexCoord = vec2(aTexCoord.x,aTexCoord.y);\n"
"}\0";
//Fragment GLSL
const char* fragmentShaderSource =
"#version 330 core\n"
"out vec4 FragColor;\n"//传出的颜色值
"in vec3 ourColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D texture1;\n"
"uniform sampler2D texture2;\n"//第二个纹理
"uniform float mixValue;\n"
"void main()\n"
"{\n"
//"FragColor = texture(texture1,TexCoord)*vec4(ourColor,1.0f);\n"//用从顶点着色器输入的值设置要输出的颜色值
" FragColor = mix(texture(texture1,TexCoord),texture(texture2,vec2(TexCoord.x,TexCoord.y)),mixValue);\n"
"}\0";
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL05", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1