Initial commit

This commit is contained in:
Nathan Chapman 2025-07-12 10:45:59 -06:00
commit 32a4097a21
21 changed files with 34491 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# CMake build directories
build/
cmake-build-*/
out/
.cache/
# CMake generated files
CMakeFiles/
CMakeCache.txt
cmake_install.cmake
Makefile
*.vcxproj*
*.sln
# IDE specific files
.idea/
.vscode/
*.user
# Other temporary files
*.log
*.tmp
*.swp

23
CMakeLists.txt Normal file
View File

@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.19)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(WIN32)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake)
endif()
project(Main)
file(GLOB SOURCES src/*.h src/*.cpp src/*.c)
add_executable(Main ${SOURCES})
find_package(glfw3 3.4 REQUIRED)
find_package(OpenGL REQUIRED)
if(UNIX)
set(GLFW3_LIBRARY glfw)
endif()
include_directories(${GLFW3_INCLUDE_DIR})
target_include_directories(Main PUBLIC include src)
target_link_libraries(Main ${GLFW3_LIBRARY} OpenGL::GL)

BIN
assets/textures/crate.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 457 KiB

44
compile Executable file
View File

@ -0,0 +1,44 @@
#!/bin/sh
RUN_AFTER_BUILD=0
CMAKE_ARGS=""
BINARY_NAME="Main"
for arg in "$@"; do
case "$arg" in
--clean)
echo "Cleaning build directory..."
rm -rf build/*
;;
--debug)
echo "Enabling debug build..."
CMAKE_ARGS="-DCMAKE_BUILD_TYPE=Debug"
;;
--run)
RUN_AFTER_BUILD=1
;;
*)
echo "Unknown argument: $arg"
echo "Usage: $0 [--clean] [--debug] [--run]"
exit 1
;;
esac
done
mkdir -p build
(
cd build || exit 1
cmake .. $CMAKE_ARGS
make
)
if [ "$RUN_AFTER_BUILD" -eq 1 ]; then
if [ -x "build/$BINARY_NAME" ]; then
echo "Running ./$BINARY_NAME..."
"./build/$BINARY_NAME"
else
echo "Error: Binary 'build/$BINARY_NAME' not found or not executable."
exit 1
fi
fi

311
include/KHR/khrplatform.h Normal file
View File

@ -0,0 +1,311 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
/*
* To support platform where unsigned long cannot be used interchangeably with
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
* unsigned long long or similar (this results in different C++ name mangling).
* To avoid changes for existing platforms, we restrict usage of intptr_t to
* platforms where the size of a pointer is larger than the size of long.
*/
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
#define KHRONOS_USE_INTPTR_T
#endif
#endif
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef KHRONOS_USE_INTPTR_T
typedef intptr_t khronos_intptr_t;
typedef uintptr_t khronos_uintptr_t;
#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
#endif
#if defined(_WIN64)
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

15914
include/glad/glad.h Normal file

File diff suppressed because one or more lines are too long

7988
include/stb_image.h Normal file

File diff suppressed because it is too large Load Diff

12
shaders/basic.frag Normal file
View File

@ -0,0 +1,12 @@
#version 460 core
layout (location = 0) in vec4 tex_color;
layout (location = 1) in vec2 tex_coord;
out vec4 frag_color;
uniform sampler2D tex;
void main() {
frag_color = texture(tex, tex_coord) * tex_color;
}

15
shaders/basic.vert Normal file
View File

@ -0,0 +1,15 @@
#version 460 core
layout (location = 0) in vec3 a_pos;
layout (location = 1) in vec3 a_color;
layout (location = 2) in vec2 a_tex_coord;
layout (location = 0) out vec4 tex_color;
layout (location = 1) out vec2 tex_coord;
void main() {
gl_Position = vec4(a_pos, 1.0);
tex_color = vec4(a_color, 1.0);
tex_coord = a_tex_coord;
}

28
src/basic.h Normal file
View File

@ -0,0 +1,28 @@
#pragma once
#include <string>
#include <glm/glm.hpp>
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef char s8;
typedef short s16;
typedef int s32;
typedef long long s64;
typedef s32 b32;
typedef float f32;
typedef double f64;
typedef std::string string;
#define array_count(array) (sizeof(array) / sizeof((array)[0]))
using Vector2 = glm::vec2;
using Vector3 = glm::vec3;
using Matrix4 = glm::mat4;

28
src/file.cpp Normal file
View File

@ -0,0 +1,28 @@
#include "file.h"
string load_file_to_string(string filepath) {
std::ifstream in_file(filepath);
string str;
if (in_file.is_open()) {
in_file.seekg(0, std::ios::end);
str.reserve(in_file.tellg());
in_file.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(in_file)),
std::istreambuf_iterator<char>());
in_file.close();
} else {
return "";
}
if (in_file.bad() || in_file.fail()) {
in_file.close();
return "";
}
in_file.close();
return str;
}

