OpenGL:光照、模型视图投影变换
数学基础
OpenGL Normal Vector Transformation
程序
太阳系,为简化内容,所以使用正方体代替球体,模拟太阳系中的太阳,地球和月亮。主要目的是展示OpenGL中用到的几个坐标系变换以及光照处理。
库配置
程序图示
代码
#include <iostream>
#include <cmath>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// GLM Mathematics
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Other includes
#include "shaderwrapper.h"
// Function prototypes
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
static void init();
static void initBuffer();
// Window dimensions
static const GLuint WIDTH = 800, HEIGHT = 600;
static GLFWwindow* window;
static GLuint VBO, VAO;
// The MAIN function, from here we start the application and run the game loop
int main()
{
init();
initBuffer();
//light position in world space
glm::vec3 lightPos(8.0f,8.0f,8.0f);
//eye position in world space
glm::vec3 eyePos(-12.0f, 12.0f, 12.0f);
//local positions
glm::vec3 cubePositions[] = {
glm::vec3(8.0f,0.0f,0.0f),
glm::vec3(3.0f,0.0f,0.0f)
};
//sun
GLfloat Sun_angle = 0.0f;
GLfloat Sun_angle_step = 1.0f;
glm::vec3 Sun_color(1.0f,0.0f,0.0f);
//earth
GLfloat Earth_self_angle = 0.0f;
GLfloat Earth_angle_step = 1.0f;
GLfloat Earth_sun_angle = 0.0f;
GLfloat Earth_sun_step = 2.0f;
glm::vec3 Earth_color(0.0f, 1.0f, 0.0f);
//moon
GLfloat Moon_self_angle = 0.0f;
GLfloat Moon_angle_step = 2.0f;
GLfloat Moon_earth_angle = 0.0f;
GLfloat Moon_earth_step = 3.0f;
glm::vec3 Moon_color(1.0f, 1.0f, 1.0f);
// Build and compile our shader program
Shader ourShader("shaders/mvp_test.vs", "shaders/mvp_test.frag");
//get locations of uniform variables
GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
GLint lightPosLoc = glGetUniformLocation(ourShader.Program, "lightPos");
GLint colorLoc = glGetUniformLocation(ourShader.Program, "objectColor");
GLint viewPosLoc = glGetUniformLocation(ourShader.Program, "viewPos");
// Camera/View transformation
glm::mat4 view;
view = glm::lookAt(eyePos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
// Projection
glm::mat4 projection;
projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
// Activate shader
ourShader.Use();
// Pass the matrices to the shader
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z);