当前位置:网站首页>Chapter 7: drawing rotating cubes
Chapter 7: drawing rotating cubes
2022-07-28 22:06:00 【Code Knight】
Catalog
5、 Engineering document structure
1、Z- buffer


// Open depth test
glEnable(GL_DEPTH_TEST);2、GLM Library function

3、PVM matrix

4、PVM The use of matrices
We need to introduce GLM Function library header file :
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>Set up vew Relevant parameters of the matrix :
// Camera parameters
glm::vec3 camera_position = glm::vec3(0.0f, 0.0f, 3.0f); // Camera position
glm::vec3 camera_front = glm::vec3(0.0f, 0.0f, -1.0f); // Camera direction
glm::vec3 camera_up = glm::vec3(0.0f, 1.0f, 0.0f); // Vector on camera Set up project Matrix vision fov:
float fov = 45.0f;
// Transform Coordinate transformation matrix
glm::mat4 model(1);//model matrix , Transform local coordinates to world coordinates
model = glm::translate(model, glm::vec3(0.0,0.0,0.0));
model = glm::rotate(model, (float)glfwGetTime(), glm::vec3(0.5f, 1.0f, 0.0f));
model = glm::scale(model, glm::vec3(1.0f,1.0f,1.0f)); 
glm::mat4 view(1);//view matrix , Transform the world coordinates to the observation coordinate system
view = glm::lookAt(camera_position, camera_position + camera_front, camera_up);

glm::mat4 projection(1);//projection matrix , Projection matrix
projection = glm::perspective(glm::radians(fov), (float)screen_width / screen_height, 0.1f, 100.0f);

int model_location = glGetUniformLocation(shader.ID, "model"); // Get the position of a parameter in the shader

glUniformMatrix4fv(model_location, 1, GL_FALSE, glm::value_ptr(model));// Write parameter values 
gl_Position=projection*view*model*vec4(aPos,1.0);5、 Engineering document structure