5
src/file.h Normal file
View File

@ -0,0 +1,5 @@
#pragma once
#include "basic.h"
#include <fstream>
string load_file_to_string(string filepath);

9436
src/glad.c Normal file

File diff suppressed because one or more lines are too long

12
src/logger.h Normal file
View File

@ -0,0 +1,12 @@
#pragma once
#include "basic.h"
#include <cstdio>
template <typename... Args>
void log(u32 log_level, Args ... args) {
if (log_level <= 9) {
std::printf(args ...);
std::fflush(stdout);
}
}

16
src/main.cpp Normal file
View File

@ -0,0 +1,16 @@
#include "window.h"
#include "logger.h"
int main(int argc, char *argv[]) {
Window window;
if (!init(&window, 640, 480, "OpenGL Renderer")) {
log(1, "%s error: Window init error\n", __FUNCTION__);
return -1;
}
main_loop(&window);
cleanup(&window);
return 0;
}

26
src/model.cpp Normal file
View File

@ -0,0 +1,26 @@
#include "model.h"
void init_model(Model *model) {
model->vertex_data.vertices.resize(6);
model->vertex_data.vertices[0].position = Vector3(-0.5f, -0.5f, 0.5f);
model->vertex_data.vertices[1].position = Vector3(0.5f, 0.5f, 0.5f);
model->vertex_data.vertices[2].position = Vector3(-0.5f, 0.5f, 0.5f);
model->vertex_data.vertices[3].position = Vector3(-0.5f, -0.5f, 0.5f);
model->vertex_data.vertices[4].position = Vector3(0.5f, -0.5f, 0.5f);
model->vertex_data.vertices[5].position = Vector3(0.5f, 0.5f, 0.5f);
model->vertex_data.vertices[0].color = Vector3(0.0f, 0.0f, 1.0f);
model->vertex_data.vertices[1].color = Vector3(0.0f, 1.0f, 1.0f);
model->vertex_data.vertices[2].color = Vector3(1.0f, 1.0f, 0.0f);
model->vertex_data.vertices[3].color = Vector3(1.0f, 0.0f, 1.0f);
model->vertex_data.vertices[4].color = Vector3(0.0f, 1.0f, 0.0f);
model->vertex_data.vertices[5].color = Vector3(1.0f, 1.0f, 1.0f);
model->vertex_data.vertices[0].uv = Vector2(0.0, 0.0);
model->vertex_data.vertices[1].uv = Vector2(1.0, 1.0);
model->vertex_data.vertices[2].uv = Vector2(0.0, 1.0);
model->vertex_data.vertices[3].uv = Vector2(0.0, 0.0);
model->vertex_data.vertices[4].uv = Vector2(1.0, 0.0);
model->vertex_data.vertices[5].uv = Vector2(1.0, 1.0);
}

13
src/model.h Normal file
View File

@ -0,0 +1,13 @@
#pragma once
#include <vector>
#include "basic.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "renderer.h"
struct Model {
Mesh vertex_data;
};
void init_model(Model *model);

337
src/renderer.cpp Normal file
View File

