matus-chochlik / oglplus

OGLplus is a collection of open-source, cross-platform libraries which implement an object-oriented facade over the OpenGL® (version 3 and higher) and also OpenAL® (version 1.1) and EGL (version 1.4) C-language APIs. It provides wrappers which automate resource and object management and make the use of these libraries in C++ safer and more convenient.
http://oglplus.org/
Boost Software License 1.0
492 stars 72 forks source link

Declaring objects prior to context initialization #119

Closed acdemiralp closed 9 years ago

acdemiralp commented 9 years ago

Hello, I am attempting to write a simple graphics sandbox using oglplus. However even just declaring most of the structures (all except oglplus::Context) prior to setting up a GL context results in a runtime error. This prevents my engine structures to carry any oglplus members such as:

class Mesh_Renderer : public Component
{
public:
    Mesh_Renderer(Mesh* _mesh = nullptr);

    void start     () override;
    void update    () override;
    void destroy   () override;

private:
    Mesh* mesh_;

    oglplus::VertexArray    vao;
    oglplus::Buffer     vbo_vert;
    oglplus::Buffer     vbo_norm;
    oglplus::Buffer     vbo_uv;
    oglplus::Buffer     ibo;
};

This will fail the first time I reference it in the code such as:

auto mesh_renderer  = resources->get_mesh_renderers().create(model->get_meshes().at(0));
object->add_component(mesh_renderer);

engine.run(); // This is where window and context gets initialized.

This is because window and context are not initialized at the time the constructor of Mesh_Renderer is called (and hence all the VertexArray and Buffer's constructors are called prior to context creation).

Everything obviously works fine if I convert VertexArray and Buffer members to pointers to objects and summon them separately on the heap after creating the context, e.g. in the start() method.

I know that oglplus is a thin wrapper, and I know that it does OGL calls in the constructor in order to closely couple the object with its OGL counterpart.

But could there be a way to delay the initialization of the oglplus structures to the context creation so I can declare them as members of objects?

matus-chochlik commented 9 years ago

Hi, You can for example use the Optional<Object> wrapper (implemented in oglplus/object/optional.hpp). The default constructor of Optional does not attempt to initialize the GL object and can be move-assigned later.

acdemiralp commented 9 years ago

Ah this is exactly what I was seeking, thank you very much.