aboutsummaryrefslogtreecommitdiff
path: root/src/RenderBackend/OpenGL/ShaderProgram.cpp
blob: ba0e6dd4f25e5f50c59e1dc999b7bbeef8725daa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "../../../include/RenderBackend/OpenGL/ShaderProgram.hpp"

#include "../../../include/RenderBackend/OpenGL/Shader.hpp"
#include "../../../include/RenderBackend/OpenGL/opengl.hpp"

using namespace std;

namespace amalgine {
    ShaderProgram::ShaderProgram(u32 shader_program_id) : program_id(shader_program_id) {
        
    }
    
    ShaderProgram::~ShaderProgram()
    {
        GLint numAttachedShaders = 0;
        glGetProgramiv(program_id, GL_ATTACHED_SHADERS, &numAttachedShaders);
        
        GLuint *attachedShaders = new GLuint[numAttachedShaders];
        glGetAttachedShaders(program_id, numAttachedShaders, nullptr, attachedShaders);
        
        for(int i = 0; i < numAttachedShaders; ++i)
        {
            GLuint attachedShaderId = attachedShaders[i];
            glDetachShader(program_id, attachedShaderId);
        }
        
        glDeleteProgram(program_id);
        delete []attachedShaders;
    }
    
    // static
    Result<std::unique_ptr<ShaderProgram>> ShaderProgram::build(const std::vector<Shader*> &shaders) {
        u32 shader_program_id = glCreateProgram();
        if(shader_program_id == 0)
            return Result<std::unique_ptr<ShaderProgram>>::Err("Failed to create shader program");
        
        for(Shader *shader : shaders) {
            glAttachShader(shader_program_id, shader->id);
        }
        
        glLinkProgram(shader_program_id);
        std::unique_ptr<ShaderProgram> shader_program;
        shader_program.reset(new ShaderProgram(shader_program_id));
        return Result<std::unique_ptr<ShaderProgram>>::Ok(std::move(shader_program));
    }

    ShaderFrame ShaderProgram::create_frame() {
        return { program_id };
    }
}