• Learn OpenGL 07 摄像机


    定义摄像机参数

    1. glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);//摄像机位置
    2. glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
    3. glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget);//摄像机方向,指向z轴正方向
    4. glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
    5. glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection));//摄像机右方向
    6. glm::vec3 cameraUp = glm::cross(cameraDirection, cameraRight);//上方向

    构建View矩阵

    这里可以参考Games101的MVP变换那一节

    视图变换要做的内容就是把相机放到正确的位置和角度上,但其实变换矩阵都是对模型进行变换,因为如果对模型进行视图变换以后,相机也就在正确的位置上了。

    这里就是相机移动到原点,g指向-z,t指向y等等。因为正着构建矩阵很困难,所以可以先求矩阵的逆变换。

    分别将X(1,0,0,0),Y,Z轴带入可以发现都符合

    也就是这样

    1. glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);//摄像机位置
    2. glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
    3. glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget);//摄像机方向,指向z轴正方向
    4. glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
    5. glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection));//摄像机右方向
    6. glm::vec3 cameraUp = glm::cross(cameraDirection, cameraRight);//上方向
    7. glm::mat4 view;
    8. view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);

    自由移动摄像机

    需要在按键检测函数里加上对应按键发生的时候对应的函数

    1. float cameraSpeed = 0.05f; // adjust accordingly
    2. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
    3. cameraPos += cameraSpeed * cameraFront;
    4. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
    5. cameraPos -= cameraSpeed * cameraFront;
    6. if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    7. cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
    8. if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
    9. cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;

    转换欧拉角

    对于我们的摄像机系统来说,我们只关心俯仰角和偏航角,所以我们不会讨论滚转角。给定一个俯仰角和偏航角,我们可以把它们转换为一个代表新的方向向量的3D向量。

    如果我们想象自己在xz平面上,看向y轴,我们可以基于第一个三角形计算来计算它的长度/y方向的强度(Strength)(我们往上或往下看多少)。从图中我们可以看到对于一个给定俯仰角的y值等于sin θ:

    direction.y = sin(glm::radians(pitch)); // 注意我们先把角度转为弧度
    

    这里我们只更新了y值,仔细观察x和z分量也被影响了。从三角形中我们可以看到它们的值等于:

    1. direction.x = cos(glm::radians(pitch));
    2. direction.z = cos(glm::radians(pitch));

    看看我们是否能够为偏航角找到需要的分量:

    就像俯仰角的三角形一样,我们可以看到x分量取决于cos(yaw)的值,z值同样取决于偏航角的正弦值。把这个加到前面的值中,会得到基于俯仰角和偏航角的方向向量:

    1. direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw)); // 译注:direction代表摄像机的前轴(Front),这个前轴是和本文第一幅图片的第二个摄像机的方向向量是相反的
    2. direction.y = sin(glm::radians(pitch));
    3. direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));

    这样我们就有了一个可以把俯仰角和偏航角转化为用来自由旋转视角的摄像机的3维方向向量了。

    鼠标输入与缩放

    分别设置鼠标移动和滚轮滑动的回调函数就可以了

    可以先设置这个函数隐藏光标

        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);//隐藏光标

    设置两个回调函数

    1. void mouse_callback(GLFWwindow* window, double xpos, double ypos)
    2. {
    3. if (firstMouse)
    4. {
    5. lastX = xpos;
    6. lastY = ypos;
    7. firstMouse = false;
    8. }
    9. float xoffset = xpos - lastX;
    10. float yoffset = lastY - ypos;
    11. lastX = xpos;
    12. lastY = ypos;
    13. float sensitivity = 0.03;
    14. xoffset *= sensitivity;
    15. yoffset *= sensitivity;
    16. yaw += xoffset;
    17. pitch += yoffset;
    18. if (pitch > 89.0f)
    19. pitch = 89.0f;
    20. if (pitch < -89.0f)
    21. pitch = -89.0f;
    22. glm::vec3 front;
    23. front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    24. front.y = sin(glm::radians(pitch));
    25. front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    26. cameraFront = glm::normalize(front);
    27. }
    28. void scroll_callbacks(GLFWwindow* window, double xoffset, double yoffset)
    29. {
    30. if (fov >= 1.0f && fov <= 45.0f)
    31. fov -= yoffset;
    32. if (fov <= 1.0f)
    33. fov = 1.0f;
    34. if (fov >= 45.0f)
    35. fov = 45.0f;
    36. }

    要到前面注册回调函数 

    1. glfwSetScrollCallback(window, scroll_callbacks);//注册回调函数
    2. glfwSetCursorPosCallback(window, mouse_callback);

    实现摄像机类

    因为每个场景都一定会需要一个摄像机,所以将摄像机类分离出来是个很有必要的事情,方便以后重复使用。直接创建一个摄像机类,它会自动生成一个camera.h文件和camera.cpp文件

    camera.h

    1. #pragma once
    2. #include <glm/glm.hpp>
    3. #include <glm/gtc/matrix_transform.hpp>
    4. #include <GLFW/glfw3.h>
    5. // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
    6. enum Camera_Movement {
    7. FORWARD,
    8. BACKWARD,
    9. LEFT,
    10. RIGHT
    11. };
    12. // Default camera values
    13. const float YAW = -90.0f;
    14. const float PITCH = 0.0f;
    15. const float SPEED = 2.5f;
    16. const float SENSITIVITY = 0.1f;
    17. const float ZOOM = 45.0f;
    18. class Camera
    19. {
    20. public:
    21. // camera Attributes
    22. glm::vec3 Position; //摄影机位置
    23. glm::vec3 Front; //Forward 摄影机的“方向”(一个和朝向相反的向量)
    24. glm::vec3 Up; //摄影机的上方向
    25. glm::vec3 Right;
    26. glm::vec3 WorldUp; //世界的上方向
    27. // euler Angles
    28. float Yaw;//偏航角
    29. float Pitch;//俯仰角
    30. // camera options
    31. float MovementSpeed;
    32. float MouseSensitivity;
    33. float Zoom;//FOV
    34. // constructor with vectors
    35. 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);
    36. Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch);
    37. glm::mat4 GetViewMatrix();
    38. void ProcessKeyboard(Camera_Movement direction, float deltaTime);//按键检测函数
    39. void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true);//鼠标移动检测函数
    40. void ProcessMouseScroll(float yoffset);//滚轮移动函数
    41. private:
    42. // calculates the front vector from the Camera's (updated) Euler Angles
    43. void updateCameraVectors();//通过欧拉角更新摄像机位置
    44. };

    Camera.cpp

    1. #include "Camera.h"
    2. Camera::Camera(glm::vec3 position, glm::vec3 up, float yaw, float pitch)
    3. : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    4. {
    5. Position = position;
    6. WorldUp = up;
    7. Yaw = yaw;
    8. Pitch = pitch;
    9. updateCameraVectors();
    10. }
    11. Camera::Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch)
    12. : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    13. {
    14. Position = glm::vec3(posX, posY, posZ);
    15. WorldUp = glm::vec3(upX, upY, upZ);
    16. Yaw = yaw;
    17. Pitch = pitch;
    18. updateCameraVectors();
    19. }
    20. // returns the view matrix calculated using Euler Angles and the LookAt Matrix
    21. glm::mat4 Camera::GetViewMatrix()
    22. {
    23. return glm::lookAt(Position, Position + Front, Up);
    24. }
    25. // 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)
    26. void Camera::ProcessKeyboard(Camera_Movement direction, float deltaTime)
    27. {
    28. float velocity = MovementSpeed * deltaTime;
    29. if (direction == FORWARD)
    30. Position += Front * velocity;
    31. if (direction == BACKWARD)
    32. Position -= Front * velocity;
    33. if (direction == LEFT)
    34. Position -= Right * velocity;
    35. if (direction == RIGHT)
    36. Position += Right * velocity;
    37. }
    38. // processes input received from a mouse input system. Expects the offset value in both the x and y direction.
    39. void Camera::ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch )
    40. {
    41. xoffset *= MouseSensitivity;
    42. yoffset *= MouseSensitivity;
    43. Yaw += xoffset;
    44. Pitch += yoffset;
    45. // make sure that when pitch is out of bounds, screen doesn't get flipped
    46. if (constrainPitch)
    47. {
    48. if (Pitch > 89.0f)
    49. Pitch = 89.0f;
    50. if (Pitch < -89.0f)
    51. Pitch = -89.0f;
    52. }
    53. //std::cout<<
    54. // update Front, Right and Up Vectors using the updated Euler angles
    55. updateCameraVectors();
    56. }
    57. // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
    58. void Camera::ProcessMouseScroll(float yoffset)
    59. {
    60. Zoom -= (float)yoffset;
    61. if (Zoom < 1.0f)
    62. Zoom = 1.0f;
    63. if (Zoom > 45.0f)
    64. Zoom = 45.0f;
    65. }
    66. void Camera::updateCameraVectors()
    67. {
    68. // calculate the new Front vector
    69. glm::vec3 front;
    70. front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    71. front.y = sin(glm::radians(Pitch));
    72. front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    73. Front = glm::normalize(front);
    74. // also re-calculate the Right and Up vector
    75. 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.
    76. Up = glm::normalize(glm::cross(Right, Front));
    77. }

    大功告成,注意在main函数里对应的变量也需要修改,然后main.cpp里原来声明的定义相机的变量就可以删掉了

    练习

    • 看看你是否能够修改摄像机类,使得其能够变成一个真正的FPS摄像机(也就是说不能够随意飞行);你只能够呆在xz平面上:参考解答

    • 只需要最后将y值永远设置在平面上就可以

    1. void Camera::ProcessKeyboard(Camera_Movement direction, float deltaTime)
    2. {
    3. float velocity = MovementSpeed * deltaTime;
    4. if (direction == FORWARD)
    5. Position += Front * velocity;
    6. if (direction == BACKWARD)
    7. Position -= Front * velocity;
    8. if (direction == LEFT)
    9. Position -= Right * velocity;
    10. if (direction == RIGHT)
    11. Position += Right * velocity;
    12. Position.y = 0.0f;
    13. }
    • 试着创建你自己的LookAt函数,其中你需要手动创建一个我们在一开始讨论的观察矩阵。用你的函数实现来替换GLM的LookAt函数,看看它是否还能一样地工作:​​​​​​​​​​​​​​参考解答

     

    根据这张图把矩阵构建出来即可

    注意GLM规定了矩阵的第一个参数是列,第二个参数是行

    旋转矩阵的第一行是右向量,第二行是上面的向量,第三行是方向向量。

    依次计算出向量搭建出矩阵就可以了

    1. // Custom implementation of the LookAt function
    2. glm::mat4 Camera::calculate_lookAt_matrix(glm::vec3 position, glm::vec3 target, glm::vec3 worldUp)
    3. {
    4. // 1. Position = known
    5. // 2. Calculate cameraDirection
    6. glm::vec3 zaxis = glm::normalize(position - target);
    7. // 3. Get positive right axis vector
    8. glm::vec3 xaxis = glm::normalize(glm::cross(glm::normalize(worldUp), zaxis));
    9. // 4. Calculate camera up vector
    10. glm::vec3 yaxis = glm::cross(zaxis, xaxis);
    11. // Create translation and rotation matrix
    12. // In glm we access elements as mat[col][row] due to column-major layout
    13. glm::mat4 translation = glm::mat4(1.0f); // Identity matrix by default
    14. translation[3][0] = -position.x; // Third column, first row
    15. translation[3][1] = -position.y;
    16. translation[3][2] = -position.z;
    17. glm::mat4 rotation = glm::mat4(1.0f);
    18. rotation[0][0] = xaxis.x; // First column, first row
    19. rotation[1][0] = xaxis.y;
    20. rotation[2][0] = xaxis.z;
    21. rotation[0][1] = yaxis.x; // First column, second row
    22. rotation[1][1] = yaxis.y;
    23. rotation[2][1] = yaxis.z;
    24. rotation[0][2] = zaxis.x; // First column, third row
    25. rotation[1][2] = zaxis.y;
    26. rotation[2][2] = zaxis.z;
    27. // Return lookAt matrix as combination of translation and rotation matrix
    28. return rotation * translation; // Remember to read from right to left (first translation then rotation)
    29. }

  • 相关阅读:
    实时数据同步工具的真正作用和对应应用场景
    【NSValue Objective-C语言】
    NumPy 差分、最小公倍数、最大公约数、三角函数详解
    mySQL—基础SQL语句
    #### 广告投放 ####
    【kali-权限提升】(4.2.6)社会工程学工具包(中):中间人攻击工具Ettercap
    pytest(13)-多线程、多进程执行用例
    原生js值之数据类型详解
    生成函数、多项式题单
    C/C++模板类模板与函数模板区别,以及用法详解
  • 原文地址:https://blog.csdn.net/Mr_Dongzheng/article/details/136608896