diff options
Diffstat (limited to 'source')
-rw-r--r-- | source/lessons/blending/main.cpp | 942 | ||||
-rw-r--r-- | source/lessons/blending/shaders/blend_test.fs.glsl | 14 | ||||
-rw-r--r-- | source/lessons/blending/shaders/depth_test.fs.glsl | 30 | ||||
-rw-r--r-- | source/lessons/blending/shaders/depth_test.vs.glsl | 19 | ||||
-rw-r--r-- | source/lessons/face_culling/main.cpp | 962 | ||||
-rw-r--r-- | source/lessons/face_culling/shaders/blend_test.fs.glsl | 14 | ||||
-rw-r--r-- | source/lessons/face_culling/shaders/depth_test.fs.glsl | 30 | ||||
-rw-r--r-- | source/lessons/face_culling/shaders/depth_test.vs.glsl | 19 | ||||
-rw-r--r-- | source/main.cpp | 311 | ||||
-rw-r--r-- | source/shaders/fbo.fs.glsl | 72 | ||||
-rw-r--r-- | source/shaders/fbo.vs.glsl | 10 |
11 files changed, 2346 insertions, 77 deletions
diff --git a/source/lessons/blending/main.cpp b/source/lessons/blending/main.cpp new file mode 100644 index 0000000..2f07c0e --- /dev/null +++ b/source/lessons/blending/main.cpp @@ -0,0 +1,942 @@ +#include <stdio.h> +#include <SDL2/SDL.h> +#include <glad/glad.h> +#include <assimp/Importer.hpp> +#include <assimp/scene.h> +#include <assimp/postprocess.h> +#include <vector> + +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +/* @lookup: +* - I do not understand how floating point numbers work, so I should probably look into that. +* - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied. +* I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet. +* Revisit the derivation for the normal matrix some time in the future. +* - Lookup the derivation of the formula for reflecting a vector about a normal. I am doing that for specular lighting, but the learnopengl tutorial +* just uses a glsl reflect formula, and at the time of writing it is also very late so I am not in the mood or position to look into it at present. +* - One of the things I have observed with specular lights is that the circle/specular highlight follows the camera (me) when I move. I would like to figure +* out a way by which this does not happen and it remains fixed on the object, at the angle at which it hits. All of this will be made complicated by the fact +* that ofcourse everything is actually happening from the cameras' perspective. I would still love to figure this out. +*/ + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +typedef int8_t s8; +typedef int16_t s16; +typedef int32_t s32; +typedef int64_t s64; + +typedef float r32; +typedef double r64; + +typedef u8 b8; + +#include "math.h" + +// =========== Shader Loading ============= + +unsigned int gl_create_vertex_shader(char* vertex_shader_source) +{ + unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); + glCompileShader(vertex_shader); + + int success; + char info_log[512]; + glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(vertex_shader, 512, NULL, info_log); + printf("================================\n"); + printf("vertex shader compilation failed:\n%s\n", info_log); + } + + return vertex_shader; +} + +unsigned int gl_create_fragment_shader(char* fragment_shader_source) +{ + unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); + glCompileShader(fragment_shader); + + int success; + char info_log[512]; + glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment_shader, 512, NULL, info_log); + printf("================================\n"); + printf("fragment shader compilation failed:\n%s\n", info_log); + } + + return fragment_shader; +} + +unsigned int gl_create_shader_program(unsigned int vertex_shader, unsigned int fragment_shader) +{ + unsigned int shader_program = glCreateProgram(); + + glAttachShader(shader_program, vertex_shader); + glAttachShader(shader_program, fragment_shader); + glLinkProgram(shader_program); + + int success; + char info_log[512]; + glGetProgramiv(shader_program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(shader_program, 512, NULL, info_log); + printf("================================\n"); + printf("shader program linking failed:\n%s\n", info_log); + } + + glDeleteShader(vertex_shader); + glDeleteShader(fragment_shader); + + return shader_program; +} + +unsigned int gl_shader_program(char* vertex_shader_source, char* fragment_shader_source) +{ + unsigned int vertex_shader = gl_create_vertex_shader(vertex_shader_source); + unsigned int fragment_shader = gl_create_fragment_shader(fragment_shader_source); + unsigned int shader_program = gl_create_shader_program(vertex_shader, fragment_shader); + + return shader_program; +} + +Mat4 camera_create4m(Vec3 camera_pos, Vec3 camera_look, Vec3 camera_up) +{ + // @note: We do this because this allows the camera to have the axis it looks at + // inwards be the +z axis. + // If we did not do this, then the inward axis the camera looks at would be negative. + // I am still learning from learnopengl.com but I imagine that this was done for conveniences' sake. + Vec3 camera_forward_dir = normalize3v(subtract3v(camera_pos, camera_look)); + Vec3 camera_right_dir = normalize3v(cross_multiply3v(camera_up, camera_forward_dir)); + Vec3 camera_up_dir = normalize3v(cross_multiply3v(camera_forward_dir, camera_right_dir)); + + Mat4 res = lookat4m(camera_up_dir, camera_forward_dir, camera_right_dir, camera_pos); + + return res; +} + +Vec3 camera_look_around(r32 angle_pitch, r32 angle_yaw) +{ + Vec3 camera_look = {0.0}; + camera_look.x = cosf(angle_yaw) * cosf(angle_pitch); + camera_look.y = sinf(angle_pitch); + camera_look.z = sinf(angle_yaw) * cosf(angle_pitch); + camera_look = normalize3v(camera_look); + + return camera_look; +} + +s32 gl_load_texture(u32 texture_id, const char* path) +{ + s32 width, height, nrChannels; + unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texture_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", path); + stbi_image_free(data); + } + + return texture_id; +} + +// =================== Model Loading ======================== +// This section contains a whole host of things: +// 1. classes +// 2. std::vectors +// 3. std::strings +// that I have only used as a glue for I did not know if I had the model loading setup properly. +// @todo: replace these things eventually. For now the goal is to complete learnopengl + +s32 TextureFromFile(const char* filepath, std::string directory) +{ + std::string filename = std::string(filepath); + filename = directory + '/' + filename; + + u32 texid; + glGenTextures(1, &texid); + + s32 width, height, nrChannels; + unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texid); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", filepath); + stbi_image_free(data); + } + + return texid; +} + +enum TextureType { TextureDiffuse=0, TextureSpecular }; + +struct Vertex { + Vec3 position; + Vec3 normal; + Vec2 texture; +}; + +struct Texture { + u32 id; + enum TextureType type; + std::string fname; +}; + +class Mesh { + public: + std::vector<Vertex> vertices; + std::vector<u32> indices; + std::vector<Texture> textures; + + u32 vao; + u32 vbo; + u32 ebo; + + Mesh(std::vector<Vertex> vertices, std::vector<u32> indices, std::vector<Texture> textures) + { + this->vertices = vertices; + this->indices = indices; + this->textures = textures; + + // setup mesh shader stuff + glGenVertexArrays(1, &vao); + glGenBuffers(1, &vbo); + glGenBuffers(1, &ebo); + + glBindVertexArray(vao); + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(struct Vertex), &(this->vertices[0]), GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(u32), &(this->indices[0]), GL_STATIC_DRAW); + + // position + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); + // normal + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); + // texture + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texture)); + + glBindVertexArray(0); + } + + void draw(u32 shader_program) + { + glUseProgram(shader_program); + + u32 diffuse_num = 1; + u32 specular_num = 1; + char tex_unit_name[64]; + // set shininess + s32 mat_shine_loc = glGetUniformLocation(shader_program, "material.shininess"); + glUniform1f(mat_shine_loc, 32.0f); + + for (u32 i=0; i<textures.size(); i++) + { + struct Texture curr_tex = textures[i]; + if (curr_tex.type == TextureDiffuse) + { + sprintf(tex_unit_name, "material.diffuse[%i]", diffuse_num); + } + else if (curr_tex.type == TextureSpecular) + { + sprintf(tex_unit_name, "material.diffuse[%i]", specular_num); + } + + glActiveTexture(GL_TEXTURE0 + i); + s32 tex_unit_loc = glGetUniformLocation(shader_program, tex_unit_name); + glUniform1i(tex_unit_loc, i); + glBindTexture(GL_TEXTURE_2D, curr_tex.id); + } + glActiveTexture(GL_TEXTURE0); + + glBindVertexArray(vao); + glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); + glBindVertexArray(0); + } +}; + +class Model +{ + public: + Model(std::string path) + { + load_model(path); + } + void draw(u32 shader_program); + private: + std::vector<Texture> loaded_textures; + std::vector<Mesh> meshes; + std::string directory; + + void load_model(std::string path); + void process_node(aiNode *node, const aiScene *scene); + Mesh process_mesh(aiMesh *mesh, const aiScene *scene); + std::vector<Texture> load_material_textures(aiMaterial *mat, aiTextureType type, TextureType type_name); +}; + +void Model::draw(u32 shader_program) +{ + for (int i=0; i < meshes.size(); i++) + { + meshes[i].draw(shader_program); + } +} + +void Model::load_model(std::string path) +{ + Assimp::Importer import; + const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); + + if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) + { + printf("error loading model :%s\n", import.GetErrorString()); + return; + } + + directory = path.substr(0, path.find_last_of('/')); + process_node(scene->mRootNode, scene); +} + +void Model::process_node(aiNode *node, const aiScene *scene) +{ + for (int i=0; i < node->mNumMeshes; i++) + { + aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; + meshes.push_back(process_mesh(mesh, scene)); + } + + for (int i=0; i<node->mNumChildren; i++) + { + process_node(node->mChildren[i], scene); + } +} + +Mesh Model::process_mesh(aiMesh *mesh, const aiScene *scene) +{ + std::vector<Vertex> vertices; + std::vector<u32> indices; + std::vector<Texture> textures; + + for (u32 i=0; i < mesh->mNumVertices; i++) + { + Vec3 position; + position.x = mesh->mVertices[i].x; + position.y = mesh->mVertices[i].y; + position.z = mesh->mVertices[i].z; + + Vec3 normal; + normal.x = mesh->mNormals[i].x; + normal.y = mesh->mNormals[i].y; + normal.z = mesh->mNormals[i].z; + + Vec2 texture = {0, 0}; + if (mesh->mTextureCoords[0]) + { + texture.x = mesh->mTextureCoords[0][i].x; + texture.y = mesh->mTextureCoords[0][i].y; + } + + struct Vertex vertex; + vertex.position = position; + vertex.normal = normal; + vertex.texture = texture; + + vertices.push_back(vertex); + } + // process indices + for (u32 i = 0; i < mesh->mNumFaces; i++) + { + aiFace face = mesh->mFaces[i]; + for(u32 j = 0; j < face.mNumIndices; j++) + { + indices.push_back(face.mIndices[j]); + } + } + // process material + if (mesh->mMaterialIndex >= 0) + { + aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; + std::vector<Texture> diffuse_maps = load_material_textures(material, aiTextureType_DIFFUSE, TextureDiffuse); + textures.insert(textures.end(), diffuse_maps.begin(), diffuse_maps.end()); + std::vector<Texture> specular_maps = load_material_textures(material, aiTextureType_SPECULAR, TextureSpecular); + textures.insert(textures.end(), specular_maps.begin(), specular_maps.end()); + } + + return Mesh(vertices, indices, textures); +} + +std::vector<Texture> Model::load_material_textures(aiMaterial *mat, aiTextureType type, TextureType tex_type) +{ + std::vector<Texture> textures; + for(u32 i=0; i<mat->GetTextureCount(type); i++) + { + bool load_texture = true; + aiString str; + mat->GetTexture(type, i, &str); + const char* fname = str.C_Str(); + + for (s32 j=0; j<loaded_textures.size(); j++) + { + if (std::strcmp(loaded_textures[j].fname.data(), fname) == 0) + { + load_texture = false; + textures.push_back(loaded_textures[j]); + break; + } + } + if (load_texture) + { + Texture texture; + texture.id = TextureFromFile(fname, directory); + texture.type = tex_type; + texture.fname = std::string(fname); + textures.push_back(texture); + loaded_textures.push_back(texture); + } + } + + return textures; +} + +int main(int argc, char* argv[]) +{ + + // ============ END ============ + int width = 1024; + int height = 768; + + if (SDL_Init(SDL_INIT_VIDEO) != 0) + { + printf("Error initialising SDL2: %s\n", SDL_GetError()); + return 0; + }; + + // set opengl version and profile + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); + + // initialise window with opengl flag + SDL_Window* window = SDL_CreateWindow("SDL Test", + 50, + 50, + width, + height, + SDL_WINDOW_OPENGL); + + SDL_SetRelativeMouseMode(SDL_TRUE); + + // create an opengl context + SDL_GLContext context = SDL_GL_CreateContext(window); + if (!context) + { + printf("OpenGL context creation failed: %s\n", SDL_GetError()); + return -1; + } + + + // load glad + if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { + printf("Failed to initialize Glad\n"); + return 1; + } + + // filesystem playground stuff + size_t read_count; + char* vertex_source = (char*)SDL_LoadFile("./source/shaders/depth_test.vs.glsl", &read_count); + char* fragment_source = (char*)SDL_LoadFile("./source/shaders/depth_test.fs.glsl", &read_count); + char* blend_shader_source = (char*)SDL_LoadFile("./source/shaders/blend_test.fs.glsl", &read_count); + + u32 shader_program = gl_shader_program(vertex_source, fragment_source); + u32 blend_shader_program = gl_shader_program(vertex_source, blend_shader_source); + + printf("Successfully compiled shaders.\n"); + + float cubeVertices[] = { + // positions // texture Coords + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, + + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, + -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, + + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, + + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, + -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f + }; + float planeVertices[] = { + // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, + -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, + + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, + 5.0f, -0.5f, -5.0f, 2.0f, 2.0f + }; + float quadVertices[] = { + // positions // texture Coords + -0.5f, -0.5f, 0.0f, 0.0f, + 0.5f, -0.5f, 1.0f, 0.0f, + 0.5f, 0.5f, 1.0f, 1.0f, + 0.5f, 0.5f, 1.0f, 1.0f, + -0.5f, 0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.0f, 0.0f, + }; + stbi_set_flip_vertically_on_load(1); + + u32 cube_vao, cube_vbo, plane_vao, plane_vbo, quad_vao, quad_vbo; + + glGenVertexArrays(1, &cube_vao); + glGenBuffers(1, &cube_vbo); + + glBindVertexArray(cube_vao); + glBindBuffer(GL_ARRAY_BUFFER, cube_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); + glBindVertexArray(0); + + glGenVertexArrays(1, &plane_vao); + glGenBuffers(1, &plane_vbo); + + glBindVertexArray(plane_vao); + glBindBuffer(GL_ARRAY_BUFFER, plane_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); + glBindVertexArray(0); + + glGenVertexArrays(1, &quad_vao); + glGenBuffers(1, &quad_vbo); + + glBindVertexArray(quad_vao); + glBindBuffer(GL_ARRAY_BUFFER, quad_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2*sizeof(float))); + glBindVertexArray(0); + + u32 cube_tex_id; + glGenTextures(1, &cube_tex_id); + glActiveTexture(GL_TEXTURE0); + gl_load_texture(cube_tex_id, "assets/container.jpg"); + + u32 plane_tex_id; + glGenTextures(1, &plane_tex_id); + glActiveTexture(GL_TEXTURE1); + gl_load_texture(plane_tex_id, "assets/smiling.png"); + + u32 window_tex_id; + glGenTextures(1, &window_tex_id); + glActiveTexture(GL_TEXTURE2); + { + u32 texture_id = window_tex_id; + char *path = "assets/window.png"; + s32 width, height, nrChannels; + unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texture_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", path); + stbi_image_free(data); + } + +} + + // objects + Vec3 model_translations[] = { + Vec3{ 0.5, 0.0, 0.0}, //origin square + Vec3{ -1.0, 0.0, -1.0}, // plane + Vec3{ -1.0, 0.0, -0.5}, // window between squares + Vec3{ 0.0, 0.0, 3.0}, //window infront of origin square + Vec3{ -2.5, 0.0, -0.5}, // square to the left + Vec3{ -1.0, 0.0, -1.5}, // random square behind window between squares + }; + + r32 FOV = 90.0; + r32 time_curr; + r32 time_prev = SDL_GetTicks64() / 100.0; + // camera stuff + Vec3 camera_pos = Vec3{ 0.0, 0.0, 10.0f}; + Vec3 preset_up_dir = Vec3{ 0.0, 1.0, 0.0 }; + + r32 angle_yaw, angle_pitch, angle_roll; + angle_pitch = (r32)To_Radian(0.0f); + angle_yaw = (r32)-To_Radian(90.0f); + + Vec3 camera_look = camera_look_around(angle_pitch, angle_yaw); + + // @todo: remove this, I dont like this and think that this is unnecessary + Vec3 camera_look_increment; + r32 camera_speed = 0.5f; + + Mat4 view = camera_create4m(camera_pos, camera_look, preset_up_dir); + + Mat4 proj = perspective4m((r32)To_Radian(90.0), (r32)width / (r32)height, 0.1f, 100.0f); + // needs this + glUseProgram(shader_program); + uint32_t proj_loc = glGetUniformLocation(shader_program, "Projection"); + glUniformMatrix4fv(proj_loc, 1, GL_TRUE, proj.buffer); + + glUseProgram(blend_shader_program); + proj_loc = glGetUniformLocation(blend_shader_program, "Projection"); + glUniformMatrix4fv(proj_loc, 1, GL_TRUE, proj.buffer); + + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glDepthFunc(GL_LESS); + + u8 game_running = true; + + u8 hold_lshift = false; + u8 move_w = false; + u8 move_a = false; + u8 move_s = false; + u8 move_d = false; + + while(game_running) + { + + // frame delta + time_curr = SDL_GetTicks64() / 100.0; + r32 time_delta = time_curr - time_prev; + + r32 camera_speed_adjusted = time_delta * camera_speed; + camera_look_increment = scaler_multiply3v(camera_look, camera_speed_adjusted); + + SDL_Event ev; + while(SDL_PollEvent(&ev)) + { + + // INPUT + switch (ev.type) + { + case (SDL_QUIT): + { + game_running = false; + } break; + case (SDL_KEYDOWN): + { + if (ev.key.keysym.sym == SDLK_LSHIFT) + { + hold_lshift = true; + } + if (ev.key.keysym.sym == SDLK_w) + { + move_w = true; + } + if (ev.key.keysym.sym == SDLK_s) + { + move_s = true; + } + if (ev.key.keysym.sym == SDLK_a) + { + move_a = true; + } + if (ev.key.keysym.sym == SDLK_d) + { + move_d = true; + } + } break; + case (SDL_KEYUP): + { + if (ev.key.keysym.sym == SDLK_LSHIFT) + { + hold_lshift = false; + } + if (ev.key.keysym.sym == SDLK_w) + { + move_w = false; + } + if (ev.key.keysym.sym == SDLK_s) + { + move_s = false; + } + if (ev.key.keysym.sym == SDLK_a) + { + move_a = false; + } + if (ev.key.keysym.sym == SDLK_d) + { + move_d = false; + } + } break; + case (SDL_MOUSEMOTION): + { + SDL_MouseMotionEvent mouse_event = ev.motion; + r32 x_motion = (r32)mouse_event.xrel; + r32 y_motion = (r32)mouse_event.yrel; + if (x_motion != 0.0 || y_motion != 0.0) + { + angle_yaw = angle_yaw + To_Radian(x_motion * 0.1f); + angle_pitch = clampf(angle_pitch + To_Radian(-y_motion * 0.1f), To_Radian(-89.0f), To_Radian(89.0f)); + + camera_look = camera_look_around(angle_pitch, angle_yaw); + } + } break; + default: + { + break; + } + } + } + + // PROCESS + if (move_w) + { + camera_pos = add3v(camera_pos, camera_look_increment); + } + if (move_s) + { + camera_pos = subtract3v(camera_pos, camera_look_increment); + } + if (move_a) + { + Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); + Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); + camera_pos = add3v(camera_pos, camera_right_scaled); + } + if (move_d) + { + Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); + Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); + camera_pos = subtract3v(camera_pos, camera_right_scaled); + } + view = camera_create4m(camera_pos, add3v(camera_pos, camera_look), preset_up_dir); + + // object shader program stuff + glUseProgram(shader_program); + uint32_t view_loc = glGetUniformLocation(shader_program, "View"); + glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer); + + glUseProgram(blend_shader_program); + view_loc = glGetUniformLocation(blend_shader_program, "View"); + glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer); + + time_prev = time_curr; + + // OUTPUT + glClearColor(1.0f, 0.6f, .6f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + glDisable(GL_BLEND); + { //plane + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 1); + Vec3 translation_iter = model_translations[1]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(plane_vao); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + {//origin square + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[0]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + {//square to the left + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[4]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + {//random square behind window between squares + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[5]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + // @note: this is to demonstrate the limitations of blending with the depth buffer. + // Currently, this will show a weird behavior where since we render the transparent object + // closest to the camera first, the second window, further from the player will be discarded by the + // depth buffer and will be invisible. + // This is a limiation of transparent objects with the depth buffer. This does not happen with opaque objects. + // + // The "fix" if we can even call it that, is to render objects in order, furthest first and closest second, in layers. + + {//window infront of origin square + glUseProgram(blend_shader_program); + s32 tex_id_loc = glGetUniformLocation(blend_shader_program, "TexId"); + glUniform1i(tex_id_loc, 2); + Vec3 translation_iter = model_translations[3]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(quad_vao); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + {//window between squares + glUseProgram(blend_shader_program); + s32 tex_id_loc = glGetUniformLocation(blend_shader_program, "TexId"); + glUniform1i(tex_id_loc, 2); + Vec3 translation_iter = model_translations[2]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(quad_vao); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + SDL_GL_SwapWindow(window); + } + + // opengl free calls + //glDeleteVertexArrays(1, &VAO); + //glDeleteBuffers(1, &VBO); + glDeleteProgram(shader_program); + glDeleteProgram(blend_shader_program); + + // sdl free calls + SDL_GL_DeleteContext(context); + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; +} diff --git a/source/lessons/blending/shaders/blend_test.fs.glsl b/source/lessons/blending/shaders/blend_test.fs.glsl new file mode 100644 index 0000000..23daa14 --- /dev/null +++ b/source/lessons/blending/shaders/blend_test.fs.glsl @@ -0,0 +1,14 @@ +#version 330 core + + +in vec2 TexCoords; +in vec3 VertexWorldPos; +uniform sampler2D TexId; +uniform vec4 hlt_color; +out vec4 FragColor; + +void main() { + vec4 tex = texture(TexId, TexCoords); + + FragColor = tex; +} diff --git a/source/lessons/blending/shaders/depth_test.fs.glsl b/source/lessons/blending/shaders/depth_test.fs.glsl new file mode 100644 index 0000000..796d849 --- /dev/null +++ b/source/lessons/blending/shaders/depth_test.fs.glsl @@ -0,0 +1,30 @@ +#version 330 core + + +in vec2 TexCoords; +in vec3 VertexWorldPos; +uniform sampler2D TexId; +out vec4 FragColor; + +uniform float near = 0.1f; +uniform float far = 100.0f; + +/* @note +float linear_fragment_depth = MakeDepthLinear(non_linear_fragment_depth); +float scaled_lfd = linear_fragment_depth/far; + +gives us the z value in eye space. +This is purely for learning purposes. +The equation used in MakeDepthLinear is derived from the PerspectiveProjectionMatrix. +Take a look at the equation for that in the codebase +or here: https://www.songho.ca/opengl/gl_projectionmatrix.html +*/ +float MakeDepthLinear(float depth) { + float ndc = 2.0f*depth - 1; + float linear_depth = (2.0 * far * near)/(far + near - ndc*(far - near)); + return linear_depth; +} + +void main() { + FragColor = texture(TexId, TexCoords); +} diff --git a/source/lessons/blending/shaders/depth_test.vs.glsl b/source/lessons/blending/shaders/depth_test.vs.glsl new file mode 100644 index 0000000..b3b81cc --- /dev/null +++ b/source/lessons/blending/shaders/depth_test.vs.glsl @@ -0,0 +1,19 @@ +#version 330 core +layout(location=0) in vec3 aPos; +layout(location=1) in vec2 aTex; + +uniform mat4 Model; +uniform mat4 View; +uniform mat4 Projection; + +out vec2 TexCoords; +out vec3 VertexWorldPos; + +// @note: I still do not fully understand how the FragNormal calculation works. Need to make sure I intuitively +// get that + +void main() { + gl_Position = Projection*View*Model*vec4(aPos, 1.0); + VertexWorldPos = vec3(Model * vec4(aPos, 1.0)); + TexCoords = aTex; +}; diff --git a/source/lessons/face_culling/main.cpp b/source/lessons/face_culling/main.cpp new file mode 100644 index 0000000..7a05897 --- /dev/null +++ b/source/lessons/face_culling/main.cpp @@ -0,0 +1,962 @@ +#include <stdio.h> +#include <SDL2/SDL.h> +#include <glad/glad.h> +#include <assimp/Importer.hpp> +#include <assimp/scene.h> +#include <assimp/postprocess.h> +#include <vector> + +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +/* @lookup: +* - I do not understand how floating point numbers work, so I should probably look into that. +* - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied. +* I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet. +* Revisit the derivation for the normal matrix some time in the future. +* - Lookup the derivation of the formula for reflecting a vector about a normal. I am doing that for specular lighting, but the learnopengl tutorial +* just uses a glsl reflect formula, and at the time of writing it is also very late so I am not in the mood or position to look into it at present. +* - One of the things I have observed with specular lights is that the circle/specular highlight follows the camera (me) when I move. I would like to figure +* out a way by which this does not happen and it remains fixed on the object, at the angle at which it hits. All of this will be made complicated by the fact +* that ofcourse everything is actually happening from the cameras' perspective. I would still love to figure this out. +*/ + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +typedef int8_t s8; +typedef int16_t s16; +typedef int32_t s32; +typedef int64_t s64; + +typedef float r32; +typedef double r64; + +typedef u8 b8; + +#include "math.h" + +// =========== Shader Loading ============= + +unsigned int gl_create_vertex_shader(char* vertex_shader_source) +{ + unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); + glCompileShader(vertex_shader); + + int success; + char info_log[512]; + glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(vertex_shader, 512, NULL, info_log); + printf("================================\n"); + printf("vertex shader compilation failed:\n%s\n", info_log); + } + + return vertex_shader; +} + +unsigned int gl_create_fragment_shader(char* fragment_shader_source) +{ + unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); + glCompileShader(fragment_shader); + + int success; + char info_log[512]; + glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment_shader, 512, NULL, info_log); + printf("================================\n"); + printf("fragment shader compilation failed:\n%s\n", info_log); + } + + return fragment_shader; +} + +unsigned int gl_create_shader_program(unsigned int vertex_shader, unsigned int fragment_shader) +{ + unsigned int shader_program = glCreateProgram(); + + glAttachShader(shader_program, vertex_shader); + glAttachShader(shader_program, fragment_shader); + glLinkProgram(shader_program); + + int success; + char info_log[512]; + glGetProgramiv(shader_program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(shader_program, 512, NULL, info_log); + printf("================================\n"); + printf("shader program linking failed:\n%s\n", info_log); + } + + glDeleteShader(vertex_shader); + glDeleteShader(fragment_shader); + + return shader_program; +} + +unsigned int gl_shader_program(char* vertex_shader_source, char* fragment_shader_source) +{ + unsigned int vertex_shader = gl_create_vertex_shader(vertex_shader_source); + unsigned int fragment_shader = gl_create_fragment_shader(fragment_shader_source); + unsigned int shader_program = gl_create_shader_program(vertex_shader, fragment_shader); + + return shader_program; +} + +Mat4 camera_create4m(Vec3 camera_pos, Vec3 camera_look, Vec3 camera_up) +{ + // @note: We do this because this allows the camera to have the axis it looks at + // inwards be the +z axis. + // If we did not do this, then the inward axis the camera looks at would be negative. + // I am still learning from learnopengl.com but I imagine that this was done for conveniences' sake. + Vec3 camera_forward_dir = normalize3v(subtract3v(camera_pos, camera_look)); + Vec3 camera_right_dir = normalize3v(cross_multiply3v(camera_up, camera_forward_dir)); + Vec3 camera_up_dir = normalize3v(cross_multiply3v(camera_forward_dir, camera_right_dir)); + + Mat4 res = lookat4m(camera_up_dir, camera_forward_dir, camera_right_dir, camera_pos); + + return res; +} + +Vec3 camera_look_around(r32 angle_pitch, r32 angle_yaw) +{ + Vec3 camera_look = {0.0}; + camera_look.x = cosf(angle_yaw) * cosf(angle_pitch); + camera_look.y = sinf(angle_pitch); + camera_look.z = sinf(angle_yaw) * cosf(angle_pitch); + camera_look = normalize3v(camera_look); + + return camera_look; +} + +s32 gl_load_texture(u32 texture_id, const char* path) +{ + s32 width, height, nrChannels; + unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texture_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", path); + stbi_image_free(data); + } + + return texture_id; +} + +// =================== Model Loading ======================== +// This section contains a whole host of things: +// 1. classes +// 2. std::vectors +// 3. std::strings +// that I have only used as a glue for I did not know if I had the model loading setup properly. +// @todo: replace these things eventually. For now the goal is to complete learnopengl + +s32 TextureFromFile(const char* filepath, std::string directory) +{ + std::string filename = std::string(filepath); + filename = directory + '/' + filename; + + u32 texid; + glGenTextures(1, &texid); + + s32 width, height, nrChannels; + unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texid); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + 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); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", filepath); + stbi_image_free(data); + } + + return texid; +} + +enum TextureType { TextureDiffuse=0, TextureSpecular }; + +struct Vertex { + Vec3 position; + Vec3 normal; + Vec2 texture; +}; + +struct Texture { + u32 id; + enum TextureType type; + std::string fname; +}; + +class Mesh { + public: + std::vector<Vertex> vertices; + std::vector<u32> indices; + std::vector<Texture> textures; + + u32 vao; + u32 vbo; + u32 ebo; + + Mesh(std::vector<Vertex> vertices, std::vector<u32> indices, std::vector<Texture> textures) + { + this->vertices = vertices; + this->indices = indices; + this->textures = textures; + + // setup mesh shader stuff + glGenVertexArrays(1, &vao); + glGenBuffers(1, &vbo); + glGenBuffers(1, &ebo); + + glBindVertexArray(vao); + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(struct Vertex), &(this->vertices[0]), GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(u32), &(this->indices[0]), GL_STATIC_DRAW); + + // position + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); + // normal + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); + // texture + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texture)); + + glBindVertexArray(0); + } + + void draw(u32 shader_program) + { + glUseProgram(shader_program); + + u32 diffuse_num = 1; + u32 specular_num = 1; + char tex_unit_name[64]; + // set shininess + s32 mat_shine_loc = glGetUniformLocation(shader_program, "material.shininess"); + glUniform1f(mat_shine_loc, 32.0f); + + for (u32 i=0; i<textures.size(); i++) + { + struct Texture curr_tex = textures[i]; + if (curr_tex.type == TextureDiffuse) + { + sprintf(tex_unit_name, "material.diffuse[%i]", diffuse_num); + } + else if (curr_tex.type == TextureSpecular) + { + sprintf(tex_unit_name, "material.diffuse[%i]", specular_num); + } + + glActiveTexture(GL_TEXTURE0 + i); + s32 tex_unit_loc = glGetUniformLocation(shader_program, tex_unit_name); + glUniform1i(tex_unit_loc, i); + glBindTexture(GL_TEXTURE_2D, curr_tex.id); + } + glActiveTexture(GL_TEXTURE0); + + glBindVertexArray(vao); + glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); + glBindVertexArray(0); + } +}; + +class Model +{ + public: + Model(std::string path) + { + load_model(path); + } + void draw(u32 shader_program); + private: + std::vector<Texture> loaded_textures; + std::vector<Mesh> meshes; + std::string directory; + + void load_model(std::string path); + void process_node(aiNode *node, const aiScene *scene); + Mesh process_mesh(aiMesh *mesh, const aiScene *scene); + std::vector<Texture> load_material_textures(aiMaterial *mat, aiTextureType type, TextureType type_name); +}; + +void Model::draw(u32 shader_program) +{ + for (int i=0; i < meshes.size(); i++) + { + meshes[i].draw(shader_program); + } +} + +void Model::load_model(std::string path) +{ + Assimp::Importer import; + const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); + + if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) + { + printf("error loading model :%s\n", import.GetErrorString()); + return; + } + + directory = path.substr(0, path.find_last_of('/')); + process_node(scene->mRootNode, scene); +} + +void Model::process_node(aiNode *node, const aiScene *scene) +{ + for (int i=0; i < node->mNumMeshes; i++) + { + aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; + meshes.push_back(process_mesh(mesh, scene)); + } + + for (int i=0; i<node->mNumChildren; i++) + { + process_node(node->mChildren[i], scene); + } +} + +Mesh Model::process_mesh(aiMesh *mesh, const aiScene *scene) +{ + std::vector<Vertex> vertices; + std::vector<u32> indices; + std::vector<Texture> textures; + + for (u32 i=0; i < mesh->mNumVertices; i++) + { + Vec3 position; + position.x = mesh->mVertices[i].x; + position.y = mesh->mVertices[i].y; + position.z = mesh->mVertices[i].z; + + Vec3 normal; + normal.x = mesh->mNormals[i].x; + normal.y = mesh->mNormals[i].y; + normal.z = mesh->mNormals[i].z; + + Vec2 texture = {0, 0}; + if (mesh->mTextureCoords[0]) + { + texture.x = mesh->mTextureCoords[0][i].x; + texture.y = mesh->mTextureCoords[0][i].y; + } + + struct Vertex vertex; + vertex.position = position; + vertex.normal = normal; + vertex.texture = texture; + + vertices.push_back(vertex); + } + // process indices + for (u32 i = 0; i < mesh->mNumFaces; i++) + { + aiFace face = mesh->mFaces[i]; + for(u32 j = 0; j < face.mNumIndices; j++) + { + indices.push_back(face.mIndices[j]); + } + } + // process material + if (mesh->mMaterialIndex >= 0) + { + aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; + std::vector<Texture> diffuse_maps = load_material_textures(material, aiTextureType_DIFFUSE, TextureDiffuse); + textures.insert(textures.end(), diffuse_maps.begin(), diffuse_maps.end()); + std::vector<Texture> specular_maps = load_material_textures(material, aiTextureType_SPECULAR, TextureSpecular); + textures.insert(textures.end(), specular_maps.begin(), specular_maps.end()); + } + + return Mesh(vertices, indices, textures); +} + +std::vector<Texture> Model::load_material_textures(aiMaterial *mat, aiTextureType type, TextureType tex_type) +{ + std::vector<Texture> textures; + for(u32 i=0; i<mat->GetTextureCount(type); i++) + { + bool load_texture = true; + aiString str; + mat->GetTexture(type, i, &str); + const char* fname = str.C_Str(); + + for (s32 j=0; j<loaded_textures.size(); j++) + { + if (std::strcmp(loaded_textures[j].fname.data(), fname) == 0) + { + load_texture = false; + textures.push_back(loaded_textures[j]); + break; + } + } + if (load_texture) + { + Texture texture; + texture.id = TextureFromFile(fname, directory); + texture.type = tex_type; + texture.fname = std::string(fname); + textures.push_back(texture); + loaded_textures.push_back(texture); + } + } + + return textures; +} + +int main(int argc, char* argv[]) +{ + + // ============ END ============ + int width = 1024; + int height = 768; + + if (SDL_Init(SDL_INIT_VIDEO) != 0) + { + printf("Error initialising SDL2: %s\n", SDL_GetError()); + return 0; + }; + + // set opengl version and profile + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); + + // initialise window with opengl flag + SDL_Window* window = SDL_CreateWindow("SDL Test", + 50, + 50, + width, + height, + SDL_WINDOW_OPENGL); + + SDL_SetRelativeMouseMode(SDL_TRUE); + + // create an opengl context + SDL_GLContext context = SDL_GL_CreateContext(window); + if (!context) + { + printf("OpenGL context creation failed: %s\n", SDL_GetError()); + return -1; + } + + + // load glad + if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { + printf("Failed to initialize Glad\n"); + return 1; + } + + // filesystem playground stuff + size_t read_count; + char* vertex_source = (char*)SDL_LoadFile("./source/shaders/depth_test.vs.glsl", &read_count); + char* fragment_source = (char*)SDL_LoadFile("./source/shaders/depth_test.fs.glsl", &read_count); + char* blend_shader_source = (char*)SDL_LoadFile("./source/shaders/blend_test.fs.glsl", &read_count); + + u32 shader_program = gl_shader_program(vertex_source, fragment_source); + u32 blend_shader_program = gl_shader_program(vertex_source, blend_shader_source); + + printf("Successfully compiled shaders.\n"); + + float cubeVertices[] = { + // Back face + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + // Front face + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // top-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + // Left face + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right + -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-left + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right + // Right face + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left + 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + // Bottom face + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // top-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right + // Top face + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + -0.5f, 0.5f, 0.5f, 0.0f, 0.0f // bottom-left + }; + float planeVertices[] = { + // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) + // BottomFace + -5.0f, -1.0f, -5.0f, 0.0f, 2.0f, // top-right + 5.0f, -1.0f, -5.0f, 2.0f, 2.0f, // top-left + 5.0f, -1.0f, 5.0f, 2.0f, 0.0f, // bottom-left + 5.0f, -1.0f, 5.0f, 2.0f, 0.0f, // bottom-left + -5.0f, -1.0f, 5.0f, 0.0f, 0.0f, // bottom-right + -5.0f, -1.0f, -5.0f, 0.0f, 2.0f, // top-right + // Top face + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // top-left + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // bottom-right + 5.0f, -0.5f, -5.0f, 2.0f, 2.0f, // top-right + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // bottom-right + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // top-left + -5.0f, -0.5f, 5.0f, 0.0f, 0.0f // bottom-left + }; + float quadVertices[] = { + // Front face + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, 0.5f, 0.0f, 1.0f, // top-left + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + // Back face + -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + -0.5f, 0.5f, 0.0f, 1.0f, // top-left + }; + stbi_set_flip_vertically_on_load(1); + + u32 cube_vao, cube_vbo, plane_vao, plane_vbo, quad_vao, quad_vbo; + + glGenVertexArrays(1, &cube_vao); + glGenBuffers(1, &cube_vbo); + + glBindVertexArray(cube_vao); + glBindBuffer(GL_ARRAY_BUFFER, cube_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); + glBindVertexArray(0); + + glGenVertexArrays(1, &plane_vao); + glGenBuffers(1, &plane_vbo); + + glBindVertexArray(plane_vao); + glBindBuffer(GL_ARRAY_BUFFER, plane_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); + glBindVertexArray(0); + + glGenVertexArrays(1, &quad_vao); + glGenBuffers(1, &quad_vbo); + + glBindVertexArray(quad_vao); + glBindBuffer(GL_ARRAY_BUFFER, quad_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2*sizeof(float))); + glBindVertexArray(0); + + u32 cube_tex_id; + glGenTextures(1, &cube_tex_id); + glActiveTexture(GL_TEXTURE0); + gl_load_texture(cube_tex_id, "assets/container.jpg"); + + u32 plane_tex_id; + glGenTextures(1, &plane_tex_id); + glActiveTexture(GL_TEXTURE1); + gl_load_texture(plane_tex_id, "assets/smiling.png"); + + u32 window_tex_id; + glGenTextures(1, &window_tex_id); + glActiveTexture(GL_TEXTURE2); + { + u32 texture_id = window_tex_id; + char *path = "assets/window.png"; + s32 width, height, nrChannels; + unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + if (data) + { + GLenum format; + if (nrChannels == 1) + format = GL_RED; + else if (nrChannels == 3) + format = GL_RGB; + else if (nrChannels == 4) + format = GL_RGBA; + + glBindTexture(GL_TEXTURE_2D, texture_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + stbi_image_free(data); + } + else + { + printf("failed to load image texture at path: %s", path); + stbi_image_free(data); + } + +} + + // objects + Vec3 model_translations[] = { + Vec3{ 0.5, 0.0, 0.0}, //origin square + Vec3{ -1.0, 0.0, -1.0}, // plane + Vec3{ -1.0, 0.0, -0.5}, // window between squares + Vec3{ 0.0, 0.0, 3.0}, //window infront of origin square + Vec3{ -2.5, 0.0, -0.5}, // square to the left + Vec3{ -1.0, 0.0, -1.5}, // random square behind window between squares + }; + + r32 FOV = 90.0; + r32 time_curr; + r32 time_prev = SDL_GetTicks64() / 100.0; + // camera stuff + Vec3 camera_pos = Vec3{ 0.0, 0.0, 10.0f}; + Vec3 preset_up_dir = Vec3{ 0.0, 1.0, 0.0 }; + + r32 angle_yaw, angle_pitch, angle_roll; + angle_pitch = (r32)To_Radian(0.0f); + angle_yaw = (r32)-To_Radian(90.0f); + + Vec3 camera_look = camera_look_around(angle_pitch, angle_yaw); + + // @todo: remove this, I dont like this and think that this is unnecessary + Vec3 camera_look_increment; + r32 camera_speed = 0.5f; + + Mat4 view = camera_create4m(camera_pos, camera_look, preset_up_dir); + + Mat4 proj = perspective4m((r32)To_Radian(90.0), (r32)width / (r32)height, 0.1f, 100.0f); + // needs this + glUseProgram(shader_program); + uint32_t proj_loc = glGetUniformLocation(shader_program, "Projection"); + glUniformMatrix4fv(proj_loc, 1, GL_TRUE, proj.buffer); + + glUseProgram(blend_shader_program); + proj_loc = glGetUniformLocation(blend_shader_program, "Projection"); + glUniformMatrix4fv(proj_loc, 1, GL_TRUE, proj.buffer); + + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glEnable(GL_CULL_FACE); + glDepthFunc(GL_LESS); + glCullFace(GL_BACK); + //glFrontFace(GL_CW); // front-faces are clock-wise, this will make the back-faces visible (since the arrays used were + // setup as counter-clockwise) + u32 fbo; + glGenFramebuffers(1, &fbo); + + u8 game_running = true; + + u8 hold_lshift = false; + u8 move_w = false; + u8 move_a = false; + u8 move_s = false; + u8 move_d = false; + + while(game_running) + { + + // frame delta + time_curr = SDL_GetTicks64() / 100.0; + r32 time_delta = time_curr - time_prev; + + r32 camera_speed_adjusted = time_delta * camera_speed; + camera_look_increment = scaler_multiply3v(camera_look, camera_speed_adjusted); + + SDL_Event ev; + while(SDL_PollEvent(&ev)) + { + + // INPUT + switch (ev.type) + { + case (SDL_QUIT): + { + game_running = false; + } break; + case (SDL_KEYDOWN): + { + if (ev.key.keysym.sym == SDLK_LSHIFT) + { + hold_lshift = true; + } + if (ev.key.keysym.sym == SDLK_w) + { + move_w = true; + } + if (ev.key.keysym.sym == SDLK_s) + { + move_s = true; + } + if (ev.key.keysym.sym == SDLK_a) + { + move_a = true; + } + if (ev.key.keysym.sym == SDLK_d) + { + move_d = true; + } + } break; + case (SDL_KEYUP): + { + if (ev.key.keysym.sym == SDLK_LSHIFT) + { + hold_lshift = false; + } + if (ev.key.keysym.sym == SDLK_w) + { + move_w = false; + } + if (ev.key.keysym.sym == SDLK_s) + { + move_s = false; + } + if (ev.key.keysym.sym == SDLK_a) + { + move_a = false; + } + if (ev.key.keysym.sym == SDLK_d) + { + move_d = false; + } + } break; + case (SDL_MOUSEMOTION): + { + SDL_MouseMotionEvent mouse_event = ev.motion; + r32 x_motion = (r32)mouse_event.xrel; + r32 y_motion = (r32)mouse_event.yrel; + if (x_motion != 0.0 || y_motion != 0.0) + { + angle_yaw = angle_yaw + To_Radian(x_motion * 0.1f); + angle_pitch = clampf(angle_pitch + To_Radian(-y_motion * 0.1f), To_Radian(-89.0f), To_Radian(89.0f)); + + camera_look = camera_look_around(angle_pitch, angle_yaw); + } + } break; + default: + { + break; + } + } + } + + // PROCESS + if (move_w) + { + camera_pos = add3v(camera_pos, camera_look_increment); + } + if (move_s) + { + camera_pos = subtract3v(camera_pos, camera_look_increment); + } + if (move_a) + { + Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); + Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); + camera_pos = add3v(camera_pos, camera_right_scaled); + } + if (move_d) + { + Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); + Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); + camera_pos = subtract3v(camera_pos, camera_right_scaled); + } + view = camera_create4m(camera_pos, add3v(camera_pos, camera_look), preset_up_dir); + + // object shader program stuff + glUseProgram(shader_program); + uint32_t view_loc = glGetUniformLocation(shader_program, "View"); + glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer); + + glUseProgram(blend_shader_program); + view_loc = glGetUniformLocation(blend_shader_program, "View"); + glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer); + + time_prev = time_curr; + + // OUTPUT + glClearColor(1.0f, 0.6f, .6f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + glDisable(GL_BLEND); + { //plane + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 1); + Vec3 translation_iter = model_translations[1]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(plane_vao); + glDrawArrays(GL_TRIANGLES, 0, 12); + } + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + {//origin square + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[0]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + {//square to the left + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[4]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + {//random square behind window between squares + glUseProgram(shader_program); + s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); + Vec3 translation_iter = model_translations[5]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(cube_vao); + glDrawArrays(GL_TRIANGLES, 0, 36); + } + // @note: this is to demonstrate the limitations of blending with the depth buffer. + // Currently, this will show a weird behavior where since we render the transparent object + // closest to the camera first, the second window, further from the player will be discarded by the + // depth buffer and will be invisible. + // This is a limiation of transparent objects with the depth buffer. This does not happen with opaque objects. + // + // The "fix" if we can even call it that, is to render objects in order, furthest first and closest second, in layers. + + {//window infront of origin square + glUseProgram(blend_shader_program); + s32 tex_id_loc = glGetUniformLocation(blend_shader_program, "TexId"); + glUniform1i(tex_id_loc, 2); + Vec3 translation_iter = model_translations[3]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(quad_vao); + glDrawArrays(GL_TRIANGLES, 0, 12); + } + {//window between squares + glUseProgram(blend_shader_program); + s32 tex_id_loc = glGetUniformLocation(blend_shader_program, "TexId"); + glUniform1i(tex_id_loc, 2); + Vec3 translation_iter = model_translations[2]; + Mat4 model = init_value4m(1.0); + Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z); + model = multiply4m(model_translation, model); + uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); + glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); + glBindVertexArray(quad_vao); + glDrawArrays(GL_TRIANGLES, 0, 12); + } + SDL_GL_SwapWindow(window); + } + + // opengl free calls + //glDeleteVertexArrays(1, &VAO); + //glDeleteBuffers(1, &VBO); + glDeleteProgram(shader_program); + glDeleteProgram(blend_shader_program); + + // sdl free calls + SDL_GL_DeleteContext(context); + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; +} diff --git a/source/lessons/face_culling/shaders/blend_test.fs.glsl b/source/lessons/face_culling/shaders/blend_test.fs.glsl new file mode 100644 index 0000000..23daa14 --- /dev/null +++ b/source/lessons/face_culling/shaders/blend_test.fs.glsl @@ -0,0 +1,14 @@ +#version 330 core + + +in vec2 TexCoords; +in vec3 VertexWorldPos; +uniform sampler2D TexId; +uniform vec4 hlt_color; +out vec4 FragColor; + +void main() { + vec4 tex = texture(TexId, TexCoords); + + FragColor = tex; +} diff --git a/source/lessons/face_culling/shaders/depth_test.fs.glsl b/source/lessons/face_culling/shaders/depth_test.fs.glsl new file mode 100644 index 0000000..796d849 --- /dev/null +++ b/source/lessons/face_culling/shaders/depth_test.fs.glsl @@ -0,0 +1,30 @@ +#version 330 core + + +in vec2 TexCoords; +in vec3 VertexWorldPos; +uniform sampler2D TexId; +out vec4 FragColor; + +uniform float near = 0.1f; +uniform float far = 100.0f; + +/* @note +float linear_fragment_depth = MakeDepthLinear(non_linear_fragment_depth); +float scaled_lfd = linear_fragment_depth/far; + +gives us the z value in eye space. +This is purely for learning purposes. +The equation used in MakeDepthLinear is derived from the PerspectiveProjectionMatrix. +Take a look at the equation for that in the codebase +or here: https://www.songho.ca/opengl/gl_projectionmatrix.html +*/ +float MakeDepthLinear(float depth) { + float ndc = 2.0f*depth - 1; + float linear_depth = (2.0 * far * near)/(far + near - ndc*(far - near)); + return linear_depth; +} + +void main() { + FragColor = texture(TexId, TexCoords); +} diff --git a/source/lessons/face_culling/shaders/depth_test.vs.glsl b/source/lessons/face_culling/shaders/depth_test.vs.glsl new file mode 100644 index 0000000..b3b81cc --- /dev/null +++ b/source/lessons/face_culling/shaders/depth_test.vs.glsl @@ -0,0 +1,19 @@ +#version 330 core +layout(location=0) in vec3 aPos; +layout(location=1) in vec2 aTex; + +uniform mat4 Model; +uniform mat4 View; +uniform mat4 Projection; + +out vec2 TexCoords; +out vec3 VertexWorldPos; + +// @note: I still do not fully understand how the FragNormal calculation works. Need to make sure I intuitively +// get that + +void main() { + gl_Position = Projection*View*Model*vec4(aPos, 1.0); + VertexWorldPos = vec3(Model * vec4(aPos, 1.0)); + TexCoords = aTex; +}; diff --git a/source/main.cpp b/source/main.cpp index 2f07c0e..650799d 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -10,6 +10,9 @@ #include "stb_image.h" /* @lookup: +* - understand kernals, how they work and how they affect post processing +* - Check to see why it is necessary to do glBindTexture() +* - understand the difference between binding textures, and activating a texture unit * - I do not understand how floating point numbers work, so I should probably look into that. * - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied. * I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet. @@ -159,7 +162,6 @@ s32 gl_load_texture(u32 texture_id, const char* path) 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); - stbi_image_free(data); } else @@ -181,6 +183,12 @@ s32 gl_load_texture(u32 texture_id, const char* path) s32 TextureFromFile(const char* filepath, std::string directory) { + // @note: this function is stupid as it already became outdated as I needed to tweak the parameters + // for wrapping. Either those become function parameters (Which makes sense I guess) or I look at + // exactly what steps I am reusing and just make that a function so the function is called fewer times. + // + // I am guessing this won't look good from a design point of view for all those jobs and postings, even if + // this may be the simpler and faster thing to do, albeit at the cost of typing. std::string filename = std::string(filepath); filename = directory + '/' + filename; @@ -454,6 +462,52 @@ std::vector<Texture> Model::load_material_textures(aiMaterial *mat, aiTextureTyp return textures; } +class Shader { + // @note: this is a draft, I think frankly, it's a stupid idea to be making this at this point + // but my goal is to look at my code at this stage (which is in the second half of (or so I think) + // learnopengl and identify repeated code that I think I can yank out and can make convenient to write. + // The precondition for all of this is that I do not remodel the program based off of some vague idea of + // cleanliness in my head. This is all still very procedural, I just want to minimize the amount I type + // and at the same time see how well I can identify good abstractions + // + // + // I much prefer to have things be not a class, especially if I look at how I did my lovely + // math functions, which are so simple and straightforward + public: + u32 id; + + // @note: all well and good until you get compute shaders + // then the entire thing shits the bed + Shader(char* vertex_shader_source, char* fragment_shader_source) { + id = gl_shader_program(vertex_shader_source, fragment_shader_source); + } + + void use() { + glUseProgram(id); + } + + void draw_triangles(u32 vao, u32 count) { + glBindVertexArray(vao); + glDrawArrays(GL_TRIANGLES, 0, count); + } + + void set_1i(char* variable, s32 value) { + s32 loc = glGetUniformLocation(id, variable); + glUniform1i(loc, value); + } + + void set_matrix4fv(char* variable, Mat4 value, int count) { + s32 loc = glGetUniformLocation(id, variable); + glUniformMatrix4fv(loc, count, GL_TRUE, value.buffer); + }; + + ~Shader() { + // @note: this can literally be replaced by another function that goes over the entire list + // of shader_programs near the program exit and deletes them, if I even need to do that. + glDeleteProgram(id); + } +}; + int main(int argc, char* argv[]) { @@ -503,78 +557,103 @@ int main(int argc, char* argv[]) char* vertex_source = (char*)SDL_LoadFile("./source/shaders/depth_test.vs.glsl", &read_count); char* fragment_source = (char*)SDL_LoadFile("./source/shaders/depth_test.fs.glsl", &read_count); char* blend_shader_source = (char*)SDL_LoadFile("./source/shaders/blend_test.fs.glsl", &read_count); + char* fbo_vs = (char*)SDL_LoadFile("./source/shaders/fbo.vs.glsl", &read_count); + char* fbo_fs = (char*)SDL_LoadFile("./source/shaders/fbo.fs.glsl", &read_count); u32 shader_program = gl_shader_program(vertex_source, fragment_source); u32 blend_shader_program = gl_shader_program(vertex_source, blend_shader_source); + u32 fbo_shader_program = gl_shader_program(fbo_vs, fbo_fs); printf("Successfully compiled shaders.\n"); float cubeVertices[] = { - // positions // texture Coords - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, - 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, - - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, - - -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, - -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - - -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, - - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f - }; + // Back face + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + // Front face + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // top-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + // Left face + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right + -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-left + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right + -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right + // Right face + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left + 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left + // Bottom face + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right + 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // top-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right + -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right + // Top face + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left + -0.5f, 0.5f, 0.5f, 0.0f, 0.0f // bottom-left + }; float planeVertices[] = { - // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) - 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, - -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, - -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, - - 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, - -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, - 5.0f, -0.5f, -5.0f, 2.0f, 2.0f + // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) + // BottomFace + -5.0f, -1.0f, -5.0f, 0.0f, 2.0f, // top-right + 5.0f, -1.0f, -5.0f, 2.0f, 2.0f, // top-left + 5.0f, -1.0f, 5.0f, 2.0f, 0.0f, // bottom-left + 5.0f, -1.0f, 5.0f, 2.0f, 0.0f, // bottom-left + -5.0f, -1.0f, 5.0f, 0.0f, 0.0f, // bottom-right + -5.0f, -1.0f, -5.0f, 0.0f, 2.0f, // top-right + // Top face + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // top-left + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // bottom-right + 5.0f, -0.5f, -5.0f, 2.0f, 2.0f, // top-right + 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // bottom-right + -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // top-left + -5.0f, -0.5f, 5.0f, 0.0f, 0.0f // bottom-left }; float quadVertices[] = { - // positions // texture Coords - -0.5f, -0.5f, 0.0f, 0.0f, - 0.5f, -0.5f, 1.0f, 0.0f, - 0.5f, 0.5f, 1.0f, 1.0f, - 0.5f, 0.5f, 1.0f, 1.0f, - -0.5f, 0.5f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.0f, 0.0f, + // Front face + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + 0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, 0.5f, 0.0f, 1.0f, // top-left + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + // Back face + -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + 0.5f, -0.5f, 1.0f, 0.0f, // bottom-right + 0.5f, 0.5f, 1.0f, 1.0f, // top-right + -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left + -0.5f, 0.5f, 0.0f, 1.0f, // top-left }; + float fboVertices[] = { + -1.0f, -1.0f, 0.0f, 0.0f, // bottom-left + 1.0f, -1.0f, 1.0f, 0.0f, // bottom-right + 1.0f, 1.0f, 1.0f, 1.0f, // top-right + 1.0f, 1.0f, 1.0f, 1.0f, // top-right + -1.0f, 1.0f, 0.0f, 1.0f, // top-left + -1.0f, -1.0f, 0.0f, 0.0f, // bottom-left + }; stbi_set_flip_vertically_on_load(1); - u32 cube_vao, cube_vbo, plane_vao, plane_vbo, quad_vao, quad_vbo; + u32 cube_vao, cube_vbo, plane_vao, plane_vbo, quad_vao, quad_vbo, fbo_vao, fbo_vbo; glGenVertexArrays(1, &cube_vao); glGenBuffers(1, &cube_vbo); @@ -612,24 +691,26 @@ int main(int argc, char* argv[]) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2*sizeof(float))); glBindVertexArray(0); - u32 cube_tex_id; - glGenTextures(1, &cube_tex_id); - glActiveTexture(GL_TEXTURE0); - gl_load_texture(cube_tex_id, "assets/container.jpg"); + // framebuffer objects + glGenVertexArrays(1, &fbo_vao); + glGenBuffers(1, &fbo_vbo); - u32 plane_tex_id; - glGenTextures(1, &plane_tex_id); - glActiveTexture(GL_TEXTURE1); - gl_load_texture(plane_tex_id, "assets/smiling.png"); + glBindVertexArray(fbo_vao); + glBindBuffer(GL_ARRAY_BUFFER, fbo_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(fboVertices), &fboVertices, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2*sizeof(float))); + glBindVertexArray(0); u32 window_tex_id; glGenTextures(1, &window_tex_id); glActiveTexture(GL_TEXTURE2); { - u32 texture_id = window_tex_id; char *path = "assets/window.png"; - s32 width, height, nrChannels; - unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); + s32 _width, _height, nrChannels; + unsigned char *data = stbi_load(path, &_width, &_height, &nrChannels, 0); if (data) { GLenum format; @@ -640,8 +721,8 @@ int main(int argc, char* argv[]) else if (nrChannels == 4) format = GL_RGBA; - glBindTexture(GL_TEXTURE_2D, texture_id); - glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_2D, window_tex_id); + glTexImage2D(GL_TEXTURE_2D, 0, format, _width, _height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -657,7 +738,17 @@ int main(int argc, char* argv[]) stbi_image_free(data); } -} + } + + u32 cube_tex_id; + glGenTextures(1, &cube_tex_id); + glActiveTexture(GL_TEXTURE0); + gl_load_texture(cube_tex_id, "assets/container.jpg"); + + u32 plane_tex_id; + glGenTextures(1, &plane_tex_id); + glActiveTexture(GL_TEXTURE1); + gl_load_texture(plane_tex_id, "assets/smiling.png"); // objects Vec3 model_translations[] = { @@ -700,7 +791,40 @@ int main(int argc, char* argv[]) glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); + glEnable(GL_CULL_FACE); glDepthFunc(GL_LESS); + glCullFace(GL_BACK); + //glFrontFace(GL_CW); // front-faces are clock-wise, this will make the back-faces visible (since the arrays used were + // setup as counter-clockwise) + u32 fbo; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + + // create a texture for the framebuffer to render data to + u32 fbo_tex; + glGenTextures(1, &fbo_tex); + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, fbo_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glBindTexture(GL_TEXTURE_2D, 0); + + u32 rbo; + glGenRenderbuffers(1, &rbo); + glBindRenderbuffer(GL_RENDERBUFFER, rbo); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + // attach to current bound framebuffer object + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_tex, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); + + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + printf("Error! Framebuffer is not completely setup\n"); + return -1; + } + glBindFramebuffer(GL_FRAMEBUFFER, 0); u8 game_running = true; @@ -832,12 +956,15 @@ int main(int argc, char* argv[]) time_prev = time_curr; // OUTPUT + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + glEnable(GL_DEPTH_TEST); glClearColor(1.0f, 0.6f, .6f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); { //plane glUseProgram(shader_program); + // @note: this is just a test, I dont need to do this here; s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); glUniform1i(tex_id_loc, 1); Vec3 translation_iter = model_translations[1]; @@ -847,13 +974,15 @@ int main(int argc, char* argv[]) uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); glBindVertexArray(plane_vao); - glDrawArrays(GL_TRIANGLES, 0, 6); + glBindTexture(GL_TEXTURE_2D, plane_tex_id); + glDrawArrays(GL_TRIANGLES, 0, 12); } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); {//origin square glUseProgram(shader_program); + glBindTexture(GL_TEXTURE_2D, cube_tex_id); s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); glUniform1i(tex_id_loc, 0); Vec3 translation_iter = model_translations[0]; @@ -867,6 +996,7 @@ int main(int argc, char* argv[]) } {//square to the left glUseProgram(shader_program); + glBindTexture(GL_TEXTURE_2D, cube_tex_id); s32 tex_id_loc = glGetUniformLocation(shader_program, "TexId"); glUniform1i(tex_id_loc, 0); Vec3 translation_iter = model_translations[4]; @@ -889,6 +1019,7 @@ int main(int argc, char* argv[]) uint32_t model_loc = glGetUniformLocation(shader_program, "Model"); glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); glBindVertexArray(cube_vao); + glBindTexture(GL_TEXTURE_2D, cube_tex_id); glDrawArrays(GL_TRIANGLES, 0, 36); } // @note: this is to demonstrate the limitations of blending with the depth buffer. @@ -910,7 +1041,8 @@ int main(int argc, char* argv[]) uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); glBindVertexArray(quad_vao); - glDrawArrays(GL_TRIANGLES, 0, 6); + glBindTexture(GL_TEXTURE_2D, window_tex_id); + glDrawArrays(GL_TRIANGLES, 0, 12); } {//window between squares glUseProgram(blend_shader_program); @@ -923,8 +1055,32 @@ int main(int argc, char* argv[]) uint32_t model_loc = glGetUniformLocation(blend_shader_program, "Model"); glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer); glBindVertexArray(quad_vao); + glBindTexture(GL_TEXTURE_2D, window_tex_id); + glDrawArrays(GL_TRIANGLES, 0, 12); + } + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + // draw everything to a framebuffer object + glDisable(GL_DEPTH_TEST); + glClearColor(1.0f, 1.0f, 1.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + { + glUseProgram(fbo_shader_program); + glBindVertexArray(fbo_vao); + // @note: this glActiveTexture call was the bane of my existence for the day, this is done to check this particular + // thing regarding which texture unit the framebuffer object gets called to and it turns out, it needs a glActiveTexture + // call (atleast in my case) since I am rendering multiple textures which are bound to different texture units, + // primarily because of the different shaders I am using. + // + // So this is why I need to call this, but what I could also do is call glActiveTexture when creating the texture + // and it would have the same effect as this + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, fbo_tex); + s32 tex_id_loc = glGetUniformLocation(fbo_shader_program, "TexId"); + glUniform1i(tex_id_loc, 0); glDrawArrays(GL_TRIANGLES, 0, 6); } + glEnable(GL_DEPTH_TEST); SDL_GL_SwapWindow(window); } @@ -933,6 +1089,7 @@ int main(int argc, char* argv[]) //glDeleteBuffers(1, &VBO); glDeleteProgram(shader_program); glDeleteProgram(blend_shader_program); + glDeleteProgram(fbo_shader_program); // sdl free calls SDL_GL_DeleteContext(context); diff --git a/source/shaders/fbo.fs.glsl b/source/shaders/fbo.fs.glsl new file mode 100644 index 0000000..afb9e08 --- /dev/null +++ b/source/shaders/fbo.fs.glsl @@ -0,0 +1,72 @@ +#version 330 core + +in vec2 TexCoords; +uniform sampler2D TexId; +out vec4 FragColor; + +vec4 filter_color_invert(vec4 color) +{ + vec4 res = vec4(vec3(1.0) - vec3(color), 1.0); + return res; +} + +vec4 filter_color_grayscale(vec4 color) +{ + // we will need to average the colors + // float average = (color.x + color.y + color.z) / 3.0f; + // in reality, human our most sensitive towards green and least to blue, so will need to weight those + float average = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b; + vec4 res = vec4(vec3(average), 1.0); + + return res; +} + +// @note: different kernels for experimentation +const float kernel_sharpen[9] = float[]( + -1, -1, -1, + -1, 9, -1, + -1, -1, -1 +); + +const float kernel_blur[9] = float[]( + 1.0/16.0, 2.0/16.0, 1.0/16.0, + 2.0/16.0, 4.0/16.0, 2.0/16.0, + 1.0/16.0, 2.0/16.0, 1.0/16.0 +); + +const float kernel_edge_detection[9] = float[]( + 1, 1, 1, + 1, -8, 1, + 1, 1, 1 +); + +vec4 filter_kernal_effects() +{ + const float offset = 1.0/300.0; + vec2 offsets[9] = vec2[]( + vec2(-offset, offset), // top left + vec2( 0, offset), // top center + vec2( offset, offset), // top right + vec2(-offset, 0), // center left + vec2( 0, 0), // center center + vec2( offset, 0), // center right + vec2(-offset, -offset), // bot left + vec2( 0, -offset), // bot center + vec2( offset, -offset) // bot right + ); + + float kernal[9] = kernel_edge_detection; + vec3 kernalValue = vec3(0.0); + vec3 sampleTex[9]; + for (int i=0; i<9; i++) { + sampleTex[i] = vec3(texture(TexId, TexCoords + offsets[i])); + kernalValue += (kernal[i] * sampleTex[i]); + } + + vec4 res = vec4(kernalValue, 1.0); + return res; +} + +void main() { + FragColor = filter_kernal_effects(); +} diff --git a/source/shaders/fbo.vs.glsl b/source/shaders/fbo.vs.glsl new file mode 100644 index 0000000..82d7211 --- /dev/null +++ b/source/shaders/fbo.vs.glsl @@ -0,0 +1,10 @@ +#version 330 core +layout(location=0) in vec3 aPos; +layout(location=1) in vec2 aTex; + +out vec2 TexCoords; + +void main() { + gl_Position = vec4(aPos.x, aPos.y, 0.0f, 1.0f); + TexCoords = aTex; +}; |