shader.h
#ifndef __SHADER_H__
#define __SHADER_H__
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "string"
class Shader
{
public:
unsigned int ID;
Shader(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path);
~Shader();
void Use();
void SetBool(const std::string &name, bool value) const;
void SetInt(const std::string &name, int value) const;
void SetFloat(const std::string &name, float value) const;
void SetVec2(const std::string &name, const glm::vec2 &value) const;
void SetVec2(const std::string &name, float x, float y) const;
void SetVec3(const std::string &name, const glm::vec3 &value) const;
void SetVec3(const std::string &name, float x, float y, float z) const;
void SetVec4(const std::string &name, const glm::vec4 &value) const;
void SetVec4(const std::string &name, float x, float y, float z, float w) const;
void SetMat2(const std::string &name, const glm::mat2 &value) const;
void SetMat3(const std::string &name, const glm::mat3 &value) const;
void SetMat4(const std::string &name, const glm::mat4 &value) const;
private:
int GetShaderFromFile(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path,
std::string *vertex_shader_code, std::string *fragment_shader_code);
int LinkShader(const char* vertex_shader_code, const char* fragment_shader_code);
int GetUniform(const std::string &name) const;
void CheckCompileErrors(GLuint shader, std::string type);
};
#endif // !__SHADER_H__
#ifndef __SHADER_H__
#define __SHADER_H__
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "string"
class Shader
{
public:
unsigned int ID;
Shader(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path);
~Shader();
void Use();
void SetBool(const std::string &name, bool value) const;
void SetInt(const std::string &name, int value) const;
void SetFloat(const std::string &name, float value) const;
void SetVec2(const std::string &name, const glm::vec2 &value) const;
void SetVec2(const std::string &name, float x, float y) const;
void SetVec3(const std::string &name, const glm::vec3 &value) const;
void SetVec3(const std::string &name, float x, float y, float z) const;
void SetVec4(const std::string &name, const glm::vec4 &value) const;
void SetVec4(const std::string &name, float x, float y, float z, float w) const;
void SetMat2(const std::string &name, const glm::mat2 &value) const;
void SetMat3(const std::string &name, const glm::mat3 &value) const;
void SetMat4(const std::string &name, const glm::mat4 &value) const;
private:
int GetShaderFromFile(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path,
std::string *vertex_shader_code, std::string *fragment_shader_code);
int LinkShader(const char* vertex_shader_code, const char* fragment_shader_code);
int GetUniform(const std::string &name) const;
void CheckCompileErrors(GLuint shader, std::string type);
};
#endif // !__SHADER_H__
#ifndef __SHADER_H__
#define __SHADER_H__
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "string"
class Shader
{
public:
unsigned int ID;
Shader(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path);
~Shader();
void Use();
void SetBool(const std::string &name, bool value) const;
void SetInt(const std::string &name, int value) const;
void SetFloat(const std::string &name, float value) const;
void SetVec2(const std::string &name, const glm::vec2 &value) const;
void SetVec2(const std::string &name, float x, float y) const;
void SetVec3(const std::string &name, const glm::vec3 &value) const;
void SetVec3(const std::string &name, float x, float y, float z) const;
void SetVec4(const std::string &name, const glm::vec4 &value) const;
void SetVec4(const std::string &name, float x, float y, float z, float w) const;
void SetMat2(const std::string &name, const glm::mat2 &value) const;
void SetMat3(const std::string &name, const glm::mat3 &value) const;
void SetMat4(const std::string &name, const glm::mat4 &value) const;
private:
int GetShaderFromFile(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path,
std::string *vertex_shader_code, std::string *fragment_shader_code);
int LinkShader(const char* vertex_shader_code, const char* fragment_shader_code);
int GetUniform(const std::string &name) const;
void CheckCompileErrors(GLuint shader, std::string type);
};
#endif // !__SHADER_H__
shader.cpp
#include "Shader.h"
#include "fstream"
#include "sstream"
#include "iostream"
Shader::Shader(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path)
{
std::string vertex_shader_code;
std::string fragment_shader_code;
if (GetShaderFromFile(vertex_shader_path, fragment_shader_path, &vertex_shader_code, &fragment_shader_code))
{
return;
}
if (LinkShader(vertex_shader_code.c_str(), fragment_shader_code.c_str()))
{
return;
}
}
Shader::~Shader()
{
}
void Shader::Use()
{
glUseProgram(ID);
}
void Shader::SetBool(const std::string &name, bool value) const
{
SetInt(name, (int)value);
}
void Shader::SetInt(const std::string &name, int value) const
{
glUniform1i(GetUniform(name), value);
}
void Shader::SetFloat(const std::string &name, float value) const
{
glUniform1f(GetUniform(name), value);
}
void Shader::SetVec2(const std::string &name, float x, float y) const
{
glUniform2f(GetUniform(name), x, y);
}
void Shader::SetVec2(const std::string &name, const glm::vec2 &value) const
{
SetVec2(name, value.x, value.y);
}
void Shader::SetVec3(const std::string &name, float x, float y, float z) const
{
glUniform3f(GetUniform(name), x, y, z);
}
void Shader::SetVec3(const std::string &name, const glm::vec3 &value) const
{
SetVec3(name, value.x, value.y, value.z);
}
void Shader::SetVec4(const std::string &name, float x, float y, float z, float w) const
{
glUniform4f(GetUniform(name), x, y, z, w);
}
void Shader::SetVec4(const std::string &name, const glm::vec4 &value) const
{
SetVec4(name, value.x, value.y, value.z, value.w);
}
void Shader::SetMat2(const std::string &name, const glm::mat2 &value) const
{
glUniformMatrix2fv(GetUniform(name), 1, GL_FALSE, &value[0][0]);
}
void Shader::SetMat3(const std::string &name, const glm::mat3 &value) const
{
glUniformMatrix3fv(GetUniform(name), 1, GL_FALSE, &value[0][0]);
}
void Shader::SetMat4(const std::string &name, const glm::mat4 &value) const
{
glUniformMatrix4fv(GetUniform(name), 1, GL_FALSE, &value[0][0]);
}
int Shader::GetShaderFromFile(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path, std::string *vertex_shader_code, std::string *fragment_shader_code)
{
std::ifstream vertex_shader_file;
std::ifstream fragment_shader_file;
vertex_shader_file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
fragment_shader_file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
try
{
vertex_shader_file.open(vertex_shader_path);
fragment_shader_file.open(fragment_shader_path);
std::stringstream vertex_shader_stream, fragment_shader_stream;
vertex_shader_stream << vertex_shader_file.rdbuf();
fragment_shader_stream << fragment_shader_file.rdbuf();
vertex_shader_file.close();
fragment_shader_file.close();
*vertex_shader_code = vertex_shader_stream.str();
*fragment_shader_code = fragment_shader_stream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "Load Shader File Error!" << std::endl;
return -1;
}
return 0;
}
int Shader::LinkShader(const char* vertex_shader_code, const char* fragment_shader_code)
{
int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_code, NULL);
glCompileShader(vertex_shader);
CheckCompileErrors(vertex_shader, "VERTEX");
int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_code, NULL);
glCompileShader(fragment_shader);
CheckCompileErrors(fragment_shader, "FRAGMENT");
this->ID = glCreateProgram();
glAttachShader(ID, vertex_shader);
glAttachShader(ID, fragment_shader);
glLinkProgram(ID);
CheckCompileErrors(ID, "PROGRAM");
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return 0;
}
int Shader::GetUniform(const std::string &name) const
{
int position = glGetUniformLocation(ID, name.c_str());
if (position == -1)
{
std::cout << "uniform " << name << " set failed!" << std::endl;
}
return position;
}
void Shader::CheckCompileErrors(GLuint shader, std::string type)
{
GLint success;
GLchar infoLog[512];
if (type == "PROGRAM")
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 512, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR!\n" << infoLog << std::endl;
}
}
else
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::" << type << "::COMPILATION_FAILED\n" << infoLog << std::endl;
}
}
}main.cpp
// Overall process
//1. Initialize and create window
//2. Load cube vertices VAOVBO And shader and turn on depth test
//3. Enter the main cycle to clear the buffer
//4. Use cube shaders , Construct and pass in pvm matrix , draw
//5. The loop ends , Release VAOVBO
#include <iostream>
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "shader.h"
const float vertices[] = { // Cube array
-0.5f, -0.5f, -0.5f, 1.0f,0.0f,0.0f,
0.5f, -0.5f, -0.5f, 1.0f,0.0f,0.0f,
0.5f, 0.5f, -0.5f, 1.0f,0.0f,0.0f,
0.5f, 0.5f,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0.5f, 0.5f, 0.5f, 0.0f,0.0f,0.5f,
-0.5f, 0.5f, 0.5f, 0.0f,0.0f,0.5f,
-0.5f, 0.5f, -0.5f, 0.0f,0.0f,0.5f
};
float screen_width = 1280.0f; // Window width
float screen_height = 720.0f; // Window height
// Camera parameters
glm::vec3 camera_position = glm::vec3(0.0f, 0.0f, 3.0f); // Camera position
glm::vec3 camera_front = glm::vec3(0.0f, 0.0f, -1.0f); // Camera direction
glm::vec3 camera_up = glm::vec3(0.0f, 1.0f, 0.0f); // Vector on camera
// View
float fov = 45.0f;
int main() {
// initialization GLFW
glfwInit(); // initialization GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // OpenGL Version is 3.3, The primary and secondary version numbers are set to 3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Use core mode ( There is no need for backward compatibility )
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // If you are using Mac OS X System , Add this line
glfwWindowHint(GLFW_RESIZABLE, FALSE); // Do not change the window size
// create a window ( wide 、 high 、 Window name )
auto window = glfwCreateWindow(screen_width, screen_height, "Cube", nullptr, nullptr);
if (window == nullptr) { // If the window creation fails , Output Failed to Create OpenGL Context
std::cout << "Failed to Create OpenGL Context" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window); // Set the context of the window to the main context of the current thread
// initialization GLAD, load OpenGL Function pointer address function
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// Specify the current viewport size ( The first two parameters are the lower left corner , The last two parameters are the rendering window width 、 high )
glViewport(0, 0, screen_width, screen_height);
Shader shader("res/shader/task-cube.vs", "res/shader/task-cube.fs");// Load shaders
// Generate and bind VAO and VBO
GLuint vertex_array_object; // == VAO
glGenVertexArrays(1, &vertex_array_object);
glBindVertexArray(vertex_array_object);
GLuint vertex_buffer_object; // == VBO
glGenBuffers(1, &vertex_buffer_object);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_object);
// Bind vertex data to the current default buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Set vertex property pointer
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glEnable(GL_DEPTH_TEST);
// Render loop Main circulation
while (!glfwWindowShouldClose(window)) {
// Enter the main loop , Clear color buffer depth buffer
glClearColor(0.0f, 0.34f, 0.57f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clean up color buffer and depth buffer
shader.Use();
// Transform Coordinate transformation matrix
glm::mat4 model(1);//model matrix , Transform local coordinates to world coordinates
model = glm::translate(model, glm::vec3(0.0,0.0,0.0));
model = glm::rotate(model, (float)glfwGetTime(), glm::vec3(0.5f, 1.0f, 0.0f));
model = glm::scale(model, glm::vec3(1.0f,1.0f,1.0f));
glm::mat4 view(1);//view matrix , Transform the world coordinates to the observation coordinate system
view = glm::lookAt(camera_position, camera_position + camera_front, camera_up);
glm::mat4 projection(1);//projection matrix , Projection matrix
projection = glm::perspective(glm::radians(fov), (float)screen_width / screen_height, 0.1f, 100.0f);
// Pass parameters into the shader
int model_location = glGetUniformLocation(shader.ID, "model"); // Get the position of a parameter in the shader
glUniformMatrix4fv(model_location, 1, GL_FALSE, glm::value_ptr(model));// Write parameter values
int view_location = glGetUniformLocation(shader.ID, "view");
glUniformMatrix4fv(view_location, 1, GL_FALSE, glm::value_ptr(view));
int projection_location = glGetUniformLocation(shader.ID, "projection");
glUniformMatrix4fv(projection_location, 1, GL_FALSE, glm::value_ptr(projection));
// draw
glBindVertexArray(vertex_array_object);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
// Release VAOVBO
glDeleteVertexArrays(1, &vertex_array_object);
glDeleteBuffers(1, &vertex_buffer_object);
// Clean up all resources and exit the program correctly
glfwTerminate();
return 0;
}Output results :

边栏推荐
- Oracle built-in functions
- Chinese patent keyword extraction based on LSTM and logistic regression
- Leetcode · 581. shortest unordered continuous subarray · double pointer
- Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 2)
- 基于属性词补全的武器装备属性抽取研究
- DHCP和PPPoE协议以及抓包分析
- How to search images efficiently and accurately? Look at the lightweight visual pre training model
- Nano gold coupled antibody / protein Kit (20nm, 1mg/100 μ g/500 μ G coupling amount) preparation
- B+ tree height calculation of MySQL
- Which brand is the best and most cost-effective open headset
猜你喜欢

