OpenGL-07-01摄像机
当我们讨论摄像机/观察空间(Camera/View Space)的时候,是在讨论以摄像机的视角作为场景原点时场景中所有的顶点坐标:观察矩阵把所有的世界坐标变换为相对于摄像机位置与方向的观察坐标。要定义一个摄像机,我们需要它在世界空间中的位置、观察的方向、一个指向它右侧的向量以及一个指向它上方的向量
创建一个摄像机
我们想要创建一个摄像机,并通过WASD来进行水平移动,步骤如下
很简单,创建一个摄像机位置,方向向量,摄像机上轴,注意,这三个是全局变量
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
疑问:为什么方向向量是负的?
实际上,对于世界空间来说,他的z轴是由屏幕射向屏幕外的,因此我们视角的前进,就是z轴值的后退
创建一个观察矩阵,并通过lookAt
方法获得正确的变化矩阵
lookAt矩阵具体原理见:https://learnopengl-cn.github.io/01%20Getting%20started/09%20Camera/#_7
参数分别为,摄像机位置,摄像机观察目标,上向量(这里使用摄像机上轴)
glm::mat4 view;
//创建lookAt矩阵
//参数分别为,位置,目标,上向量
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
#pragma endregion
观察目标这里是通过摄像机位置加上方向向量获得的,这样摄像机的朝向就能通过方向向量来控制,这个后面会讲。
然后把三个矩阵都传给着色器就行了,和上一章一样
这样当然还不够,我们还没有设置键盘输入
函数如下:
这里解释几点:
deltaTime
是什么?
简单来说就是渲染帧时间,我们通过记录上一帧的时间,然后把现在的时间减去上一帧,我们就可以得到本帧的渲染时间
把渲染时间赋予给摄像机移动速度即可,我们控制摄像机移动是通过这个移动速度来控制的。为什么要讲移动速度乘上渲染帧呢?
原文解释如下:
目前我们的移动速度是个常量。理论上没什么问题,但是实际情况下根据处理器的能力不同,有些人可能会比其他人每秒绘制更多帧,也就是以更高的频率调用processInput函数。结果就是,根据配置的不同,有些人可能移动很快,而有些人会移动很慢。当你发布你的程序的时候,你必须确保它在所有硬件上移动速度都一样。
图形程序和游戏通常会跟踪一个时间差(Deltatime)变量,它储存了渲染上一帧所用的时间。我们把所有速度都去乘以deltaTime值。结果就是,如果我们的deltaTime很大,就意味着上一帧的渲染花费了更多时间,所以这一帧的速度需要变得更高来平衡渲染所花去的时间。使用这种方法时,无论你的电脑快还是慢,摄像机的速度都会相应平衡,这样每个用户的体验就都一样了。
void moveInput(GLFWwindow *window){
float cameraSpeed = 2.5f*deltaTime; // adjust accordingly
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
cameraPos += cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
cameraPos -= cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
}
把该函数用在循环体里面就OK了。
现在我们就可以通过WASD进行水平移动了!
自由运动
当然,仅仅是水平移动也太无趣了。我们还想要实现,通过鼠标能够控制摄像机朝向,更加自由的进行移动。
那么首先我们要了解一些知识,该如何进行视角移动?
视角移动
通过欧拉角我们知道,我们通常只需要两个轴的角度就可以完成我们所需要的全部旋转了,一般为:
俯仰角(pitch)和偏航角(Yaw)
接下来,就是该如何通过这两个角度转化为一个3D向量
计算方式如下
具体原理见:https://learnopengl-cn.github.io/01%20Getting%20started/09%20Camera/#_5
direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw)); // 译注:direction代表摄像机的前轴(Front),这个前轴是和本文第一幅图片的第二个摄像机的方向向量是相反的
direction.y = sin(glm::radians(pitch));
direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
鼠标输入
到这里,我们已经知道如何通过两个角度获得3D向量了。那么问题来了,我们如何获得这两个角度?
答案是通过鼠标移动获得:
偏航角和俯仰角是通过鼠标(或手柄)移动获得的,水平的移动影响偏航角,竖直的移动影响俯仰角。它的原理就是,储存上一帧鼠标的位置,在当前帧中我们当前计算鼠标位置与上一帧的位置相差多少。如果水平/竖直差别越大那么俯仰角或偏航角就改变越大,也就是摄像机需要移动更多的距离。
首先通过这个语句,我们可以隐藏鼠标
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
然后,我们还需要让GLFW监听鼠标移动事件,因此我们要用一个回调函数来实现,并且要用GLFW注册回调函数
注册:
glfwSetCursorPosCallback(window, mouse_callback);
函数如下:
具体输入两个值,分别为鼠标的2D坐标
初始情况,我们默认鼠标在屏幕正中间
鼠标的偏移量乘以了一个值sensitivity
,这个值用来控制鼠标灵敏度
这里有一点比较特殊,那就是,俯仰角为负时,是“抬头”,为正时,是“低头”。因为正的时候为顺时针,而负的时候才为逆时针,观察方向为从正轴看向负轴。
因此下面的yoffset
的相减是反的
我们还需要给摄像机添加一些限制,这样摄像机就不会发生奇怪的移动了(这样也会避免一些奇怪的问题)。对于俯仰角,要让用户不能看向高于89度的地方(在90度时视角会发生逆转,所以我们把89度作为极限),同样也不允许小于-89度。这样能够保证用户只能看到天空或脚下,但是不能超越这个限制。我们可以在值超过限制的时候将其改为极限值来实现:
每次我们都叠加两个角度,并转换为3D向量赋予给摄像机的方向向量,这样最终就能完成通过鼠标控制视角的移动了
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if(firstMouse)//第一次鼠标移动,赋予初始位置,默认屏幕中央
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
float sensitivity = 0.05;
xoffset *= sensitivity;
yoffset *= sensitivity;
yaw += xoffset;
pitch += yoffset;
if(pitch > 89.0f)
pitch = 89.0f;
if(pitch < -89.0f)
pitch = -89.0f;
glm::vec3 front;
front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
front.y = sin(glm::radians(pitch));
front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
cameraFront = glm::normalize(front);
}
这里有一些新的全局变量
bool firstMouse = true;
float yaw = -90.0f; // yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing to the right so we initially rotate a bit to the left.
float pitch = 0.0f;
float lastX = 800.0f / 2.0;
float lastY = 600.0 / 2.0;
视角缩放
鼠标滚轮回调函数
也是首先用GLFW注册函数即可
注意:注册只需要注册一次就行了,因此注册行为不要放到循环体里
glfwSetScrollCallback(window, scroll_callback);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
if(fov >= 1.0f && fov <= 45.0f)
fov -= yoffset;
if(fov <= 1.0f)
fov = 1.0f;
if(fov >= 45.0f)
fov = 45.0f;
}
这里有一个新的全局变量fov
,这个变量我们在上一章的练习题里测试过,这里不在多说了。
传给投影矩阵
projection = glm::perspective(glm::radians(fov), (float)(SCR_WIDTH)/ (SCR_HEIGHT), 0.1f, 100.0f);
到这里我们就可以自由的通过鼠标和键盘移动摄像机了!
摄像机类封装
对于一个摄像机类,它应该拥有什么属性?
- 摄像机位置
- 摄像机方向向量(摄像机朝向)
- 上轴
- 右轴
- 上向量
- 俯仰角
- 偏航角
- 摄像机移动速度
- 鼠标灵敏度
- 视野大小
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
// euler Angles
float Yaw;
float Pitch;
// camera options
float MovementSpeed;
float MouseSensitivity;
float Zoom;
首先,我们先写构造函数
// constructor with vectors
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH)
: Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
构造函数初始化,摄像机位置,上向量,两个角度初始值,摄像机方向向量,摄像机移动速度,摄像机旋转灵敏度,视野大小。其中
以下几个值,我们使用全局变量默认值,给予初始赋值
// Default camera values
const float YAW = -90.0f;
const float PITCH = 0.0f;
const float SPEED = 2.5f;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.0f;
构造函数重载,用具体的各分量值构造
Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = glm::vec3(posX, posY, posZ);
WorldUp = glm::vec3(upX, upY, upZ);
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
这里有一个私有成员函数,它用来更新摄像机类的各项属性
// calculates the front vector from the Camera's (updated) Euler Angles
void updateCameraVectors()
{
// calculate the new Front vector
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
// also re-calculate the Right and Up vector
Right = glm::normalize(glm::cross(Front, WorldUp)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
Up = glm::normalize(glm::cross(Right, Front));
}
更新方向向量,右轴,上轴
接下来是一些开放接口
获得观察矩阵
// returns the view matrix calculated using Euler Angles and the LookAt Matrix
glm::mat4 GetViewMatrix()
{
return glm::lookAt(Position, Position + Front, Up);
}
移动指令
// processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
}
鼠标控制朝向旋转
void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
// make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
// update Front, Right and Up Vectors using the updated Euler angles
updateCameraVectors();
}
缩放滚轮
// processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
void ProcessMouseScroll(float yoffset)
{
Zoom -= (float)yoffset;
if (Zoom < 1.0f)
Zoom = 1.0f;
if (Zoom > 45.0f)
Zoom = 45.0f;
}
注意每次输入指令后,都要记得更新属性
使用摄像机类后,C++程序完整代码如下
#pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <myShader.h>
#include <myCamera.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <iostream>
#pragma region 声明函数
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void moveInput(GLFWwindow *window);
void processInput(GLFWwindow *window);
float virtualInput(GLFWwindow *window,float value);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
#pragma endregion
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
float deltaTime = 0.0f; // 当前帧与上一帧的时间差
float lastFrame = 0.0f; // 上一帧的时间
bool firstMouse = true;
float lastX=0;
float lastY=0;
#pragma region 摄像机
Camera camera;
#pragma endregion
int main()
{
#pragma region glfw
// 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, "LearnOpenGL", 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;
}
#pragma endregion
#pragma region 定义顶点与着色器
// build and compile our shader zprogram
// ------------------------------------
Shader ourShader("path/to/shaders/shader.vs", "path/to/shaders/shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
glm::vec3 cubePositions[] = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3( 2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3( 1.3f, -2.0f, -2.5f),
glm::vec3( 1.5f, 2.0f, -2.5f),
glm::vec3( 1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
#pragma endregion
#pragma region 顶点数据输入
unsigned int VBO, VAO;//, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
// glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// // color attribute
// layout (location = 1) in vec3 aColor;
// out vec3 ourColor;
// ourColor = aColor;
// glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
// glEnableVertexAttribArray(1);
// texture1 coord attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
#pragma endregion
#pragma region 纹理
// load and create a texture1
// -------------------------
//创建纹理ID
unsigned int texture1;
//生成纹理对象,并存储在texture中
glGenTextures(1, &texture1);
//绑定当前的纹理
glBindTexture(GL_TEXTURE_2D,texture1); // all upcoming GL_TEXTURE_2D operations now have effect on this texture1 object
// 为当前绑定的纹理对象设置环绕、过滤方式
// set the texture1 wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // set texture1 wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// 为当前绑定的纹理对象设置环绕、过滤方式
// set texture1 filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture1 and generate mipmaps
int width, height, nrChannels;
// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
unsigned char *data = stbi_load("Texture/container.jpeg", &width, &height, &nrChannels, 0);
if (data)
{
//生成纹理
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
//这会为当前绑定的纹理自动生成所有需要的多级渐远纹理。
// glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture1" << std::endl;
}
//释放图像内存
stbi_image_free(data);
stbi_set_flip_vertically_on_load(true);
// load and create a texture1
// -------------------------
//创建纹理ID
unsigned int texture2;
//生成纹理对象,并存储在texture中
glGenTextures(1, &texture2);
//绑定当前的纹理
glBindTexture(GL_TEXTURE_2D,texture2); // all upcoming GL_TEXTURE_2D operations now have effect on this texture1 object
// 为当前绑定的纹理对象设置环绕、过滤方式
// set the texture1 wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); // set texture1 wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
// 为当前绑定的纹理对象设置环绕、过滤方式
// set texture1 filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture1 and generate mipmaps
// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
data = stbi_load("Texture/awesomeface.png", &width, &height, &nrChannels, 0);
if (data)
{
//生成纹理.注意awesomeface.png有透明度和alpha通道,所以一定要告诉OpenGL的数据类型是GL_RGBA
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
//这会为当前绑定的纹理自动生成所有需要的多级渐远纹理。
// glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture1" << std::endl;
}
//释放图像内存
stbi_image_free(data);
// tell opengl for each sampler to which texture1 unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
ourShader.use(); // don't forget to activate/use the shader before setting uniforms!
// either set it manually like so:
ourShader.setInt("texture1",0);
// or set it via the texture1 class
ourShader.setInt("texture2", 1);
ourShader.setFloat("mixScale",1);
#pragma endregion
#pragma region 设置windows回调函数
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
#pragma endregion
glEnable(GL_DEPTH_TEST);
float scale=1.0f;
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
#pragma region input
// input
// -----
processInput(window);
scale=virtualInput(window,scale);
moveInput(window);
#pragma endregion
#pragma region 渲染指令
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
stbi_set_flip_vertically_on_load(true);
// bind Texture
// bind textures on corresponding texture1 units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D,texture2);
// render container
ourShader.use();
glm::mat4 view;
//创建lookAt矩阵
//参数分别为,位置,目标,上向量
view = camera.GetViewMatrix();
// glm::mat4 view= glm::mat4(1.0f);
glm::mat4 projection= glm::mat4(1.0f);
// 注意,我们将矩阵向我们要进行移动场景的反方向移动。
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(glm::radians(camera.Zoom), (float)(SCR_WIDTH)/ (SCR_HEIGHT), 0.1f, 100.0f);
// ourShader.setMatrix4("model",model);
ourShader.setMatrix4("view",view);
ourShader.setMatrix4("projection",projection);
ourShader.setFloat("mixScale",scale);
//每次渲染前,清除之前的深度缓存
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(VAO);
for (unsigned int i = 0; i < 10; i++)
{
// calculate the model matrix for each object and pass it to shader before drawing
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
float angle = glfwGetTime()*50+20;
if(i==0||i%3==0){
model=glm::rotate(model,glm::radians(angle),glm::vec3(1.0f,0.3f,0.5f));
model=glm::translate(model,glm::vec3(2,0,0));
ourShader.setMatrix4("model",model);
}else{
model=glm::rotate(model,glm::radians(10.0f),glm::vec3(1.0f,0.3f,0.5f));
ourShader.setMatrix4("model",model);
}
glDrawArrays(GL_TRIANGLES, 0, 36);
}
#pragma endregion
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
#pragma region over
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glDeleteBuffers(1, &EBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
#pragma endregion
return 0;
}
#pragma region 函数实现
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if(firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset,yoffset);
}
Camera_Movement cameraMovement;
void moveInput(GLFWwindow *window){
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
cameraMovement=FORWARD;
camera.ProcessKeyboard(cameraMovement,deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
cameraMovement=BACKWARD;
camera.ProcessKeyboard(cameraMovement,deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
cameraMovement=LEFT;
camera.ProcessKeyboard(cameraMovement,deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
cameraMovement=RIGHT;
camera.ProcessKeyboard(cameraMovement,deltaTime);
}
}
float virtualInput(GLFWwindow *window,float value){
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS){
value=value+0.1f;
if(value>1) value=1;
}else if(glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS){
value=value-0.1f;
if(value<0) value=0;
}
return value;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
#pragma endregion