From a711521f1770823d4e8c284308867981e412da5b Mon Sep 17 00:00:00 2001 From: Abdelrahman Date: Sat, 21 Sep 2024 18:01:11 +0100 Subject: [PATCH] Load shaders from file --- shaders/frag.glsl | 7 +++++++ shaders/vert.glsl | 7 +++++++ src/main.cc | 45 ++++++++++++++++++++++++++------------------- 3 files changed, 40 insertions(+), 19 deletions(-) create mode 100644 shaders/frag.glsl create mode 100644 shaders/vert.glsl diff --git a/shaders/frag.glsl b/shaders/frag.glsl new file mode 100644 index 0000000..249ff80 --- /dev/null +++ b/shaders/frag.glsl @@ -0,0 +1,7 @@ +#version 460 core + +out vec4 color; + +void main() { + color = vec4(0.93f, 0.42f, 0.35f, 1.0f); +}; diff --git a/shaders/vert.glsl b/shaders/vert.glsl new file mode 100644 index 0000000..27d159c --- /dev/null +++ b/shaders/vert.glsl @@ -0,0 +1,7 @@ +#version 460 core + +in vec4 position; + +void main() { + gl_Position = vec4(position.x, position.y, position.z, position.w); +}; diff --git a/src/main.cc b/src/main.cc index 2354d92..7ed3a65 100644 --- a/src/main.cc +++ b/src/main.cc @@ -41,13 +41,14 @@ struct App { bool running; }; -int init (App &app); -void create_vertex_spec (App &app); -void create_graphics_pipeline(App &app); -void run_main_loop (App &app); -void cleanup (App &app); -GLuint create_shader_program (const std::string &vertex_shader_source, const std::string &fragment_shader_source); -GLuint compile_shader (GLuint type, const std::string &source); +int init (App &app); +void create_vertex_spec (App &app); +void create_graphics_pipeline(App &app); +void run_main_loop (App &app); +void cleanup (App &app); +GLuint create_shader_program (const std::string &vertex_shader_source, const std::string &fragment_shader_source); +GLuint compile_shader (GLuint type, const std::string &source); +std::string load_shader (const std::string &filepath); int main() { App app = {}; @@ -148,18 +149,8 @@ void create_vertex_spec(App &app) { } void create_graphics_pipeline(App &app) { - const std::string vs_source = - "#version 460 core\n" - "in vec4 position;\n" - "void main() {\n" - " gl_Position = vec4(position.x, position.y, position.z, position.w);\n" - "}"; - const std::string fs_source = - "#version 460 core\n" - "out vec4 color;\n" - "void main() {\n" - " color = vec4(0.93f, 0.42f, 0.35f, 1.0f);\n" - "}"; + const std::string vs_source = load_shader("shaders/vert.glsl"); + const std::string fs_source = load_shader("shaders/frag.glsl"); app.shader_program = create_shader_program(vs_source, fs_source); } @@ -256,3 +247,19 @@ GLuint compile_shader(GLuint type, const std::string &source) { return shader; } + +std::string load_shader(const std::string &filepath) { + FILE *fp = fopen(filepath.c_str(), "r"); + if (!fp) { + return ""; + } + + std::string output = {}; + + char buf[1024] = {0}; + while (fgets(buf, sizeof(buf), fp)) { + output += buf; + } + + return output; +}