@ -0,0 +1,337 @@
#define STB_IMAGE_IMPLEMENTATION
#include "renderer.h"
bool init_renderer(Renderer *renderer, u32 width, u32 height) {
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
log(1, "%s error: failed to initialize GLAD\n", __FUNCTION__);
return false;
}
if (!GLAD_GL_VERSION_4_6) {
log(1, "%s error: failed to get at least OpenGL 4.6\n", __FUNCTION__);
return false;
}
{
bool success = init_frame_buffer(&renderer->frame_buffer, width, height);
if (!success) {
log(1, "%s error: could not init Framebuffer\n", __FUNCTION__);
return false;
}
log(1, "%s: framebuffer succesfully initialized\n", __FUNCTION__);
}
{
bool success = load_texture(&renderer->texture, "assets/textures/crate.png");
if (!success) {
log(1, "%s: texture loading failed\n", __FUNCTION__);
return false;
}
log(1, "%s: texture successfully loaded\n", __FUNCTION__);
}
{
bool success = init_vertex_buffer(&renderer->vertex_buffer);
if (!success) {
log(1, "%s: vertex buffer successfully created\n", __FUNCTION__);
return false;
}
}
{
bool success = load_shaders(&renderer->shader, "shaders/basic.vert", "shaders/basic.frag");
if (!success) {
log(1, "%s: shader loading failed\n", __FUNCTION__);
return false;
}
log(1, "%s: shaders succesfully loaded\n", __FUNCTION__);
}
return true;
}
void set_renderer_size(Renderer *renderer, u32 width, u32 height) {
resize_frame_buffer(&renderer->frame_buffer, width, height);
glViewport(0, 0, width, height);
}
void draw_renderer(Renderer *renderer) {
bind_frame_buffer(&renderer->frame_buffer);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
use_shader(&renderer->shader);
bind_texture(&renderer->texture);
bind_vertex_buffer(&renderer->vertex_buffer);
draw_vertex_buffer(GL_TRIANGLES, 0, renderer->triangle_count * 3);
unbind_vertex_buffer();
unbind_texture();
unbind_frame_buffer(&renderer->frame_buffer);
draw_frame_buffer(&renderer->frame_buffer);
}
void upload_renderer_data(Renderer *renderer, Mesh *vertex_data) {
renderer->triangle_count = vertex_data->vertices.size() / 3;
upload_vertex_buffer_data(&renderer->vertex_buffer, vertex_data);
}
void cleanup_renderer(Renderer *renderer) {
cleanup_shader(&renderer->shader);
cleanup_texture(&renderer->texture);
cleanup_vertex_buffer(&renderer->vertex_buffer);
cleanup_frame_buffer(&renderer->frame_buffer);
}
/*
* Frame buffer
*/
bool init_frame_buffer(Frame_Buffer *frame_buffer, u32 width, u32 height) {
frame_buffer->width = width;
frame_buffer->height = height;
glGenFramebuffers(1, &frame_buffer->buffer);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer->buffer);
glEnable(GL_FRAMEBUFFER_SRGB);
glGenTextures(1, &frame_buffer->color_tex);
glBindTexture(GL_TEXTURE_2D, frame_buffer->color_tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, frame_buffer->color_tex, 0);
log(1, "%s: added color buffer\n", __FUNCTION__);
glGenRenderbuffers(1, &frame_buffer->depth_buffer);
glBindRenderbuffer(GL_RENDERBUFFER, frame_buffer->depth_buffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, frame_buffer->depth_buffer);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
log(1, "%s: added depth render buffer\n", __FUNCTION__);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return check_frame_buffer_complete(frame_buffer);
}
bool check_frame_buffer_complete(Frame_Buffer *frame_buffer) {
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer->buffer);
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (result != GL_FRAMEBUFFER_COMPLETE) {
log(1, "%s error: framebuffer is NOT complete\n", __FUNCTION__);
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
log(1, "%s: framebuffer is complete\n", __FUNCTION__);
return true;
}
bool resize_frame_buffer(Frame_Buffer *frame_buffer, u32 width, u32 height) {
frame_buffer->width = width;
frame_buffer->height = height;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDeleteTextures(1, &frame_buffer->color_tex);
glDeleteRenderbuffers(1, &frame_buffer->depth_buffer);
glDeleteFramebuffers(1, &frame_buffer->buffer);
return init_frame_buffer(frame_buffer, width, height);
}
void draw_frame_buffer(Frame_Buffer *frame_buffer) {
glBindFramebuffer(GL_READ_FRAMEBUFFER, frame_buffer->buffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, frame_buffer->width, frame_buffer->height, 0, 0, frame_buffer->width, frame_buffer->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
void bind_frame_buffer(Frame_Buffer *frame_buffer) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame_buffer->buffer);
}
void unbind_frame_buffer(Frame_Buffer *frame_buffer) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
void cleanup_frame_buffer(Frame_Buffer *frame_buffer) {
unbind_frame_buffer(frame_buffer);
glDeleteTextures(1, &frame_buffer->color_tex);
glDeleteRenderbuffers(1, &frame_buffer->depth_buffer);
glDeleteFramebuffers(1, &frame_buffer->buffer);
}
/*
* Vertex buffer
*/
bool init_vertex_buffer(Vertex_Buffer *vertex_buffer) {
glGenVertexArrays(1, &vertex_buffer->vao);
glGenBuffers(1, &vertex_buffer->vbo);
glBindVertexArray(vertex_buffer->vao);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer->vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, position));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, color));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, uv));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return true;
}
void cleanup_vertex_buffer(Vertex_Buffer *vertex_buffer) {
glDeleteBuffers(1, &vertex_buffer->vbo);
glDeleteVertexArrays(1, &vertex_buffer->vao);
}
void upload_vertex_buffer_data(Vertex_Buffer *vertex_buffer, Mesh *vertex_data) {
glBindVertexArray(vertex_buffer->vao);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer->vbo);
glBufferData(GL_ARRAY_BUFFER, vertex_data->vertices.size() * sizeof(Vertex), &vertex_data->vertices.at(0), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void bind_vertex_buffer(Vertex_Buffer *vertex_buffer) {
glBindVertexArray(vertex_buffer->vao);
}
void unbind_vertex_buffer() {
glBindVertexArray(0);
}
void draw_vertex_buffer(u32 mode, u32 start, u32 num) {
glDrawArrays(mode, start, num);
}
/*
* Texture
*/
bool load_texture(Texture *texture, string filepath) {
texture->name = filepath;
stbi_set_flip_vertically_on_load(true);
u8* texture_data = stbi_load(filepath.c_str(), &texture->width, &texture->height, &texture->number_of_channels, 0);
if (!texture_data) {
stbi_image_free(texture_data);
return false;
}
glGenTextures(1, &texture->texture);
glBindTexture(GL_TEXTURE_2D, texture->texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width, texture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(texture_data);
return true;
}
void bind_texture(Texture *texture) {
glBindTexture(GL_TEXTURE_2D, texture->texture);
}
void unbind_texture() {
glBindTexture(GL_TEXTURE_2D, 0);
}
void cleanup_texture(Texture *texture) {
glDeleteTextures(1, &texture->texture);
}
/*
* Shaders
*/
bool load_shaders(Shader *shader, string vertex_shader_filepath, string fragment_shader_filepath) {
u32 vertex_shader = load_shader(vertex_shader_filepath, GL_VERTEX_SHADER);
if (!vertex_shader) {
return false;
}
u32 fragment_shader = load_shader(fragment_shader_filepath, GL_FRAGMENT_SHADER);
if (!fragment_shader) {
return false;
}
shader->program = glCreateProgram();
glAttachShader(shader->program, vertex_shader);
glAttachShader(shader->program, fragment_shader);
glLinkProgram(shader->program);
s32 is_program_linked;
glGetProgramiv(shader->program, GL_LINK_STATUS, &is_program_linked);
if (!is_program_linked) {
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return false;
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return true;
}
void cleanup_shader(Shader *shader) {
glDeleteProgram(shader->program);
}
u32 load_shader(string filepath, u32 shader_type) {
string shader_as_text;
shader_as_text = load_file_to_string(filepath);
const char*shader_source = shader_as_text.c_str();
u32 shader = glCreateShader(shader_type);
glShaderSource(shader, 1, (const GLchar**) &shader_source, 0);
glCompileShader(shader);
s32 is_shader_compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &is_shader_compiled);
if (!is_shader_compiled) {
return 0;
}
return shader;
}
void use_shader(Shader *shader) {
glUseProgram(shader->program);
}

87
src/renderer.h Normal file
View File

@ -0,0 +1,87 @@
#pragma once
#include <vector>
#include "logger.h"
#include "basic.h"
#include "file.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stb_image.h>
struct Vertex {
Vector3 position;
Vector3 color;
Vector2 uv;
};
struct Mesh {
std::vector<Vertex> vertices;
};
struct Frame_Buffer {
u32 width = 640;
u32 height = 480;
u32 buffer = 0;
u32 color_tex = 0;
u32 depth_buffer = 0;
};
struct Vertex_Buffer {
u32 vao = 0;
u32 vbo = 0;
};
struct Texture {
u32 texture = 0;
s32 width = 0;
s32 height = 0;
s32 number_of_channels = 0;
string name;
};
struct Shader {
u32 program = 0;
};
struct Renderer {
Shader shader;
Frame_Buffer frame_buffer;
Vertex_Buffer vertex_buffer;
Texture texture;
Mesh mesh;
s32 triangle_count = 0;
};
bool init_renderer(Renderer *renderer, u32 width, u32 height);
void set_renderer_size(Renderer *renderer, u32 width, u32 height);
void draw_renderer(Renderer *renderer);
void upload_renderer_data(Renderer *renderer, Mesh *vertex_data);
void cleanup_renderer(Renderer *renderer);
bool init_frame_buffer(Frame_Buffer *frame_buffer, u32 width, u32 height);
bool resize_frame_buffer(Frame_Buffer *frame_buffer, u32 width, u32 height);
bool check_frame_buffer_complete(Frame_Buffer *frame_buffer);
void bind_frame_buffer(Frame_Buffer *frame_buffer);
void unbind_frame_buffer(Frame_Buffer *frame_buffer);
void draw_frame_buffer(Frame_Buffer *frame_buffer);
void cleanup_frame_buffer(Frame_Buffer *frame_buffer);
bool init_vertex_buffer(Vertex_Buffer *vertex_buffer);
void cleanup_vertex_buffer(Vertex_Buffer *vertex_buffer);
void upload_vertex_buffer_data(Vertex_Buffer *vertex_buffer, Mesh *vertex_data);
void bind_vertex_buffer(Vertex_Buffer *vertex_buffer);
void unbind_vertex_buffer();
void draw_vertex_buffer(u32 mode, u32 start, u32 num);
bool load_texture(Texture *texture, string filepath);
void bind_texture(Texture *texture);
void unbind_texture();
void cleanup_texture(Texture *texture);
bool load_shaders(Shader *shader, string vertex_shader_filepath, string fragment_shader_filepath);
u32 load_shader(string filepath, u32 shader_type);
void use_shader(Shader *shader);
void cleanup_shader(Shader *shader);

153
src/window.cpp Normal file
View File

@ -0,0 +1,153 @@
#include "window.h"
#include "logger.h"
bool init(Window *window, u32 width, u32 height, string title) {
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_WAYLAND);
if (!glfwInit()) {
log(1, "%s: glfwInit() error\n", __FUNCTION__);
glfwTerminate();
return false;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
window->glfw_window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
if (!window->glfw_window) {
log(1, "%s: Could not create window\n", __FUNCTION__);
const char *desc;
int code = glfwGetError(&desc);
log(1, "GLFW error code: %d, description: %s\n", code,
desc ? desc : "No description given");
glfwTerminate();
return false;
}
glfwMakeContextCurrent(window->glfw_window);
window->renderer = new Renderer();
bool success = init_renderer(window->renderer, width, height);
if (!success) {
log(1, "%s: could not initialize renderer\n", __FUNCTION__);
glfwTerminate();
return false;
}
log(1, "%s: Renderer initialized\n", __FUNCTION__);
glfwSetWindowUserPointer(window->glfw_window, window);
glfwSetWindowSizeCallback(window->glfw_window, handle_window_resize_events);
glfwSetWindowCloseCallback(window->glfw_window, handle_close);
glfwSetKeyCallback(window->glfw_window, handle_key_events);
glfwSetCursorPosCallback(window->glfw_window, handle_mouse_position_events);
glfwSetMouseButtonCallback(window->glfw_window, handle_mouse_button_events);
window->model = new Model();
init_model(window->model);
log(1, "%s: Window initialized\n", __FUNCTION__);
return true;
}
void main_loop(Window *window) {
glfwSwapInterval(1);
upload_renderer_data(window->renderer, &window->model->vertex_data);
while (!glfwWindowShouldClose(window->glfw_window)) {
draw_renderer(window->renderer);
glfwSwapBuffers(window->glfw_window);
glfwPollEvents();
}
}
void cleanup(Window *window) {
log(1, "%s: Terminating Window\n", __FUNCTION__);
delete window->renderer;
delete window->model;
glfwDestroyWindow(window->glfw_window);
glfwTerminate();
}
void handle_close(GLFWwindow *gl_window) {
Window *window = static_cast<Window *>(glfwGetWindowUserPointer(gl_window));
log(1, "%s: Window got close event... bye!\n", __FUNCTION__);
}
void handle_key_events(GLFWwindow *gl_window, s32 key, s32 scancode, s32 action, s32 mods) {
Window *window = static_cast<Window *>(glfwGetWindowUserPointer(gl_window));
string action_name;
switch(action) {
case GLFW_PRESS:
action_name = "pressed";
break;
case GLFW_RELEASE:
action_name = "released";
break;
case GLFW_REPEAT:
action_name = "repeated";
break;
default:
action_name = "invalid";
break;
}
const char *key_name = glfwGetKeyName(key, 0);
log(1, "%s: key %s (key %i, scancode %i) %s\n", __FUNCTION__, key_name, key, scancode, action_name.c_str());
}
void handle_mouse_position_events(GLFWwindow *gl_window, f64 x_pos, f64 y_pos) {
Window *window = static_cast<Window *>(glfwGetWindowUserPointer(gl_window));
log(1, "%s: Mouse is at position %lf/%lf\n", __FUNCTION__, x_pos, y_pos);
}
void handle_mouse_button_events(GLFWwindow *gl_window, s32 button, s32 action, s32 mods) {
Window *window = static_cast<Window *>(glfwGetWindowUserPointer(gl_window));
string action_name;
switch(action) {
case GLFW_PRESS:
action_name = "pressed";
break;
case GLFW_RELEASE:
action_name = "released";
break;
case GLFW_REPEAT:
action_name = "repeated";
break;
default:
action_name = "invalid";
break;
}
string mouse_button_name;
switch(button) {
case GLFW_MOUSE_BUTTON_LEFT:
mouse_button_name = "left";
break;
case GLFW_MOUSE_BUTTON_RIGHT:
mouse_button_name = "right";
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
mouse_button_name = "middle";
break;
default:
mouse_button_name = "other";
break;
}
log(1, "%s: %s mouse button (%i) %s\n", __FUNCTION__, mouse_button_name.c_str(), button, action_name.c_str());
}
void handle_window_resize_events(GLFWwindow *gl_window, s32 width, s32 height) {
Window *window = static_cast<Window *>(glfwGetWindowUserPointer(gl_window));
set_renderer_size(window->renderer, width, height);
}

20
src/window.h Normal file
View File

@ -0,0 +1,20 @@
#pragma once
#include "basic.h"
#include "renderer.h"
#include "model.h"
struct Window {
GLFWwindow* glfw_window = nullptr;
Renderer* renderer = nullptr;
Model* model = nullptr;
};
bool init(Window *window, u32 width, u32 height, string title);
void main_loop(Window *window);
void cleanup(Window *window);
void handle_close(GLFWwindow *gl_window);
void handle_key_events(GLFWwindow *gl_window, s32 key, s32 scancode, s32 action, s32 mods);
void handle_mouse_position_events(GLFWwindow *gl_window, f64 x_pos, f64 y_pos);
void handle_mouse_button_events(GLFWwindow *gl_window, s32 button, s32 action, s32 mods);
void handle_window_resize_events(GLFWwindow *gl_window, s32 width, s32 height);