微信小程序开发公司你懂得选择吗?

腾讯云数据库负责人借了一亿元炒股?知情人士:金额不实

使用Mock技术帮助提升测试效率的小tips,你知道几个?
![[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势](/img/aa/a169cdd8cc6cdfda6d2777511b4dd2.png)
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势

Introduction to wechat applet development, develop your own applet

【NLP】生成词云

JS DOM编程之平平无奇小练习

Information fusion method and application of expert opinion and trust in large group emergency decision-making based on complex network

Oracle database objects
![[machine learning] naive Bayesian classification of text -- Classification of people's names and countries](/img/95/1f5b0a17a00da5473180667ccc33e2.png)
[machine learning] naive Bayesian classification of text -- Classification of people's names and countries
随机推荐
迪赛智慧数——折线图(堆叠面积图):2022年不同职业人群存款额占月收入比例排名
Save 70% of the video memory and increase the training speed by 2 times! Zheda & Ali proposed online convolution re parameterization orepa, and the code has been open source! (CVPR 2022 )
What technology is needed for applet development
ESP8266-Arduino编程实例-SPIFFS及数据上传(Arduino IDE和PlatformIO IDE)
【NLP】生成词云
Have you seen the management area decoupling architecture? Can help customers solve big problems
Soft test --- database (3) data operation
array_diff_assoc 元素是数组时不比较数组值的办法
详解visual studio 2015在局域网中远程调试程序
kingbase中指定用户默认查找schema,或曰用户无法使用public schema下函数问题
The applet listens for the target node to appear on the screen
In Kingbase, the user is specified to search the schema by default, or the user cannot use the function under the public schema
Mesh data generation function meshgrid
KubeEdge发布云原生边缘计算威胁模型及安全防护技术白皮书
typeof原理
小程序开发需要什么技术
RHCSA第一天
如何高效、精准地进行图片搜索?看看轻量化视觉预训练模型
拥抱开源指南
B+ tree height calculation of MySQL