Skip to content

Create a shader cache #148

@Sebanisu

Description

@Sebanisu

Currently I'm reloading the shaders every time I make a map_sprite. I think since it's the same shader everytime. I could store them in some kinda pool or cache.

Though I need this thing to die before the context dies. So I don't want it to be living for ever till end of time as a Singleton.

Something like this maybe GPT

struct ShaderCache {
private:
    static std::array<glengine::Shader, static_cast<size_t>(ShaderID::Count)> shaders{};

public:
    static void Init() {
        shaders[std::to_underlying(ShaderID::Basic)] = loadShader("basic.vert", "basic.frag");
        shaders[std::to_underlying(ShaderID::Sprite)] = loadShader("sprite.vert", "sprite.frag");
        shaders[std::to_underlying(ShaderID::PostProcess)] = loadShader("post.vert", "post.frag");
    }

    static void Destroy() {
        for (auto& shader : shaders) {
            shader = glengine::Shader{}; // Reset to default
        }
    }

    static const glengine::Shader& Get(ShaderID id) {
        const auto idx = std::to_underlying(id);
        assert(idx < shaders.size());
        return shaders[idx];
    }
};

Batch render currently just holds onto the shader. so I'd need to let it keep a const reference in a wrapper or something. hmm :/

#include <functional>

class BatchRenderer {
public:
    explicit BatchRenderer(const glengine::Shader& shader)
        : m_shader(std::cref(shader)) {}

    void Render() const {
        m_shader.get().Bind(); // Bind is a const method
        // ...render stuff...
    }

private:
    std::reference_wrapper<const glengine::Shader> m_shader;
};

a reference wrapper is basically a like a bad weak pointer. heh. might be even better to use a shared pointer and a weak pointer because that checks to see if it's still there everytime. But this should be safe as long as the value doesn't go away ever. And we're planning to clean up after the draw loop ends and init before the draw loop starts. So it shouldn't go out of scope.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions