From fe96bc501c56fa8ef4eb11b72a7ce5516140094f Mon Sep 17 00:00:00 2001 From: GuilhermeWerner Date: Thu, 14 Jan 2021 15:11:53 -0300 Subject: [PATCH] Craete Custom Shader --- OpenGL/Source/Application.cpp | 81 +++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 3 deletions(-) diff --git a/OpenGL/Source/Application.cpp b/OpenGL/Source/Application.cpp index 2cda635..ec26bac 100644 --- a/OpenGL/Source/Application.cpp +++ b/OpenGL/Source/Application.cpp @@ -3,6 +3,56 @@ #include +static unsigned int CompileShader(unsigned int type, const std::string &source) +{ + unsigned int id = glCreateShader(type); + const char *src = source.c_str(); + + glShaderSource(id, 1, &src, nullptr); + glCompileShader(id); + + int result; + glGetShaderiv(id, GL_COMPILE_STATUS, &result); + + if (result == GL_FALSE) + { + int lenght; + glGetShaderiv(id, GL_INFO_LOG_LENGTH, &lenght); + + char *message = (char *)alloca(lenght + sizeof(char)); + + glGetShaderInfoLog(id, lenght, &lenght, message); + + std::cout << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader!" << std::endl; + std::cout << message << std::endl; + + glDeleteShader(id); + + return 0; + } + + return id; +} + +static unsigned int CreateShader(const std::string &vertexShader, const std::string &fragmentShader) +{ + unsigned int program = glCreateProgram(); + + unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader); + unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader); + + glAttachShader(program, vs); + glAttachShader(program, fs); + + glLinkProgram(program); + glValidateProgram(program); + + glDeleteShader(vs); + glDeleteShader(fs); + + return program; +} + int main() { GLFWwindow *window; @@ -31,9 +81,8 @@ int main() float positions[6] = { -0.5f, -0.5f, - 0.0f, 0.5f, - 0.5f, -0.5f - }; + 0.0f, 0.5f, + 0.5f, -0.5f}; unsigned int buffer; glGenBuffers(1, &buffer); @@ -43,6 +92,30 @@ int main() glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); glEnableVertexAttribArray(0); + std::string vertexShader = + "#version 330 core\n" + "\n" + "layout(location = 0) in vec4 position;\n" + "\n" + "void main()\n" + "{\n" + " gl_Position = position;\n" + "}\n"; + + std::string fragmentShader = + "#version 330 core\n" + "\n" + "layout(location = 0) out vec4 color;\n" + "\n" + "void main()\n" + "{\n" + " color = vec4(0.0, 1.0, 0.0, 1.0);\n" + "}\n"; + + unsigned int shader = CreateShader(vertexShader, fragmentShader); + + glUseProgram(shader); + /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { @@ -58,6 +131,8 @@ int main() glfwPollEvents(); } + glDeleteProgram(shader); + glfwTerminate(); return 0;