Skip to content

Instantly share code, notes, and snippets.

@ZeVS777
Last active June 10, 2023 13:46
Show Gist options
  • Save ZeVS777/ca88759c02a127e4519081c051c82543 to your computer and use it in GitHub Desktop.
Save ZeVS777/ca88759c02a127e4519081c051c82543 to your computer and use it in GitHub Desktop.
Udemy - Computer Graphics with Modern OpenGL and C++ / code files after 02 - Beginner 016 CODING Clean Up
// main.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <vector>
//#pragma comment (lib, "glew32s.lib") // Если хотите, чтоб glew32.dll не надо было копировать
//#define GLEW_STATIC // Если хотите, чтоб glew32.dll не надо было копировать
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> // translate, rotate, scale, identity
#include <glm/gtc/type_ptr.hpp>
#include "Window.h"
#include "Mesh.h"
#include "Shader.h"
const float toRadians = 3.14159265f / 180.0f;
Window mainWindow;
std::vector<Mesh*> meshList;
std::vector<Shader> shaderList;
// Vertex Shader
static const char* vShader = "Shaders/shader.vert";
// Fragment Shader
static const char* fShader = "Shaders/shader.frag";
void CreateObjects()
{
unsigned int indices[] = {
0, 3, 1,
1, 3, 2,
2, 3, 0,
0, 1, 2
};
GLfloat vertices[] = {
-1.0f, -1.0f, 0.0f,
0.0f, -1.0f, 1.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
Mesh* obj1 = new Mesh();
obj1->CreateMesh(vertices, indices, 12, 12);
meshList.push_back(obj1);
Mesh* obj2 = new Mesh();
obj2->CreateMesh(vertices, indices, 12, 12);
meshList.push_back(obj2);
}
void CreateShaders()
{
Shader* shader1 = new Shader();
shader1->CreateFromFiles(vShader, fShader);
shaderList.push_back(*shader1);
}
int main()
{
mainWindow.initialize();
CreateObjects();
CreateShaders();
GLuint uniformModel, uniformProjection;
glm::mat4 projection = glm::perspective(45.0f, (GLfloat)mainWindow.getBufferWidth() / (GLfloat)mainWindow.getBufferHeight(), 0.1f, 100.0f);
// Loop until windows closed
while (!mainWindow.getShouldClose())
{
// Get+Handle user inputs
glfwPollEvents();
// Clear window
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shaderList[0].UseShader();
uniformModel = shaderList[0].GetModelLocation();
uniformProjection = shaderList[0].GetProjectionLocation();
glm::mat4 model = glm::identity<glm::mat4>();
model = glm::translate(model, glm::vec3(0.0f, 0.0f, -2.5f));
model = glm::scale(model, glm::vec3(0.4f, 0.4f, 1.0f));
glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(projection));
meshList[0]->RenderMesh();
model = glm::identity<glm::mat4>();
model = glm::translate(model, glm::vec3(0.0f, 1.0f, -2.5f));
model = glm::scale(model, glm::vec3(0.4f, 0.4f, 1.0f));
glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(projection));
meshList[1]->RenderMesh();
glUseProgram(0);
mainWindow.swapBuffers();
}
return 0;
}
#include "Mesh.h"
Mesh::Mesh()
{
VAO = 0, VBO = 0, IBO = 0, indexCount = 0;
}
void Mesh::CreateMesh(GLfloat* vertices, unsigned int* indices, unsigned int numOfVertices, unsigned int numOfIndices)
{
indexCount = numOfIndices;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, numOfIndices * sizeof(indices[0]), indices, GL_STATIC_DRAW);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, numOfVertices * sizeof(vertices[0]), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void Mesh::RenderMesh()
{
glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
Mesh::~Mesh()
{
}
#include <GL/glew.h>
#pragma once
class Mesh
{
public:
Mesh();
void CreateMesh(GLfloat* vertices, unsigned int* indices, unsigned int numOfVertices, unsigned int numOfIndices);
void RenderMesh();
~Mesh();
private:
GLuint VAO, VBO, IBO, indexCount;
};
#include "Shader.h"
Shader::Shader()
{
shader = 0, uniformModel = 0, uniformProjection = 0;
}
void Shader::CreateFromFiles(const char* vShader, const char* fShader)
{
std::string vShaderCode = readShaderCodeFromFile(vShader);
std::string fShaderCode = readShaderCodeFromFile(fShader);
compileShaders(vShaderCode.c_str(), fShaderCode.c_str());
}
Shader::~Shader()
{
}
std::string Shader::readShaderCodeFromFile(const char* shaderPath)
{
std::string code;
std::ifstream shaderFile;
shaderFile.exceptions(std::ifstream::badbit);
try
{
// Открываем файлы
shaderFile.open(shaderPath);
std::stringstream shaderStream;
// Считываем данные в потоки
shaderStream << shaderFile.rdbuf();
// Закрываем файлы
shaderFile.close();
// Преобразовываем потоки в массив GLchar
code = shaderStream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "Shader file " << shaderPath << " cannot be read" << std::endl;
}
return code;
}
void Shader::addShader(GLuint theProgram, const char* shaderCode, GLenum shaderType)
{
GLuint theShader = glCreateShader(shaderType);
const GLchar* theCode[1];
theCode[0] = shaderCode;
GLint codeLength[1];
codeLength[0] = strlen(shaderCode);
glShaderSource(theShader, 1, theCode, codeLength);
glCompileShader(theShader);
GLint result = 0;
GLchar errLog[1024] = { 0 };
glGetShaderiv(theShader, GL_COMPILE_STATUS, &result);
if (!result)
{
glGetShaderInfoLog(theShader, sizeof(errLog), NULL, errLog);
std::cerr << "Error compiling the " << shaderType << " shader: '" << errLog << "'\n";
return;
}
glAttachShader(theProgram, theShader);
}
void Shader::compileShaders(const char* vShaderCode, const char* fShaderCode)
{
shader = glCreateProgram();
if (!shader) {
std::cerr << "Error creating shader program\n";
return;
}
addShader(shader, vShaderCode, GL_VERTEX_SHADER);
addShader(shader, fShaderCode, GL_FRAGMENT_SHADER);
GLint result = 0;
GLchar errLog[1024] = { 0 };
glLinkProgram(shader);
glGetProgramiv(shader, GL_LINK_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shader, sizeof(errLog), NULL, errLog);
std::cerr << "Error linking program: '" << errLog << "'\n";
return;
}
glValidateProgram(shader);
glGetProgramiv(shader, GL_VALIDATE_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shader, sizeof(errLog), NULL, errLog);
std::cerr << "Error validating program: '" << errLog << "'\n";
return;
}
uniformModel = glGetUniformLocation(shader, "model");
uniformProjection = glGetUniformLocation(shader, "projection");
}
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <GL/glew.h>;
#pragma once
class Shader
{
public:
Shader();
void CreateFromFiles(const char* vShader, const char* fShader);
void UseShader() { glUseProgram(this->shader); }
GLuint GetModelLocation() { return this->uniformModel; }
GLuint GetProjectionLocation() { return this->uniformProjection; }
~Shader();
private:
GLuint shader, uniformModel, uniformProjection;
std::string readShaderCodeFromFile(const char* shaderPath);
void addShader(GLuint theProgram, const char* shaderCode, GLenum shaderType);
void compileShaders(const char* vShaderCode, const char* fShaderCode);
};
#version 330
in vec4 vCol;
out vec4 colour;
void main()
{
colour = vCol;
}
#version 330
layout (location = 0) in vec3 pos;
out vec4 vCol;
uniform mat4 model;
uniform mat4 projection;
void main()
{
gl_Position = projection * model * vec4(pos, 1.0);
vCol = vec4(clamp(pos, 0.0f, 1.0f), 1.0f);
}
#include "Window.h"
Window::Window()
{
width = 800;
height = 600;
bufferWidth = 0, bufferHeight = 0;
mainWindow = 0;
}
Window::Window(GLint windowWidth, GLint windowHeight)
{
width = windowWidth;
height = windowHeight;
bufferWidth = 0, bufferHeight = 0;
mainWindow = 0;
}
int Window::initialize()
{
if (!glfwInit())
{
std::cerr << "GLFW library load failed...\n";
glfwTerminate();
return 1;
}
// Setup GLFW Window properties
// OpenGL Version
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// OpenGL profile without backwards compatibility
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// OpenGL profile allow forward compatibility
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
mainWindow = glfwCreateWindow(width, height, "Main window", NULL, NULL);
if (!mainWindow)
{
std::cerr << "GLFW window creation failed...\n";
glfwTerminate();
return 1;
}
// OpenGL viewport dimensions
glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight);
// Set context for GLEW to use
glfwMakeContextCurrent(mainWindow);
glewExperimental = GLU_TRUE;
GLenum error = glewInit();
if (error != GLEW_OK)
{
std::cerr << "GLEW initialization failed...\n";
glfwDestroyWindow(mainWindow);
glfwTerminate();
return 1;
}
glEnable(GL_DEPTH_TEST);
// Setup viewport size
glViewport(0, 0, bufferWidth, bufferHeight);
return 0;
}
Window::~Window()
{
glfwDestroyWindow(mainWindow);
glfwTerminate();
}
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#pragma once
class Window
{
public:
Window();
Window(GLint windowWidth, GLint windowHeight);
int initialize();
GLint getBufferWidth() { return bufferWidth; }
GLint getBufferHeight() { return bufferHeight; }
bool getShouldClose() { return glfwWindowShouldClose(mainWindow); }
void swapBuffers() { glfwSwapBuffers(mainWindow); }
~Window();
private:
GLFWwindow* mainWindow;
GLint width, height;
GLint bufferWidth, bufferHeight;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment