Thursday, September 5, 2019

c++ - Separating game data/logic from rendering


I'm writing a game using C++ and OpenGL 2.1. I was thinking how could I separate the data/logic from rendering. At the moment I use a base class 'Renderable' that gives a pure virtual method to implement drawing. But every object has so specialized code, only the object knows how to properly set shader uniforms and organize vertex array buffer data. I end up with a lot of gl* function calls all over my code. Is there any generic way to draw the objects?



Answer



An idea is to use the Visitor design pattern. You need a Renderer implementation that knows how to render props. Every object can call the renderer instance to handle the render job.



In a few lines of pseudocode:


class Renderer {
public:
void render( const ObjectA & obj );
void render( const ObjectB & obj );
};


class ObjectA{
public:

void draw( Renderer & r ){ r.render( *this ) };
}

class ObjectB{
public:
void draw( Renderer & r ){ r.render( *this ) };
}

The gl* stuff is implemented by the renderer's methods, and the objects only store the data needed to be rendered, position, texture type, size ...etc.


Also, you can setup different renderers (debugRenderer, hqRenderer, ...etc) and use these dynamically, without changing the objects.



This also can be easy combined with Entity/Component systems.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...