feat: initial commit
This commit is contained in:
6
src/block.cpp
Normal file
6
src/block.cpp
Normal file
@ -0,0 +1,6 @@
|
||||
#include "block.h"
|
||||
|
||||
Block::Block(glm::vec3 position, glm::vec4 color) {
|
||||
this->m_position = position;
|
||||
this->m_color = m_color;
|
||||
}
|
33
src/file_manager.cpp
Normal file
33
src/file_manager.cpp
Normal file
@ -0,0 +1,33 @@
|
||||
#include "file_manager.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
FileManager::FileManager()
|
||||
{
|
||||
}
|
||||
|
||||
FileManager::~FileManager()
|
||||
{
|
||||
}
|
||||
|
||||
std::string FileManager::read(const std::string &filename)
|
||||
{
|
||||
std::ifstream file;
|
||||
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
|
||||
|
||||
std::stringstream fileStream;
|
||||
try
|
||||
{
|
||||
file.open(filename.c_str());
|
||||
fileStream << file.rdbuf();
|
||||
file.close();
|
||||
}
|
||||
catch (std::ifstream::failure e)
|
||||
{
|
||||
std::cout << "FileManager: error reading file: " << filename << std::endl;
|
||||
}
|
||||
|
||||
return fileStream.str();
|
||||
}
|
229
src/main.bkp.cpp
Normal file
229
src/main.bkp.cpp
Normal file
@ -0,0 +1,229 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/ext/matrix_transform.hpp>
|
||||
#include <glm/ext/matrix_clip_space.hpp>
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include "shader.h"
|
||||
#include "file_manager.h"
|
||||
#include "prelude.h"
|
||||
#include "block.h"
|
||||
#include "vertex.h"
|
||||
#include "model.h"
|
||||
|
||||
#define WIDTH 1024
|
||||
#define HEIGHT 768
|
||||
|
||||
int main() {
|
||||
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
|
||||
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
|
||||
|
||||
SDL_Window *window = SDL_CreateWindow("OpenGL Test", WIDTH, HEIGHT, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE|SDL_WINDOW_ALWAYS_ON_TOP);
|
||||
|
||||
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
|
||||
|
||||
glewExperimental = GL_TRUE;
|
||||
if (GLEW_OK != glewInit()) {
|
||||
fprintf(stderr, "Could not initialize GLEW!\n");
|
||||
SDL_GL_DestroyContext(glcontext);
|
||||
SDL_DestroyWindow(window);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
glEnable(GL_DEBUG_OUTPUT);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glDebugMessageCallback(MessageCallback, 0);
|
||||
|
||||
// brightness multipliers for faces
|
||||
const float FACE_BRIGHTNESS[6] = {
|
||||
1.0f, // front
|
||||
0.7f, // right
|
||||
0.5f, // back
|
||||
0.7f, // left
|
||||
1.2f, // top
|
||||
0.4f // bottom
|
||||
};
|
||||
|
||||
// position, normal, color
|
||||
glm::vec4 cubeColor = {1.0f, 0.5f, 0.31f, 1.0f};
|
||||
std::vector<Point> cubeVerts = {
|
||||
// front face (z = 0, normal = +Z)
|
||||
{ {-0.5f, -0.5f, 0.5f}, {0.f, 0.f, 1.f}, cubeColor },
|
||||
{ {0.5f, -0.5f, 0.5f}, {0.f, 0.f, 1.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, 0.5f}, {0.f, 0.f, 1.f}, cubeColor },
|
||||
{ {-0.5f, 0.5f, 0.5f}, {0.f, 0.f, 1.f}, cubeColor },
|
||||
|
||||
// back face (z = 1, normal = -Z)
|
||||
{ {-0.5f, -0.5f, -0.5f}, {0.f, 0.f, -1.f}, cubeColor },
|
||||
{ {0.5f, -0.5f, -0.5f}, {0.f, 0.f, -1.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, -0.5f}, {0.f, 0.f, -1.f}, cubeColor },
|
||||
{ {-0.5f, 0.5f, -0.5f}, {0.f, 0.f, -1.f}, cubeColor },
|
||||
|
||||
// left face (x = 0, normal = -X)
|
||||
{ {-0.5f, -0.5f, -0.5f}, {-1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {-0.5f, -0.5f, 0.5f}, {-1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {-0.5f, 0.5f, 0.5f}, {-1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {-0.5f, 0.5f, -0.5f}, {-1.f, 0.f, 0.f}, cubeColor },
|
||||
|
||||
// right face (x = 1, normal = +X)
|
||||
{ {0.5f, -0.5f, -0.5f}, {1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {0.5f, -0.5f, 0.5f}, {1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, 0.5f}, {1.f, 0.f, 0.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, -0.5f}, {1.f, 0.f, 0.f}, cubeColor },
|
||||
|
||||
// top face (y = 1, normal = +Y)
|
||||
{ {-0.5f, 0.5f, 0.5f}, {0.f, 1.f, 0.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, 0.5f}, {0.f, 1.f, 0.f}, cubeColor },
|
||||
{ {0.5f, 0.5f, -0.5f}, {0.f, 1.f, 0.f}, cubeColor },
|
||||
{ {-0.5f, 0.5f, -0.5f}, {0.f, 1.f, 0.f}, cubeColor },
|
||||
|
||||
// bottom face (y = 0, normal = -Y)
|
||||
{ {-0.5f, -0.5f, 0.5f}, {0.f, -1.f, 0.f}, cubeColor },
|
||||
{ {0.5f, -0.5f, 0.5f}, {0.f, -1.f, 0.f}, cubeColor },
|
||||
{ {0.5f, -0.5f, -0.5f}, {0.f, -1.f, 0.f}, cubeColor },
|
||||
{ {-0.5f, -0.5f, -0.5f}, {0.f, -1.f, 0.f}, cubeColor },
|
||||
};
|
||||
|
||||
std::vector<unsigned int> cubeIndices = {
|
||||
0,1,2, 2,3,0, // front
|
||||
4,5,6, 6,7,4, // back
|
||||
8,9,10, 10,11,8, // left
|
||||
12,13,14, 14,15,12, // right
|
||||
16,17,18, 18,19,16, // top
|
||||
20,21,22, 22,23,20 // bottom
|
||||
};
|
||||
|
||||
Vertices vertices;
|
||||
for (auto &v : cubeVerts) vertices.PushVertex(v);
|
||||
for (auto i : cubeIndices) vertices.PushIndex(i);
|
||||
vertices.Upload();
|
||||
|
||||
Shader simpleShader;
|
||||
simpleShader.init(
|
||||
FileManager::read("./src/shaders/simple.vs"),
|
||||
FileManager::read("./src/shaders/simple.fs")
|
||||
);
|
||||
|
||||
int screenWidth = WIDTH, screenHeight = HEIGHT;
|
||||
|
||||
glm::vec3 cameraPosition(0.f, 0.f, 2.f);
|
||||
glm::vec3 cameraViewDirection(0.f, 0.f, -1.f);
|
||||
// glm::vec3 lightPosition(1.f, 3.5f, -2.f);
|
||||
glm::vec3 lightPosition = cameraPosition;
|
||||
|
||||
glm::mat4 model(1.f);
|
||||
|
||||
glm::mat4 view = glm::lookAt(
|
||||
cameraPosition,
|
||||
cameraPosition + cameraViewDirection,
|
||||
glm::vec3(0.f, 1.f, 0.f)
|
||||
);
|
||||
|
||||
glm::mat4 projection = glm::perspective(
|
||||
(float)M_PI_2,
|
||||
(float)screenWidth / (float)screenHeight,
|
||||
0.01f,
|
||||
100.0f
|
||||
);
|
||||
|
||||
float angle = 3.45f;
|
||||
Uint64 lastTicks = SDL_GetTicks();
|
||||
|
||||
Object cube = Object::LoadFile("./assets/cube.obj");
|
||||
Object monkey = Object::LoadFile("./assets/monkey.obj");
|
||||
|
||||
bool paused = false;
|
||||
|
||||
bool quit = false;
|
||||
while (!quit) {
|
||||
Uint64 currentTicks = SDL_GetTicks();
|
||||
float deltaTime = (currentTicks - lastTicks) / 1000.0f; // seconds
|
||||
|
||||
lastTicks = currentTicks;
|
||||
|
||||
SDL_Event event;
|
||||
while(SDL_PollEvent(&event)) {
|
||||
switch (event.type) {
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
case SDL_EVENT_QUIT:
|
||||
quit = true;
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
int width, height;
|
||||
if (SDL_GetWindowSize(window, &width, &height)) {
|
||||
glViewport(
|
||||
0,
|
||||
0,
|
||||
width,
|
||||
height);
|
||||
}
|
||||
break;
|
||||
case SDL_EVENT_KEY_DOWN:
|
||||
switch (event.key.key) {
|
||||
case SDLK_SPACE:
|
||||
paused = !paused;
|
||||
break;
|
||||
// case SDLK_F5:
|
||||
// reload_shaders(&context);
|
||||
// break;
|
||||
default: break;
|
||||
};
|
||||
break;
|
||||
default: break;
|
||||
};
|
||||
}
|
||||
|
||||
// update rotation
|
||||
if (!paused) {
|
||||
angle += glm::radians(45.0f) * deltaTime; // 72° per second
|
||||
if (angle > glm::two_pi<float>()) {
|
||||
angle -= glm::two_pi<float>(); // keep value small
|
||||
}
|
||||
}
|
||||
|
||||
// std::cout << "angle = " << angle << std::endl;
|
||||
|
||||
glClearColor(0x18/255.0f, 0x18/255.0f, 0x18/255.0f, 1);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
// Triangle render
|
||||
{
|
||||
simpleShader.use();
|
||||
|
||||
model = glm::rotate(
|
||||
glm::mat4(1.f),
|
||||
angle,
|
||||
glm::vec3(0.8f, -0.4f, 0.5f)
|
||||
);
|
||||
|
||||
// lightPosition -= glm::vec3(0.05f, 0.f, 0.f) * deltaTime;
|
||||
|
||||
simpleShader.setMat4("u_model", model);
|
||||
simpleShader.setMat4("u_view", view);
|
||||
simpleShader.setMat4("u_projection", projection);
|
||||
|
||||
simpleShader.setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
|
||||
simpleShader.setVec3("lightPos", lightPosition);
|
||||
simpleShader.setVec3("viewPos", cameraPosition);
|
||||
simpleShader.setFloat("ambientStrength", 0.2f);
|
||||
simpleShader.setFloat("specularStrength", 0.5f);
|
||||
|
||||
vertices.Draw();
|
||||
}
|
||||
|
||||
SDL_GL_SwapWindow(window);
|
||||
}
|
||||
|
||||
SDL_GL_DestroyContext(glcontext);
|
||||
SDL_DestroyWindow(window);
|
||||
|
||||
return 0;
|
||||
}
|
231
src/main.cpp
Normal file
231
src/main.cpp
Normal file
@ -0,0 +1,231 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/ext/quaternion_geometric.hpp>
|
||||
#include <glm/ext/matrix_transform.hpp>
|
||||
#include <glm/ext/matrix_clip_space.hpp>
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include "shader.h"
|
||||
#include "file_manager.h"
|
||||
#include "prelude.h"
|
||||
#include "block.h"
|
||||
#include "vertex.h"
|
||||
#include "model.h"
|
||||
|
||||
#define WIDTH 1024
|
||||
#define HEIGHT 768
|
||||
|
||||
int main() {
|
||||
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
|
||||
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
|
||||
|
||||
SDL_Window *window = SDL_CreateWindow("OpenGL Test", WIDTH, HEIGHT, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE|SDL_WINDOW_ALWAYS_ON_TOP);
|
||||
|
||||
SDL_SetWindowRelativeMouseMode(window, true);
|
||||
|
||||
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
|
||||
|
||||
glewExperimental = GL_TRUE;
|
||||
if (GLEW_OK != glewInit()) {
|
||||
fprintf(stderr, "Could not initialize GLEW!\n");
|
||||
SDL_GL_DestroyContext(glcontext);
|
||||
SDL_DestroyWindow(window);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
std::cout << "GL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
|
||||
std::cout << "GL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
|
||||
std::cout << "GL_VERSION: " << glGetString(GL_VERSION) << std::endl;
|
||||
|
||||
glEnable(GL_DEBUG_OUTPUT);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glDebugMessageCallback(MessageCallback, 0);
|
||||
|
||||
Shader simpleShader;
|
||||
simpleShader.init(
|
||||
FileManager::read("./src/shaders/simple.vs"),
|
||||
FileManager::read("./src/shaders/simple.fs")
|
||||
);
|
||||
|
||||
int screenWidth = WIDTH, screenHeight = HEIGHT;
|
||||
|
||||
glm::vec3 cameraPosition(0.f, 0.f, 2.f);
|
||||
// glm::vec3 cameraViewDirection(0.f, 0.f, -1.f);
|
||||
// glm::vec3 lightPosition(1.f, 3.5f, -2.f);
|
||||
glm::vec3 lightPosition(-5.f, 5.f, 5.f);
|
||||
|
||||
glm::mat4 model(1.f);
|
||||
|
||||
glm::mat4 projection = glm::perspective(
|
||||
(float)M_PI_2,
|
||||
(float)screenWidth / (float)screenHeight,
|
||||
0.01f,
|
||||
100.0f
|
||||
);
|
||||
|
||||
float angle = 3.45f;
|
||||
Uint64 lastTicks = SDL_GetTicks();
|
||||
|
||||
// Object teapot = Object::LoadFile("./assets/kastrula/kastrula.obj");
|
||||
// Object bricks = Object::LoadFile("./assets/bricks/bricks.obj");
|
||||
Object lightSource = Object::LoadFile("./assets/cube.obj");
|
||||
Object target = Object::LoadFile("./assets/car/car.obj");
|
||||
|
||||
bool paused = false;
|
||||
|
||||
float yaw = -90.0f; // looking along -Z initially
|
||||
float pitch = 0.0f; // no vertical tilt
|
||||
|
||||
// FPS tracking
|
||||
Uint64 startTicks = SDL_GetTicks();
|
||||
int frameCount = 0;
|
||||
|
||||
bool quit = false;
|
||||
while (!quit) {
|
||||
Uint64 currentTicks = SDL_GetTicks();
|
||||
float deltaTime = (currentTicks - lastTicks) / 1000.0f; // seconds
|
||||
|
||||
lastTicks = currentTicks;
|
||||
|
||||
SDL_Event event;
|
||||
while(SDL_PollEvent(&event)) {
|
||||
switch (event.type) {
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
case SDL_EVENT_QUIT:
|
||||
quit = true;
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
int width, height;
|
||||
if (SDL_GetWindowSize(window, &width, &height)) {
|
||||
screenWidth = width;
|
||||
screenHeight = height;
|
||||
glViewport(
|
||||
0,
|
||||
0,
|
||||
width,
|
||||
height);
|
||||
projection = glm::perspective(
|
||||
(float)M_PI_2,
|
||||
(float)screenWidth / (float)screenHeight,
|
||||
0.01f,
|
||||
100.0f
|
||||
);
|
||||
}
|
||||
break;
|
||||
default: break;
|
||||
};
|
||||
}
|
||||
|
||||
float mouseXRel, mouseYRel;
|
||||
Uint32 mouseState = SDL_GetRelativeMouseState(&mouseXRel, &mouseYRel);
|
||||
|
||||
float sensitivity = 0.1f; // tweak as needed
|
||||
yaw += mouseXRel * sensitivity;
|
||||
pitch -= mouseYRel * sensitivity; // invert Y for typical FPS control
|
||||
|
||||
// clamp pitch to avoid flipping
|
||||
if (pitch > 89.0f) pitch = 89.0f;
|
||||
if (pitch < -89.0f) pitch = -89.0f;
|
||||
|
||||
// convert to direction vector
|
||||
glm::vec3 cameraViewDirection(0.f, 0.f, -1.f);
|
||||
cameraViewDirection.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
|
||||
cameraViewDirection.y = sin(glm::radians(pitch));
|
||||
cameraViewDirection.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
|
||||
cameraViewDirection = glm::normalize(cameraViewDirection);
|
||||
|
||||
glm::vec3 velocity(0.f);
|
||||
|
||||
const bool* state = SDL_GetKeyboardState(nullptr);
|
||||
|
||||
if (state[SDL_SCANCODE_P]) paused = !paused;
|
||||
|
||||
glm::vec3 front = glm::normalize(glm::vec3(cameraViewDirection.x, 0.f, cameraViewDirection.z));
|
||||
glm::vec3 right = glm::normalize(glm::cross(front, glm::vec3(0.f, 1.f, 0.f)));
|
||||
|
||||
if (state[SDL_SCANCODE_W]) velocity += front;
|
||||
if (state[SDL_SCANCODE_S]) velocity -= front;
|
||||
if (state[SDL_SCANCODE_A]) velocity -= right;
|
||||
if (state[SDL_SCANCODE_D]) velocity += right;
|
||||
if (state[SDL_SCANCODE_SPACE]) velocity.y += 1.f;
|
||||
if (state[SDL_SCANCODE_LSHIFT]) velocity.y -= 1.f;
|
||||
|
||||
cameraPosition += velocity * deltaTime * 2.5f; // speed is e.g. 2.5f
|
||||
|
||||
glm::mat4 view = glm::lookAt(
|
||||
cameraPosition,
|
||||
cameraPosition + cameraViewDirection,
|
||||
glm::vec3(0.f, 1.f, 0.f)
|
||||
);
|
||||
|
||||
// update rotation
|
||||
if (!paused) {
|
||||
angle += glm::radians(45.0f) * deltaTime; // 72° per second
|
||||
if (angle > glm::two_pi<float>()) {
|
||||
angle -= glm::two_pi<float>(); // keep value small
|
||||
}
|
||||
}
|
||||
|
||||
// std::cout << "angle = " << angle << std::endl;
|
||||
|
||||
glClearColor(0x18/255.0f, 0x18/255.0f, 0x18/255.0f, 1);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
// Triangle render
|
||||
{
|
||||
simpleShader.use();
|
||||
|
||||
simpleShader.setMat4("u_view", view);
|
||||
simpleShader.setMat4("u_projection", projection);
|
||||
|
||||
simpleShader.setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
|
||||
simpleShader.setVec3("lightPos", lightPosition);
|
||||
simpleShader.setVec3("viewPos", cameraPosition);
|
||||
|
||||
model = glm::mat4(1.f);
|
||||
model = glm::translate(model, lightPosition);
|
||||
|
||||
simpleShader.setMat4("u_model", model);
|
||||
|
||||
lightSource.Render(simpleShader);
|
||||
|
||||
// lightPosition -= glm::vec3(0.05f, 0.f, 0.f) * deltaTime;
|
||||
|
||||
model = glm::rotate(
|
||||
glm::mat4(1.f),
|
||||
angle,
|
||||
glm::vec3(0.f, -0.5f, 0.0f)
|
||||
) * 0.5f;
|
||||
|
||||
simpleShader.setMat4("u_model", model);
|
||||
|
||||
target.Render(simpleShader);
|
||||
}
|
||||
|
||||
SDL_GL_SwapWindow(window);
|
||||
|
||||
frameCount++;
|
||||
currentTicks = SDL_GetTicks();
|
||||
Uint64 elapsed = currentTicks - startTicks;
|
||||
|
||||
if (elapsed >= 1000) { // one second passed
|
||||
double fps = (double)frameCount / (elapsed / 1000.0);
|
||||
std::cout << "FPS: " << fps << std::endl;
|
||||
frameCount = 0;
|
||||
startTicks = currentTicks;
|
||||
}
|
||||
}
|
||||
|
||||
SDL_GL_DestroyContext(glcontext);
|
||||
SDL_DestroyWindow(window);
|
||||
|
||||
return 0;
|
||||
}
|
365
src/model.cpp
Normal file
365
src/model.cpp
Normal file
@ -0,0 +1,365 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <GL/glew.h>
|
||||
|
||||
#include "model.h"
|
||||
|
||||
ObjElement toElement(const std::string &s) {
|
||||
if (s == "#") return ObjElement::OHASH;
|
||||
if (s == "mtllib") return ObjElement::MTLLIB;
|
||||
if (s == "usemtl") return ObjElement::USEMTL;
|
||||
if (s == "o") return ObjElement::O;
|
||||
if (s == "v") return ObjElement::V;
|
||||
if (s == "vn") return ObjElement::VN;
|
||||
if (s == "vt") return ObjElement::VT;
|
||||
if (s == "f") return ObjElement::F;
|
||||
return ObjElement::OUNKNOWN;
|
||||
}
|
||||
|
||||
MtlElement toMtlElement(const std::string &s) {
|
||||
if (s == "#") return MtlElement::MHASH;
|
||||
if (s == "newmtl") return MtlElement::NEWMTL;
|
||||
if (s == "Ns") return MtlElement::NS;
|
||||
if (s == "Ka") return MtlElement::KA;
|
||||
if (s == "Ks") return MtlElement::KS;
|
||||
if (s == "Kd") return MtlElement::KD;
|
||||
if (s == "Ni") return MtlElement::NI;
|
||||
if (s == "d") return MtlElement::D;
|
||||
if (s == "illum") return MtlElement::ILLUM;
|
||||
if (s == "map_Kd") return MtlElement::MAP_KD;
|
||||
if (s == "map_Ka") return MtlElement::MAP_KA;
|
||||
// if (s == "map_Ke") return MtlElement::MAP_KE;
|
||||
return MtlElement::MUNKNOWN;
|
||||
}
|
||||
|
||||
void Vertex::DefineAttrib()
|
||||
{
|
||||
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, m_position)));
|
||||
glEnableVertexAttribArray(0);
|
||||
|
||||
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, m_normal)));
|
||||
glEnableVertexAttribArray(1);
|
||||
|
||||
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, m_texCoord)));
|
||||
glEnableVertexAttribArray(2);
|
||||
}
|
||||
|
||||
void Face::PushItem(const FaceItem& item)
|
||||
{
|
||||
m_items.push_back(item);
|
||||
}
|
||||
|
||||
inline int Object::NormalizeIndex(const std::string &s, int baseCount) {
|
||||
if (s.empty()) return -1;
|
||||
int idx = std::stoi(s);
|
||||
if (idx > 0) return idx - 1;
|
||||
return baseCount + idx;
|
||||
}
|
||||
|
||||
Mesh::Mesh() {
|
||||
glGenVertexArrays(1, &m_vao);
|
||||
glGenBuffers(1, &m_vbo);
|
||||
glGenBuffers(1, &m_ebo);
|
||||
|
||||
glBindVertexArray(m_vao);
|
||||
|
||||
// VBO (vertex buffer)
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_STATIC_DRAW);
|
||||
|
||||
// EBO (index buffer)
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 0, nullptr, GL_STATIC_DRAW);
|
||||
|
||||
Vertex::DefineAttrib();
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
Object::Object() {
|
||||
m_vertices = std::vector<glm::vec3>();
|
||||
m_normals = std::vector<glm::vec3>();
|
||||
m_texCoords = std::vector<glm::vec2>();
|
||||
}
|
||||
|
||||
void Object::LoadMaterials(const std::string& filename) {
|
||||
std::ifstream file(filename);
|
||||
|
||||
std::string currentMaterialName;
|
||||
std::shared_ptr<Material> currentMaterial;
|
||||
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
std::istringstream iss(line);
|
||||
std::string prefix;
|
||||
iss >> prefix;
|
||||
switch(toMtlElement(prefix)) {
|
||||
case MtlElement::MHASH:
|
||||
{
|
||||
std::cout << "comment: " << line << std::endl;
|
||||
continue;
|
||||
}
|
||||
case MtlElement::NEWMTL:
|
||||
{
|
||||
if (currentMaterial) {
|
||||
m_materials.insert(std::make_pair(currentMaterialName, std::move(currentMaterial)));
|
||||
currentMaterial = nullptr;
|
||||
}
|
||||
std::string materialName;
|
||||
iss >> materialName;
|
||||
currentMaterialName = materialName;
|
||||
currentMaterial = std::make_shared<Material>();
|
||||
break;
|
||||
}
|
||||
case MtlElement::NS:
|
||||
{
|
||||
float weight;
|
||||
iss >> weight;
|
||||
currentMaterial->SetSpecularWeight(weight);
|
||||
}
|
||||
case MtlElement::KA:
|
||||
{
|
||||
float r, g, b;
|
||||
iss >> r >> g >> b;
|
||||
currentMaterial->SetAmbientColor(glm::vec3(r, g, b));
|
||||
break;
|
||||
}
|
||||
case MtlElement::KS:
|
||||
{
|
||||
float r, g, b;
|
||||
iss >> r >> g >> b;
|
||||
currentMaterial->SetSpecularColor(glm::vec3(r, g, b));
|
||||
break;
|
||||
}
|
||||
case MtlElement::KD:
|
||||
{
|
||||
float r, g, b;
|
||||
iss >> r >> g >> b;
|
||||
currentMaterial->SetDiffuseColor(glm::vec3(r, g, b));
|
||||
break;
|
||||
}
|
||||
case MtlElement::MAP_KD:
|
||||
{
|
||||
std::string texturePath;
|
||||
std::string part;
|
||||
while (iss >> part) {
|
||||
texturePath += part + " ";
|
||||
}
|
||||
texturePath = texturePath.substr(0, texturePath.size() - 1);
|
||||
currentMaterial->SetDiffuseTexture(Texture::LoadFile(texturePath));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentMaterial) {
|
||||
// m_materials.insert(std::make_pair(currentMaterialName, std::move(currentMaterial)));
|
||||
AddMaterial(currentMaterialName, std::move(currentMaterial));
|
||||
}
|
||||
}
|
||||
|
||||
void Object::AddMaterial(std::string name, std::shared_ptr<Material> material)
|
||||
{
|
||||
m_materials.insert(std::make_pair(std::move(name), std::move(material)));
|
||||
}
|
||||
|
||||
std::shared_ptr<Material> Object::GetMaterial(std::string name)
|
||||
{
|
||||
auto material = m_materials.find(name);
|
||||
if (material == m_materials.end()) return nullptr;
|
||||
return material->second;
|
||||
}
|
||||
|
||||
void Object::CreateNewMesh(const std::string& materialName)
|
||||
{
|
||||
Mesh mesh;
|
||||
mesh.materialName = materialName;
|
||||
m_meshes.push_back(mesh);
|
||||
}
|
||||
|
||||
Mesh& Object::GetLastMesh()
|
||||
{
|
||||
if (m_meshes.empty()) {
|
||||
auto material = std::make_shared<Material>();
|
||||
material->SetAmbientColor(glm::vec3(0.52f, 0.52f, 0.52f));
|
||||
// TODO: come up with name for a default material
|
||||
AddMaterial("", std::move(material));
|
||||
CreateNewMesh("");
|
||||
}
|
||||
return m_meshes.back();
|
||||
}
|
||||
|
||||
Object Object::LoadFile(const std::string& filename) {
|
||||
std::ifstream file(filename);
|
||||
|
||||
Object obj;
|
||||
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
std::istringstream iss(line);
|
||||
std::string prefix;
|
||||
iss >> prefix;
|
||||
switch(toElement(prefix)) {
|
||||
// comment
|
||||
case ObjElement::OHASH:
|
||||
{
|
||||
std::cout << "comment: " << line << std::endl;
|
||||
continue;
|
||||
}
|
||||
case ObjElement::MTLLIB:
|
||||
{
|
||||
std::string mtlFile;
|
||||
iss >> mtlFile;
|
||||
std::filesystem::path fullPath = filename;
|
||||
std::filesystem::path mtlPath = fullPath.replace_filename(mtlFile);
|
||||
obj.LoadMaterials(mtlPath);
|
||||
std::cout << "loaded mtl at '" << mtlPath << "' with "
|
||||
<< obj.m_materials.size() << " materials" << std::endl;
|
||||
break;
|
||||
}
|
||||
case ObjElement::USEMTL:
|
||||
{
|
||||
std::string materialName;
|
||||
iss >> materialName;
|
||||
auto& mesh = obj.GetLastMesh();
|
||||
if (mesh.materialName != materialName) {
|
||||
Mesh mesh;
|
||||
mesh.materialName = materialName;
|
||||
obj.m_meshes.push_back(mesh);
|
||||
}
|
||||
break;
|
||||
}
|
||||
// object name I suppose
|
||||
case ObjElement::O:
|
||||
{
|
||||
obj.m_name = line.substr(2);
|
||||
break;
|
||||
}
|
||||
// vertex with its position
|
||||
case ObjElement::V:
|
||||
{
|
||||
float x, y, z, w;
|
||||
w = 1.0f;
|
||||
iss >> x >> y >> z;
|
||||
if (iss >> w) {
|
||||
x /= w;
|
||||
y /= w;
|
||||
z /= w;
|
||||
}
|
||||
obj.m_vertices.emplace_back(x, y, z);
|
||||
break;
|
||||
}
|
||||
case ObjElement::VN:
|
||||
{
|
||||
float x, y, z;
|
||||
iss >> x >> y >> z;
|
||||
obj.m_normals.emplace_back(x, y, z);
|
||||
break;
|
||||
}
|
||||
case ObjElement::VT:
|
||||
{
|
||||
float u, v;
|
||||
iss >> u >> v;
|
||||
obj.m_texCoords.emplace_back(u, 1.0f - v);
|
||||
break;
|
||||
}
|
||||
case ObjElement::F:
|
||||
{
|
||||
auto& mesh = obj.GetLastMesh();
|
||||
std::string token;
|
||||
|
||||
Face fv;
|
||||
|
||||
while (iss >> token) {
|
||||
std::string a, b, c;
|
||||
std::istringstream ref(token);
|
||||
|
||||
std::getline(ref, a, '/');
|
||||
std::getline(ref, b, '/');
|
||||
std::getline(ref, c, '/');
|
||||
|
||||
int vi = Object::NormalizeIndex(a, (int)obj.m_vertices.size());
|
||||
int ti = Object::NormalizeIndex(b, (int)obj.m_texCoords.size());
|
||||
int ni = Object::NormalizeIndex(c, (int)obj.m_normals.size());
|
||||
|
||||
glm::vec3 vert, norm;
|
||||
glm::vec2 texCoord;
|
||||
vert = obj.m_vertices[vi];
|
||||
if (ni >= 0) norm = obj.m_normals[ni];
|
||||
if (ti >= 0) texCoord = obj.m_texCoords[ti];
|
||||
|
||||
mesh.m_vertexBuffer.emplace_back(vert, norm, texCoord);
|
||||
mesh.m_indexBuffer.push_back(mesh.m_vertexBuffer.size() - 1);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "Object name: " << obj.m_name << std::endl;
|
||||
std::cout << "Vertices count: " << obj.m_vertices.size() << std::endl;
|
||||
std::cout << "Normals count: " << obj.m_normals.size() << std::endl;
|
||||
std::cout << "TexCoords count: " << obj.m_texCoords.size() << std::endl;
|
||||
std::cout << "Meshes count: " << obj.m_meshes.size() << std::endl;
|
||||
std::cout << "Materials count: " << obj.m_materials.size() << std::endl;
|
||||
|
||||
// std::cout << "Vertex Buffer size: " << obj.m_vertexBuffer.size() << std::endl;
|
||||
// std::cout << "Index Buffer size: " << obj.m_indexBuffer.size() << std::endl;
|
||||
|
||||
file.close();
|
||||
|
||||
for (auto &mesh : obj.m_meshes) {
|
||||
mesh.Upload();
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
void Object::Render(Shader& shader)
|
||||
{
|
||||
for (auto &mesh : m_meshes) {
|
||||
auto material = GetMaterial(mesh.materialName);
|
||||
|
||||
shader.setFloat("ambientStrength", 0.2f);
|
||||
shader.setFloat("specularStrength", material->GetSpecularWeight());
|
||||
shader.setVec3("ambientColor", material->GetAmbientColor());
|
||||
shader.setVec3("diffuseColor", material->GetDiffuseColor());
|
||||
shader.setVec3("specularColor", material->GetSpecularColor());
|
||||
|
||||
if (material->HasDiffuseTexture()) {
|
||||
shader.setBool("useTexture", true);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, material->GetDiffuseTexture()->GetID());
|
||||
shader.setInt("diffuseTex", 0);
|
||||
} else {
|
||||
shader.setBool("useTexture", false);
|
||||
}
|
||||
|
||||
mesh.Render();
|
||||
}
|
||||
}
|
||||
|
||||
void Mesh::Upload()
|
||||
{
|
||||
glBindVertexArray(m_vao);
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, m_vertexBuffer.size() * sizeof(Vertex), m_vertexBuffer.data(), GL_STATIC_DRAW);
|
||||
|
||||
// Upload indices
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer.size() * sizeof(unsigned int), m_indexBuffer.data(), GL_STATIC_DRAW);
|
||||
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
void Mesh::Render()
|
||||
{
|
||||
Bind();
|
||||
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(m_indexBuffer.size()), GL_UNSIGNED_INT, 0);
|
||||
Unbind();
|
||||
}
|
190
src/prelude.cpp
Normal file
190
src/prelude.cpp
Normal file
@ -0,0 +1,190 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include "prelude.h"
|
||||
|
||||
#define GLEW_STATIC
|
||||
#include <GL/glew.h>
|
||||
|
||||
#define SCREEN_WIDTH 1024
|
||||
#define SCREEN_HEIGHT 768
|
||||
|
||||
void panic_errno(const char *fmt, ...)
|
||||
{
|
||||
fprintf(stderr, "ERROR: ");
|
||||
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vfprintf(stderr, fmt, args);
|
||||
va_end(args);
|
||||
|
||||
fprintf(stderr, ": %s\n", strerror(errno));
|
||||
|
||||
exit(1);
|
||||
}
|
||||
|
||||
char *slurp_file(const char *file_path)
|
||||
{
|
||||
#define SLURP_FILE_PANIC panic_errno("Could not read file `%s`", file_path)
|
||||
FILE *f = fopen(file_path, "r");
|
||||
if (f == NULL) SLURP_FILE_PANIC;
|
||||
if (fseek(f, 0, SEEK_END) < 0) SLURP_FILE_PANIC;
|
||||
|
||||
long size = ftell(f);
|
||||
if (size < 0) SLURP_FILE_PANIC;
|
||||
|
||||
char *buffer = (char*)malloc(size + 1);
|
||||
if (buffer == NULL) SLURP_FILE_PANIC;
|
||||
|
||||
if (fseek(f, 0, SEEK_SET) < 0) SLURP_FILE_PANIC;
|
||||
|
||||
fread(buffer, 1, size, f);
|
||||
if (ferror(f) < 0) SLURP_FILE_PANIC;
|
||||
|
||||
buffer[size] = '\0';
|
||||
|
||||
if (fclose(f) < 0) SLURP_FILE_PANIC;
|
||||
|
||||
return buffer;
|
||||
#undef SLURP_FILE_PANIC
|
||||
}
|
||||
|
||||
bool compile_shader_source(const GLchar *source, GLenum shader_type, GLuint *shader)
|
||||
{
|
||||
*shader = glCreateShader(shader_type);
|
||||
glShaderSource(*shader, 1, &source, NULL);
|
||||
glCompileShader(*shader);
|
||||
|
||||
GLint compiled = 0;
|
||||
glGetShaderiv(*shader, GL_COMPILE_STATUS, &compiled);
|
||||
|
||||
if (!compiled) {
|
||||
GLchar message[1024];
|
||||
GLsizei message_size = 0;
|
||||
glGetShaderInfoLog(*shader, sizeof(message), &message_size, message);
|
||||
fprintf(stderr, "%.*s\n", message_size, message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool compile_shader_file(const char *file_path, GLenum shader_type, GLuint *shader)
|
||||
{
|
||||
char *source = slurp_file(file_path);
|
||||
bool err = compile_shader_source(source, shader_type, shader);
|
||||
free(source);
|
||||
return err;
|
||||
}
|
||||
|
||||
bool link_program(GLuint vert_shader, GLuint frag_shader, GLuint *program)
|
||||
{
|
||||
*program = glCreateProgram();
|
||||
|
||||
glAttachShader(*program, vert_shader);
|
||||
glAttachShader(*program, frag_shader);
|
||||
glLinkProgram(*program);
|
||||
|
||||
GLint linked = 0;
|
||||
glGetProgramiv(*program, GL_LINK_STATUS, &linked);
|
||||
if (!linked) {
|
||||
GLsizei message_size = 0;
|
||||
GLchar message[1024];
|
||||
|
||||
glGetProgramInfoLog(*program, sizeof(message), &message_size, message);
|
||||
fprintf(stderr, "Program Linking: %.*s\n", message_size, message);
|
||||
}
|
||||
|
||||
glDeleteShader(vert_shader);
|
||||
glDeleteShader(frag_shader);
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
void reload_shaders(RenderContext* context)
|
||||
{
|
||||
glDeleteProgram(context->program);
|
||||
|
||||
context->program_failed = false;
|
||||
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
|
||||
GLuint vert = 0;
|
||||
if (!compile_shader_file("./main.vert", GL_VERTEX_SHADER, &vert)) {
|
||||
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
context->program_failed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
GLuint frag = 0;
|
||||
if (!compile_shader_file("./main.frag", GL_FRAGMENT_SHADER, &frag)) {
|
||||
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
context->program_failed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!link_program(vert, frag, &context->program)) {
|
||||
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
context->program_failed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
glUseProgram(context->program);
|
||||
|
||||
context->resolution_location = glGetUniformLocation(context->program, "resolution");
|
||||
context->time_location = glGetUniformLocation(context->program, "time");
|
||||
|
||||
printf("Successfully Reload the Shaders\n");
|
||||
}
|
||||
|
||||
void window_size_callback(SDL_Window* window, int width, int height)
|
||||
{
|
||||
(void) window;
|
||||
glViewport(
|
||||
width / 2 - SCREEN_WIDTH / 2,
|
||||
height / 2 - SCREEN_HEIGHT / 2,
|
||||
SCREEN_WIDTH,
|
||||
SCREEN_HEIGHT);
|
||||
}
|
||||
|
||||
void MessageCallback(GLenum source,
|
||||
GLenum type,
|
||||
GLuint id,
|
||||
GLenum severity,
|
||||
GLsizei length,
|
||||
const GLchar* message,
|
||||
const void* userParam)
|
||||
{
|
||||
(void) source;
|
||||
(void) id;
|
||||
(void) length;
|
||||
(void) userParam;
|
||||
fprintf(stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
|
||||
(type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : ""),
|
||||
type, severity, message);
|
||||
}
|
||||
|
||||
void process_prelude(RenderContext *context)
|
||||
{
|
||||
// glfwSetKeyCallback(window, key_callback);
|
||||
// glfwSetFramebufferSizeCallback(window, window_size_callback);
|
||||
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
|
||||
if (!context->program_failed) {
|
||||
glUniform2f(context->resolution_location,
|
||||
SCREEN_WIDTH,
|
||||
SCREEN_HEIGHT);
|
||||
glUniform1f(context->time_location, context->time);
|
||||
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
int64_t cur_time = SDL_GetTicks();
|
||||
if (!context->pause) {
|
||||
context->time += cur_time - context->prev_time;
|
||||
}
|
||||
context->prev_time = cur_time;
|
||||
}
|
133
src/shader.cpp
Normal file
133
src/shader.cpp
Normal file
@ -0,0 +1,133 @@
|
||||
#include "shader.h"
|
||||
|
||||
Shader::Shader()
|
||||
{
|
||||
}
|
||||
|
||||
Shader::~Shader()
|
||||
{
|
||||
}
|
||||
|
||||
void Shader::init(const std::string &vertexCode, const std::string &fragmentCode)
|
||||
{
|
||||
m_vertexCode = vertexCode;
|
||||
m_fragmentCode = fragmentCode;
|
||||
compile();
|
||||
link();
|
||||
}
|
||||
|
||||
void Shader::use()
|
||||
{
|
||||
glUseProgram(m_id);
|
||||
}
|
||||
|
||||
void Shader::setBool(const std::string &name, bool value) const
|
||||
{
|
||||
glUniform1i(glGetUniformLocation(m_id, name.c_str()), (int)value);
|
||||
}
|
||||
|
||||
void Shader::setInt(const std::string &name, int value) const
|
||||
{
|
||||
glUniform1i(glGetUniformLocation(m_id, name.c_str()), value);
|
||||
}
|
||||
|
||||
void Shader::setFloat(const std::string &name, float value) const
|
||||
{
|
||||
glUniform1f(glGetUniformLocation(m_id, name.c_str()), value);
|
||||
}
|
||||
|
||||
void Shader::setVec2(const std::string &name, const glm::vec2 &value) const
|
||||
{
|
||||
glUniform2fv(glGetUniformLocation(m_id, name.c_str()), 1, &value[0]);
|
||||
}
|
||||
void Shader::setVec2(const std::string &name, float x, float y) const
|
||||
{
|
||||
glUniform2f(glGetUniformLocation(m_id, name.c_str()), x, y);
|
||||
}
|
||||
|
||||
void Shader::setVec3(const std::string &name, const glm::vec3 &value) const
|
||||
{
|
||||
glUniform3fv(glGetUniformLocation(m_id, name.c_str()), 1, &value[0]);
|
||||
}
|
||||
void Shader::setVec3(const std::string &name, float x, float y, float z) const
|
||||
{
|
||||
glUniform3f(glGetUniformLocation(m_id, name.c_str()), x, y, z);
|
||||
}
|
||||
|
||||
void Shader::setVec4(const std::string &name, const glm::vec4 &value) const
|
||||
{
|
||||
glUniform4fv(glGetUniformLocation(m_id, name.c_str()), 1, &value[0]);
|
||||
}
|
||||
void Shader::setVec4(const std::string &name, float x, float y, float z, float w) const
|
||||
{
|
||||
glUniform4f(glGetUniformLocation(m_id, name.c_str()), x, y, z, w);
|
||||
}
|
||||
|
||||
void Shader::setMat2(const std::string &name, const glm::mat2 &mat) const
|
||||
{
|
||||
glUniformMatrix2fv(glGetUniformLocation(m_id, name.c_str()), 1, GL_FALSE, &mat[0][0]);
|
||||
}
|
||||
|
||||
void Shader::setMat3(const std::string &name, const glm::mat3 &mat) const
|
||||
{
|
||||
glUniformMatrix3fv(glGetUniformLocation(m_id, name.c_str()), 1, GL_FALSE, &mat[0][0]);
|
||||
}
|
||||
|
||||
void Shader::setMat4(const std::string &name, const glm::mat4 &mat) const
|
||||
{
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_id, name.c_str()), 1, GL_FALSE, &mat[0][0]);
|
||||
}
|
||||
|
||||
void Shader::compile()
|
||||
{
|
||||
const char *vsCode = m_vertexCode.c_str();
|
||||
m_vertexId = glCreateShader(GL_VERTEX_SHADER);
|
||||
glShaderSource(m_vertexId, 1, &vsCode, NULL);
|
||||
glCompileShader(m_vertexId);
|
||||
checkCompileError(m_vertexId, "Vertex Shader");
|
||||
|
||||
const char *fsCode = m_fragmentCode.c_str();
|
||||
m_fragmentId = glCreateShader(GL_FRAGMENT_SHADER);
|
||||
glShaderSource(m_fragmentId, 1, &fsCode, NULL);
|
||||
glCompileShader(m_fragmentId);
|
||||
checkCompileError(m_fragmentId, "Fragment Shader");
|
||||
}
|
||||
|
||||
void Shader::link()
|
||||
{
|
||||
m_id = glCreateProgram();
|
||||
glAttachShader(m_id, m_vertexId);
|
||||
glAttachShader(m_id, m_fragmentId);
|
||||
glLinkProgram(m_id);
|
||||
checkLinkingError();
|
||||
glDeleteShader(m_vertexId);
|
||||
glDeleteShader(m_fragmentId);
|
||||
}
|
||||
|
||||
void Shader::checkCompileError(unsigned int shader, const std::string type)
|
||||
{
|
||||
int success;
|
||||
char infoLog[1024];
|
||||
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
|
||||
if (!success)
|
||||
{
|
||||
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
|
||||
std::cout << "Shader: Error compiling " << type << ":" << std::endl
|
||||
<< infoLog
|
||||
<< std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void Shader::checkLinkingError()
|
||||
{
|
||||
int success;
|
||||
char infoLog[1024];
|
||||
glGetProgramiv(m_id, GL_LINK_STATUS, &success);
|
||||
if (!success)
|
||||
{
|
||||
glGetProgramInfoLog(m_id, 1024, NULL, infoLog);
|
||||
std::cout << "Shader: Error linking shader program: " << std::endl
|
||||
<< infoLog
|
||||
<< std::endl;
|
||||
}
|
||||
}
|
50
src/shaders/simple.fs
Normal file
50
src/shaders/simple.fs
Normal file
@ -0,0 +1,50 @@
|
||||
#version 410 core
|
||||
|
||||
// Output color of the fragment (pixel)
|
||||
out vec4 FragColor; // RGBA color for the fragment, where A is the alpha (opacity)
|
||||
|
||||
in vec3 vertexPos;
|
||||
in vec3 vertexNormal;
|
||||
in vec2 TexCoords;
|
||||
|
||||
uniform vec3 lightPos;
|
||||
uniform vec3 viewPos;
|
||||
|
||||
// From Object Renderer
|
||||
|
||||
uniform vec3 ambientColor;
|
||||
uniform vec3 diffuseColor;
|
||||
uniform vec3 specularColor;
|
||||
|
||||
uniform float ambientStrength;
|
||||
uniform float specularStrength;
|
||||
|
||||
uniform sampler2D diffuseTex;
|
||||
uniform bool useTexture;
|
||||
|
||||
#define LIGHT_COLOR vec3(1.0, 1.0, 1.0)
|
||||
|
||||
void main()
|
||||
{
|
||||
// Lighting vectors
|
||||
vec3 lightDir = normalize(lightPos - vertexPos);
|
||||
vec3 norm = normalize(vertexNormal);
|
||||
vec3 viewDir = normalize(viewPos - vertexPos);
|
||||
vec3 reflectDir = reflect(-lightDir, norm);
|
||||
|
||||
// Phong components
|
||||
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
|
||||
vec3 specular = specularStrength * spec * specularColor;
|
||||
|
||||
float diff = max(dot(norm, lightDir), 0.0);
|
||||
vec3 diffuse = diff * diffuseColor;
|
||||
|
||||
vec3 ambient = ambientStrength * ambientColor;
|
||||
|
||||
vec3 texColor = (useTexture)
|
||||
? texture(diffuseTex, TexCoords).rgb
|
||||
: diffuseColor;
|
||||
|
||||
vec3 result = (ambient + diffuse + specular) * texColor;
|
||||
FragColor = vec4(result, 1.0);
|
||||
}
|
29
src/shaders/simple.vs
Normal file
29
src/shaders/simple.vs
Normal file
@ -0,0 +1,29 @@
|
||||
#version 460 core
|
||||
|
||||
// Input vertex attributes
|
||||
layout (location = 0) in vec3 position; // Vertex position in local space (model space)
|
||||
layout (location = 1) in vec3 normal; // vertex normal
|
||||
layout (location = 2) in vec2 texCoord; // Vertex texture uv
|
||||
|
||||
// Output to fragment shader
|
||||
out vec3 vertexPos;
|
||||
out vec3 vertexNormal;
|
||||
out vec2 TexCoords;
|
||||
|
||||
// Uniforms for transformation matrices
|
||||
uniform mat4 u_model; // Model matrix: transforms from local space to world space
|
||||
uniform mat4 u_view; // View matrix: transforms from world space to camera space (view space)
|
||||
uniform mat4 u_projection; // Projection matrix: transforms from camera space to clip space
|
||||
|
||||
void main()
|
||||
{
|
||||
vertexPos = vec3(u_model * vec4(position, 1.0));
|
||||
|
||||
mat3 normalMatrix = mat3(transpose(inverse(u_model)));
|
||||
vertexNormal = normalMatrix * normal;
|
||||
// vertexNormal = normal;
|
||||
|
||||
TexCoords = texCoord;
|
||||
|
||||
gl_Position = u_projection * u_view * vec4(vertexPos, 1.0);
|
||||
}
|
36
src/texture.cpp
Normal file
36
src/texture.cpp
Normal file
@ -0,0 +1,36 @@
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <GL/glew.h>
|
||||
#include "texture.h"
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#include "stb_image.h"
|
||||
|
||||
std::unique_ptr<Texture> Texture::LoadFile(const std::string& filename) {
|
||||
auto texture = std::make_unique<Texture>();
|
||||
|
||||
int w, h, c;
|
||||
unsigned char *data = stbi_load(filename.c_str(), &w, &h, &c, 0);
|
||||
if (!data) {
|
||||
std::cerr << "ERROR: Failed to load texture under '" << filename << "'" << std::endl;
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
glGenTextures(1, &texture.get()->m_id);
|
||||
glBindTexture(GL_TEXTURE_2D, texture.get()->m_id);
|
||||
|
||||
// TODO: configure properly
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
|
||||
// TODO: automatically detect values for this function
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
|
||||
glGenerateMipmap(GL_TEXTURE_2D);
|
||||
|
||||
std::cout << "Loaded texture under '" << filename << "' with size of " << sizeof(data) << " bytes" << std::endl;
|
||||
stbi_image_free(data);
|
||||
|
||||
return std::move(texture);
|
||||
}
|
151
src/vertex.cpp
Normal file
151
src/vertex.cpp
Normal file
@ -0,0 +1,151 @@
|
||||
#include <GL/glew.h>
|
||||
|
||||
#include "vertex.h"
|
||||
|
||||
#define BLOCK_SIZE 0.5f
|
||||
|
||||
Point::Point(glm::vec3 position, glm::vec3 normal, glm::vec4 color)
|
||||
{
|
||||
m_position = position;
|
||||
m_normal = normal;
|
||||
m_color = color;
|
||||
}
|
||||
|
||||
Vertices::Vertices()
|
||||
{
|
||||
m_items = std::vector<Point>();
|
||||
|
||||
glGenVertexArrays(1, &m_vao);
|
||||
glGenBuffers(1, &m_vbo);
|
||||
glGenBuffers(1, &m_ebo);
|
||||
|
||||
glBindVertexArray(m_vao);
|
||||
|
||||
// VBO (vertex buffer)
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
|
||||
|
||||
// EBO (index buffer)
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
|
||||
|
||||
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
|
||||
// glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(triangleIndices), triangleIndices, GL_STATIC_DRAW);
|
||||
|
||||
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Point), (void*)0);
|
||||
glEnableVertexAttribArray(0);
|
||||
|
||||
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Point), (void*)(3 * sizeof(float)));
|
||||
glEnableVertexAttribArray(1);
|
||||
|
||||
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Point), (void*)(6 * sizeof(float)));
|
||||
glEnableVertexAttribArray(2);
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
// Call this after you finish adding vertices (or call it each time after PushBlock)
|
||||
void Vertices::Upload()
|
||||
{
|
||||
glBindVertexArray(m_vao);
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, m_items.size() * sizeof(Point), m_items.data(), GL_DYNAMIC_DRAW);
|
||||
|
||||
// Upload indices
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indices.size() * sizeof(unsigned int), m_indices.data(), GL_STATIC_DRAW);
|
||||
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
// void Vertices::PushBlock(const Block& block)
|
||||
// {
|
||||
// // 1 face
|
||||
// m_items.emplace_back(block.Position(), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, -BLOCK_SIZE, 0.f), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 2 face
|
||||
// m_items.emplace_back(block.Position(), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, 0.f), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 3 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, -BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
|
||||
// // 4 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
|
||||
// // 5 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position(), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 6 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, -BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 7 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, 0.f), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 8 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, -BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 9 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, 0.f), block.Color());
|
||||
// m_items.emplace_back(block.Position(), block.Color());
|
||||
|
||||
// // 10 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, 0.f, 0.f), block.Color());
|
||||
|
||||
// // 11 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, BLOCK_SIZE, 0.f), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, BLOCK_SIZE, 0.f), block.Color());
|
||||
|
||||
// // 12 face
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(0.f, BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, BLOCK_SIZE, -BLOCK_SIZE), block.Color());
|
||||
// m_items.emplace_back(block.Position() + glm::vec3(BLOCK_SIZE, BLOCK_SIZE, 0.f), block.Color());
|
||||
// }
|
||||
|
||||
void Vertices::PushVertex(const Point& point)
|
||||
{
|
||||
m_items.push_back(point);
|
||||
}
|
||||
|
||||
void Vertices::PushIndex(unsigned int index)
|
||||
{
|
||||
m_indices.push_back(index);
|
||||
}
|
||||
|
||||
void Vertices::Bind()
|
||||
{
|
||||
glBindVertexArray(m_vao);
|
||||
}
|
||||
|
||||
void Vertices::Unbind()
|
||||
{
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
void Vertices::Draw()
|
||||
{
|
||||
Bind();
|
||||
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(m_indices.size()), GL_UNSIGNED_INT, 0);
|
||||
Unbind();
|
||||
}
|
Reference in New Issue
Block a user