How do I avoid this singleton-like design pattern? - c++

We have a rendering pipeline and our current code creates an instance for every stage of the pipeline. This means that as we update our code, we will be constantly updating the pipeline (or multiple sets of pipelines) code. This feels like a point where we should have additional abstraction, but we're not sure how to proceed.
Edit: It seems my pseudo code is not well understood. Perhaps a diagram will more easily explain the pattern.
Link to a block diagram: http://yuml.me/0650d1bf.svg
// yuml.me
[GenericRenderStage|render|Parent Class]<---[Shadow1RenderStage|render|Derived Class]
[Shadow1RenderStage|render|Derived Class]<---[_shadowRenderStage1|Singleton Object]
[GenericRenderStage|render|Parent Class]<---[Shadow2RenderStage|render|Derived Class]
[Shadow2RenderStage|render|Derived Class]<---[_shadowRenderStage2|Singleton Object]
[GenericRenderStage|render|Parent Class]<---[ShadowNRenderStage|render|Derived Class]
[ShadowNRenderStage|render|Derived Class]<---[_shadowRenderStageN|Singleton Object]
Psuedo-c++ code of parent class:
class GenericRenderStage(...) {
/// Render method
virtual void render(void) {
/// handles drawing code
}
class Shadow1RenderStage : GenericRenderStage(...) {
/// Render method
void render(void) {
/// handles custom drawing for shadow1 stage
}
class Shadow2RenderStage : GenericRenderStage(...) {
/// Render method
void render(void) {
/// handles custom drawing for shadow2 stage
}
...
class ShadowNRenderStage : GenericRenderStage(...) {
/// Render method
void render(void) {
/// handles custom drawing for shadowN stage
}
We then have a set of the same type of pattern for our pipelines...
class GenericRenderPipeLine(...) {
/// Render method
virtual void render(void) {
/// handles drawing code
}
class ShadowRenderPipeline : GenericRenderPipeLine() {
/// instantiate stages for this pipeline
ShadowRenderPipeline() {
shadow1Stage = new Shadow1RenderStage();
shadow2Stage = new Shadow2RenderStage();
...
shadowNStage = new ShadowNRenderStage();
}
/// Render method
void render(void) {
/// setup fbo
/// for each render stage, render
shadow1Stage.render()
shadow2Stage.render()
...
shadowNStage.render()
/// handle fbo
}
Something here seems really wrong with the pattern. We've got a parent class that is basically a set of virtual methods to be inherited by a customized class that only ever has one instance.

From what I understand (please correct me if I'm wrong), each render stage is unique and doesn't really follow any specific pattern. So, I think it's best to keep those the way they are; have each render stage in a self-contained file/class.
However, I think you could reduce a lot of work by eliminating your render pipeline inheritance structure. All of these appear to be the same (i.e. they have some number of stages and call render() on each of them). What if you instead had a dynamic, generic pipeline?
#include <vector>
#include <memory>
class DynamicRenderPipeline {
private:
std::vector<std::unique_ptr<GenericRenderStage>> renderStages;
public:
void add(std::unique_ptr<GenericRenderStage> renderStage) {
renderStages.push_back(std::move(renderStage));
}
void render() {
for (auto& stage : renderStages) {
stage->render();
}
}
};
int main() {
DynamicRenderPipeline pipeline;
pipeline.add(std::unique_ptr<GenericRenderStage>(new RenderStage1()));
pipeline.add(std::unique_ptr<GenericRenderStage>(new RenderStage2()));
pipeline.add(std::unique_ptr<GenericRenderStage>(new RenderStage3()));
pipeline.add(std::unique_ptr<GenericRenderStage>(new RenderStage4()));
pipeline.add(std::unique_ptr<GenericRenderStage>(new RenderStage5()));
pipeline.render();
}
You can now just create instances of DynamicRenderPipeline and add any stages you wish. When you call render() on it, it will loop through all of the added render stages in the proper order. Now your pipeline only depends on the GenericRenderStage interface. If you're not using C++11 you could do the same with raw pointers (instead of unique_ptr), but you'd have to make sure to clean up your vector in the pipeline's destructor.

The fact that you only ever instantiate one object of each one of the many classes you created is a manifestation of a common problem in class-based OOP à la Java/C++. It is somewhat easier to circumvent in C++ than in Java.
The problem is simply that all code has to reside in class definitions if you want to go the pure class-based OO way. For instance, in Java, if you wanted to create many vastly different comparators (boolean predicates of two values of the same type), you ideally would have to create just as many subclasses of the standard Java generic interface Comparator. Actually, I lied, because in many cases you could just use the
new Comparator<Type>() {
public bool compare(Type a, Type b) { /* */ }
}
syntax, which is the closest Java ever got to having first-class citizen functions prior to Java 8. However, even that syntax doesn't work when you want to allow the creation of customized comparators, and you then have to write an entire class like so in order to void repeating yourself:
class CompareIntsPlusX implements Comparator<int>
{
private int number;
public CompareIntsPlusX(int number) {
this.number = number;
}
public bool compare(int x, int y) {
return x < y + number;
}
}
Comparator<int> myComparator = new CompareIntsPlusX(3);
and we end up with very cumbersome syntax for even the simplest of objects. Notice that in any (somewhat) functional programming language like Javascript, this problem would be more easily solved.
The same phenomenon is happening here. You have been going the class-based OO way in your pipeline stage definitions, and now you realise it's not scalable because you only need one object carrying with it the code defined in its class, and you need many such objects.
Those objects are what you referred to as "singletons" even though they do not in any way follow the Singleton design pattern. They are de facto singletons, and the reason for this is that they are actually just functions in disguise. Their only goal is to "carry" with them a void render() method.
From here you have several solutions:
If the render functions are vastly different, and you cannot generate them from one class that accepts parameters like we did with the CompareIntsPlusX Java class above, that is to say if you cannot factor your code, then
If you are using a functional style of C++03 (I wouldn't recommend that) or of C++11 (I have never used what I'm about to suggest) then you can simply use one RenderStage class defined like so:
class RenderStage
{
private:
std::function<void()> renderFunction;
public:
RenderStage(std::function<void()> renderFunction)
: renderFunction(renderFunction)
{ }
void render() {
renderFunction();
}
}
/* Somewhere else in the code, create your render stages */
RenderStage r1([]() {
// blah blah
});
// You can also capture stuff!
Texture tex;
RenderStage r2([&tex]() {
// blah blah
});
In C++03, we would use function pointers (whose functions are defined in a namespace because we don't want to be polluting the global namespace). Note that in the C++11 case, we only need to use std::function if captures are needed in the lambdas. If not, then just use function pointers.
Else, if you want to keep using an OO style, then create as many classes as you need and don't feel bad about it. In fact, creating anonymous classes is what the compiler does behind your back when you create lambdas (in fact it creates classes if your lambdas have captures and simple functions if not) and the Java compiler does it too when you "instantiate an interface".
Else, if the render methods can be factored, i.e. if instead of N classes you can have one with a constructor that allows for customization, then do that instead.
It's probable that a mix of the first and second solutions is what you need. You should try the second solution of having customizable render stage objects before you go for the more complex solution.

Related

c++ Hold instructions for a later time

I am trying to design a UIDraw method. I want to declare what UI elements to draw in the main Draw method But then Have a separate UIDraw Method later in the code. So I need a way to store instructions to execute in this new function. I hope it makes sense.
Something like this:
Draw();
DrawUI();
But say what UI to draw in the Draw() function.
Any ideas on how to tackle this problem?
There are many ways to tackle this problem depending on what exactly you need. One approach popular in the OO world is the so called Command Pattern (similar approaches exist in other programming paradigms, they just have either different names or are considered so obvious they don't even get a specific name at all).
The basic idea is this: You want to execute some command, but the time you want to execute the command and the time you decide what command to execute are different. So the way to solve this problem is to simply create an object that contains the information you need to execute the command, pass that object to the place that decides when the execution should happen, and then that code can run the command as it pleases.
Here’s a mockup of what that might look like in C++ (note: didn't actually compile this code, might contain minor errors – just meant to convey the idea).
#include <memory>
#include <vector>
/// this is an abstract class that gives us an interface to use
class DrawCommand {
public:
virtual void Draw() = 0;
};
/// one kind of thing you might want to draw
class DrawTree : public DrawCommand {
public:
void Draw() override {
// tree drawing code
}
};
/// another kind of thing you might want to draw
class DrawCat : public DrawCommand {
public:
void Draw() override {
// cat drawing code
}
};
/// we can even come up with ways to combine these in interesting ways
class DrawABunchOfThings : public DrawCommand {
std::vector<std::unique_ptr<DrawCommand>> things;
public:
DrawABunchOfThings(std::vector<std::unique_ptr<DrawCommand>> things)
: things{std::move(things)}
{}
void Draw() override {
for(auto &thing : things) {
thing->Draw();
}
}
};
/// this is where we decide what we will draw
std::unique_ptr<DrawCommand> PrepareDraw() {
if(someCondition) {
// just a cat
return std::make_unique<DrawCat>();
} else if(someOtherCondition) {
// just a tree
return std::make_unique<DrawTree>();
} else {
// forest with a cat hidden inside
return std::make_unique<DrawABunchOfThings>(
std::vector<std::unique_ptr<DrawCommand>>{
std::make_unique<DrawTree>(),
std::make_unique<DrawTree>(),
std::make_unique<DrawCat>()
std::make_unique<DrawTree>(),
}
);
}
}
/// this is where we will do the actual drawing
/// note that any arbitrary amount of code can go between
/// PrepareDraw and ExecuteDraw
void ExecuteDraw(DrawCommand &command) {
// this can of course have a bunch of elaborate
// code here as well -- also, DrawCommand::Draw might
// take extra parameters here, like 2D or 3D transforms,
// time since we last drew something, or whatever
command.Draw();
}
Note that if you only need a single method on this thing C++ already has this in the form of std::function, so you could just say using DrawCommand = std::function<void()>; and be done with it, which would also immediately allow you to use it with lambdas:
int nTimes = 10;
DrawCommand drawNTimesCommand = [nTimes]() {
for(int i = 0; i < nTimes; ++i) {
// draw something
}
};
// --- any code you like here ---
// actually execute the draw command
drawNTimesCommand();

c++ particle system inheritance

i'm creating particle system and i want to have possibility to choose what kind of object will be showing on the screen (like simply pixels, or circle shapes). I have one class in which all parameters are stored (ParticleSettings), but without those entities that stores points, or circle shapes, etc. I thought that i may create pure virtual class (ParticlesInterface) as a base class, and its derived classes like ParticlesVertex, or ParticlesCircles for storing those drawable objects. It is something like that:
class ParticlesInterface
{
protected:
std::vector<ParticleSettings> m_particleAttributes;
public:
ParticlesInterface(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
const std::vector<ParticleSettings>& getParticleAttributes() { return m_particleAttributes; }
...
}
and :
class ParticlesVertex : public ParticlesInterface
{
private:
std::vector<sf::Vertex> m_particleVertex;
public:
ParticlesVertex(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
std::vector<sf::Vertex>& getParticleVertex() { return m_particleVertex; }
...
}
So... I know that i do not have access to getParticleVertex() method by using polimorphism. And I really want to have that access. I want to ask if there is any better solution for that. I have really bad times with decide how to connect all that together. I mean i was thinking also about using template classes but i need it to be dynamic binding not static. I thought that this idea of polimorphism will be okay, but i'm really need to have access to that method in that option. Can you please help me how it should be done? I want to know what is the best approach here, and also if there is any good answer to that problem i have if i decide to make that this way that i show you above.
From the sounds of it, the ParticlesInterface abstract class doesn't just have a virtual getParticleVertex because that doesn't make sense in general, only for the specific type ParticlesVertex, or maybe a group of related types.
The recommended approach here is: Any time you need code that does different things depending on the actual concrete type, make those "different things" a virtual function in the interface.
So starting from:
void GraphicsDriver::drawUpdate(ParticlesInterface &particles) {
if (auto* vparticles = dynamic_cast<ParticlesVertex*>(&particles)) {
for (sf::Vertex v : vparticles->getParticleVertex()) {
draw_one_vertex(v, getCanvas());
}
} else if (auto* cparticles = dynamic_cast<ParticlesCircle*>(&particles)) {
for (CircleWidget& c : cparticles->getParticleCircles()) {
draw_one_circle(c, getCanvas());
}
}
// else ... ?
}
(CircleWidget is made up. I'm not familiar with sf, but that's not the point here.)
Since getParticleVertex doesn't make sense for every kind of ParticleInterface, any code that would use it from the interface will necessarily have some sort of if-like check, and a dynamic_cast to get the actual data. The drawUpdate above also isn't extensible if more types are ever needed. Even if there's a generic else which "should" handle everything else, the fact one type needed something custom hints that some other future type or a change to an existing type might want its own custom behavior at that point too. Instead, change from a thing code does with the interface to a thing the interface can be asked to do:
class ParticlesInterface {
// ...
public:
virtual void drawUpdate(CanvasWidget& canvas) = 0;
// ...
};
class ParticlesVertex {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
class ParticlesCircle {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
Now the particles classes are more "alive" - they actively do things, rather than just being acted on.
For another example, say you find ParticlesCircle, but not ParticlesVertex, needs to make some member data updates whenever the coordinates are changed. You could add a virtual void coordChangeCB() {} to ParticlesInterface and call it after each motion model tick or whenever. With the {} empty definition in the interface class, any class like ParticlesVertex that doesn't care about that callback doesn't need to override it.
Do try to keep the interface's virtual functions simple in intent, following the Single Responsibility Principle. If you can't write in a sentence or two what the purpose or expected behavior of the function is in general, it might be too complicated, and maybe it could more easily be thought of in smaller steps. Or if you find the virtual overrides in multiple classes have similar patterns, maybe some smaller pieces within those implementations could be meaningful virtual functions; and the larger function might or might not stay virtual, depending on whether what remains can be considered really universal for the interface.
(Programming best practices are advice, backed by good reasons, but not absolute laws: I'm not going to say "NEVER use dynamic_cast". Sometimes for various reasons it can make sense to break the rules.)

Engine to render different types of graphic objects

I'm trying to write a class (some sort of graphics engine) basically it's purpose is to render ANYTHING that I pass into it. In most tutorials I've seen, objects draw themselves. I'm not sure if that's how things are supposed to work. I've been searching the internet trying to come up with different ways to handle this problem, I've been reviewing function templates and class templates over and over again (which sounds like the solution I could be looking for) but when I try using templates, it just seems messy to me (possibly because I don't fully understand how to use them) and then I'll feel like taking the template class down, then I'll give it a second try but then I just take it down again, I'm not sure if that's the way to go but it might be. Originally it was tiled-based only (including a movable player on screen along with a camera system), but now I've trying to code up a tile map editor which has things such as tool bars, lists, text, possibly even primitives on screen in the future, etc. and I'm wondering how I will draw all those elements onto the screen with a certain procedure (the procedure isn't important right now, I'll find that out later). If any of you were going to write a graphics engine class, how would you have it distinguish different types of graphic objects from one another, such as a primitive not being drawn as a sprite or a sphere primitive not being drawn as a triangle primitive, etc.? Any help would be appreciated. :)
This is the header for it, it's not functional right now because I've been doing some editing on it, Just ignore the part where I'm using the "new" keyword, I'm still learning that, but I hope this gives an idea for what I'm trying to accomplish:
//graphicsEngine.h
#pragma once
#include<allegro5\allegro.h>
#include<allegro5\allegro_image.h>
#include<allegro5\allegro_primitives.h>
template <class graphicObjectData>
class graphicsEngine
{
public:
static graphicObjectData graphicObject[];
static int numObjects;
static void setup()
{
al_init_image_addon();
al_init_primitives_addon();
graphicObject = new graphicObjectData [1]; //ignore this line
}
template <class graphicObjectData> static void registerObject(graphicObjectData &newGraphicObject) //I'm trying to use a template function to take any type of graphic object
{
graphicObject[numObjects] = &newObject;
numObjects++;
}
static void process() //This is the main process where EVERYTHING is supposed be drawn
{
int i;
al_clear_to_color(al_map_rgb(0,0,0));
for (i=0;i<numObjects;i++) drawObject(graphicObject[i]);
al_flip_display();
}
};
I am a huge fan of templates, but you may find in this case that they are cumbersome (though not necessarily the wrong answer). Since it appears you may be wanting diverse object types in your drawing container, inheritance may actually be a stronger solution.
You will want a base type which provides an abstract interface for drawing. All this class needs is some function which provides a mechanism for the actual draw process. It does not actually care how drawing occurs, what's important is that the deriving class knows how to draw itself (if you want to separate your drawing and your objects, keep reading and I will try to explain a way to accomplish this):
class Drawable {
public:
// This is our interface for drawing. Simply, we just need
// something to instruct our base class to draw something.
// Note: this method is pure virtual so that is must be
// overriden by a deriving class.
virtual void draw() = 0;
// In addition, we need to also give this class a default virtual
// destructor in case the deriving class needs to clean itself up.
virtual ~Drawable() { /* The deriving class might want to fill this in */ }
};
From here, you would simply write new classes which inherit from the Drawable class and provide the necessary draw() override.
class Circle : public Drawable {
public:
void draw() {
// Do whatever you need to make this render a circle.
}
~Circle() { /* Do cleanup code */ }
};
class Tetrahedron : public Drawable {
public:
void draw() {
// Do whatever you need to make this render a tetrahedron.
}
~Tetrahedron() { /* Do cleanup code */ }
};
class DrawableText : public Drawable {
public:
std::string _text;
// Just to illustrate that the state of the deriving class
// could be variable and even dependent on other classes:
DrawableText(std::string text) : _text(text) {}
void draw() {
// Yet another override of the Drawable::draw function.
}
~DrawableText() {
// Cleanup here again - in this case, _text will clean itself
// up so nothing to do here. You could even omit this since
// Drawable provides a default destructor.
}
};
Now, to link all these objects together, you could simply place them in a container of your choosing which accepts references or pointers (or in C++11 and greater, unique_ptr, shared_ptr and friends). Setup whatever draw context you need and loop through all the contents of the container calling draw().
void do_drawing() {
// This works, but consider checking out unique_ptr and shared_ptr for safer
// memory management
std::vector<Drawable*> drawable_objects;
drawable_objects.push_back(new Circle);
drawable_objects.push_back(new Tetrahedron);
drawable_objects.push_back(new DrawableText("Hello, Drawing Program!"));
// Loop through and draw our circle, tetrahedron and text.
for (auto drawable_object : drawable_objects) {
drawable_object->draw();
}
// Remember to clean up the allocations in drawable_objects!
}
If you would like to provide state information to your drawing mechanism, you can require that as a parameter in the draw() routine of the Drawable base class:
class Drawable {
public:
// Now takes parameters which hold program state
virtual void draw(DrawContext& draw_context, WorldData& world_data) = 0;
virtual ~Drawable() { /* The deriving class might want to fill this in */ }
};
The deriving classes Circle, Tetrahedron and DrawableText would, of course, need their draw() signatures updated to take the new program state, but this will allow you to do all of your low-level drawing through an object which is designed for graphics drawing instead of burdening the main class with this functionality. What state you provide is solely up to you and your design. It's pretty flexible.
BIG UPDATE - Another Way to Do It Using Composition
I've been giving it careful thought, and decided to share what I've been up to. What I wrote above has worked for me in the past, but this time around I've decided to go a different route with my engine and forego a scene graph entirely. I'm not sure I can recommend this way of doing things as it can make things complicated, but it also opens the doors to a tremendous amount of flexibility. Effectively, I have written lower-level objects such as VertexBuffer, Effect, Texture etc. which allow me to compose objects in any way I want. I am using templates this time around more than inheritance (though intheritance is still necessary for providing implementations for the VertexBuffers, Textures, etc.).
The reason I bring this up is because you were talking about getting a larger degree of seperation. Using a system such as I described, I could build a world object like this:
class World {
public:
WorldGeometry geometry; // Would hold triangle data.
WorldOccluder occluder; // Runs occlusion tests against
// the geometry and flags what's visible and
// what is not.
WorldCollider collider; // Handles all routines for collision detections.
WorldDrawer drawer; // Draws the world geometry.
void process_and_draw();// Optionally calls everything in necessary
// order.
};
Here, i would have multiple objects which focus on a single aspect of my engine's processing. WorldGeometry would store all polygon details about this particular world object. WorldOccluder would do checks against the camera and geometry to see which patches of the world are actually visible. WorldCollider would process collission detection against any world objects (omitted for brevity). Finally, WorldDrawer would actually be responsible for the drawing of the world and maintain the VertexBuffer and other lower-level drawing objects as needed.
As you can see, this works a little more closely to what you originally asked as the geometry is actually not used only for rendering. It's more data on the polygons of the world but can be fed to WorldGeometry and WorldOccluder which don't do any drawing whatsoever. In fact, the World class only exists to group these similar classes together, but the WorldDrawer may not be dependent on a World object. Instead, it may need a WorldGeometry object or even a list of Triangles. Basically, your program structure becomes highly flexible and dependencies begin to disappear since objects do not inherit often or at all and only request what they absolutely require to function. Case in point:
class WorldOccluder {
public:
// I do not need anything more than a WorldGeometry reference here //
WorldOccluder(WorldGeometry& geometry) : _geometry(geometry)
// At this point, all I need to function is the position of the camera //
WorldOccluderResult check_occlusion(const Float3& camera) {
// Do all of the world occlusion checks based on the passed
// geometry and then return a WorldOccluderResult
// Which hypothetically could contain lists for visible and occluded
// geometry
}
private:
WorldGeometry& _geometry;
};
I chose the WorldOccluder as an example because I've spent the better part of the day working on something like this for my engine and have used a class hierarchy much like above. I've got boxes in 3D space changing colors based on if they should be seen or not. My classes are very succinct and easy to follow, and my entire project hierarchy is easy to follow (I think it is anyway). So this seems to work just fine! I love being on vacation!
Final note: I mentioned templates but didn't explain them. If I have an object that does processing around drawing, a template works really well for this. It avoids dependencies (such as through inheritence) while still giving a great degree of flexibility. Additionally, templates can be optimized by the compiler by inlining code and avoiding virtual-style calls (if the compiler can deduce such optimizations):
template <typename TEffect, TDrawable>
void draw(TEffect& effect, TDrawable& drawable, const Matrix& world, const Matrix& view, const Matrix& projection) {
// Setup effect matrices - our effect template
// must provide these function signatures
effect.world(world);
effect.view(view);
effect.projection(projection);
// Do some drawing!
// (NOTE: could use some RAII stuff here in case drawable throws).
effect.begin();
for (int pass = 0; pass < effect.pass_count(); pass++) {
effect.begin_pass(pass);
drawable.draw(); // Once again, TDrawable objects must provide this signature
effect.end_pass(pass);
}
effect.end();
}
My technique might really suck, but I do it like this.
class entity {
public:
virtual void render() {}
};
vector<entity> entities;
void render() {
for(auto c : entities) {
c->render();
}
}
Then I can do stuff like this:
class cubeEntity : public entity {
public:
virtual void render() override {
drawCube();
}
};
class triangleEntity : public entity {
public:
virtual void render() override {
drawTriangle();
}
};
And to use it:
entities.push_back(new cubeEntity());
entities.push_back(new triangleEntity());
People say that it's bad to use dynamic inheritance. They're a lot smarter than me, but this approach has been working fine for a while. Make sure to make all your destructors virtual!
The way the SFML graphics library draws objects (and the way I think is most manageable) is to have all drawable objects inherit from a 'Drawable' class (like the one in David Peterson's answer), which can then be passed to the graphics engine in order to be drawn.
To draw objects, I'd have:
A Base class:
class Drawable
{
int XPosition;
int YPosition;
int PixelData[100][100]; //Or whatever storage system you're using
}
This can be used to contain information common to all drawable classes (like position, and some form of data storage).
Derived Subclasses:
class Triangle : public Drawable
{
Triangle() {} //overloaded constructors, additional variables etc
int indigenous_to_triangle;
}
Because each subclass is largely unique, you can use this method to create anything from sprites to graphical-primitives.
Each of these derived classes can then be passed to the engine by reference with
A 'Draw' function referencing the Base class:
void GraphicsEngine::draw(const Drawable& _object);
Using this method, a template is no longer necessary. Unfortunately your current graphicObjectData array wouldn't work, because derived classes would be 'sliced' in order to fit in it. However, creating a list or vector of 'const Drawable*' pointers (or preferably, smart pointers) would work just as well for keeping tabs on all your objects, though the actual objects would have to be stored elsewhere.
You could use something like this to draw everything using a vector of pointers (I tried to preserve your function and variable names):
std::vector<const Drawable*> graphicObject; //Smart pointers would be better here
static void process()
{
for (int i = 0; i < graphicObject.size(); ++i)
draw(graphicObject[i]);
}
You'd just have to make sure you added each object to the list as it was created.
If you were clever about it, you could even do this in the construction and destruction:
class Drawable; //So the compiler doesn't throw an error
std::vector<const Drawable*> graphicObject;
class Drawable
{
Triangle() {} //overloaded constructors, additional variables etc
int indigenous_to_triangle;
std::vector<const Drawable*>::iterator itPos;
Drawable() {
graphicObject.push_back(this);
itPos = graphicObject.end() - 1;
}
~Drawable() {
graphicObject.erase(itPos);
}
}
Now you can just create objects and they'll be drawn automatically when process() is called! And they'll even be removed from the list once they're destroyed!
All the above ideas have served me well in the past, so I hope I've helped you out, or at least given you something to think about.

Creating classes to represent different permutations of a type

Suppose I have a class structure like (simplifying the actual classes I have):
class Graph
{
};
class DerivedGraph : public Graph
{
};
class DerivedGraph2 : public Graph
{
};
I want to expand this structure to account for different variations of the same graph. Ideally I would like to be able to do something like:
class Graph
{
};
// Removed
//class DerivedGraph : public Graph
//{
//};
// Removed
//class DerivedGraph2 : public Graph
//{
//};
class DerivedGraph3 : public Graph // really just a mode of DerivedGraph
{
};
class DerivedGraph4 : public Graph // really just a second mode of DerivedGraph
{
};
class DerivedGraph5 : public Graph // really just a mode of DerivedGraph2
{
};
class DerivedGraph6 : public Graph // really just a second mode of DerivedGraph2
{
};
But you can quickly see the problem here -- I am having to create too many classes here. Also, the base class is extremely complex and large (the bottom line is that it just plain sucks) ... so I don't want to make too many structural changes. I want the flexibility of defining things at the level of just the graph itself but at the same time have the flexibility of defining things for a particular mode of one graph type. I would like to be able to use virtual functions such as DoesGraphSupportNormalizedData() or something like that (this is just a simple example). Each class would then override this method.
Another idea I had was to create a separate class structure for the modes themselves (the Graph class would create an instance of it), like:
class BaseMode
{
};
class Mode1 : public BaseMode
{
};
class Mode2 : public BaseMode
{
};
Now the problem is that these mode classes need access to several pieces of data from the Graph class ... and I really don't want to pass all of that information. The mode class would then become just as useless and wouldn't be flexible at all. I just can't think of a clean way to deal with this. The best I could come up with is to have the mode classes do what it can without having to pass all kinds of crap to it but now the interface is just goofy and awkward. Any ideas?
You can either user and interface or use inherited classes from what I can gather from your description.
If you use a base-class and inherit off of it just have the things you don't want derived classes to have just give them the private access modifier and then protected or public for the others (depending on the situation of course). That way your derived classes only take what information they need. You could also have a instance variable that needs to be set in each of lower classes to define things about each derived class. Access modifiers are your friends.
If you use an interface just include everything each graph will need and then when building the individual classes just customize them from there to include the specialties.
If it were up to me, personally, I would go with inheritance over an interface but that's just me.
I ran in this kind of a problem before (and still now and then...)
In this case, you may be taking it the wrong way, what you're looking into is device a specialized function depending on the type of graph and mode. Inheritance is nice, but it has its limits as you mentioned. Especially because the user may want to switch the type of graph, but keep is existing graph object. Inheritance is not helpful in that case.
One way to do something like this is to create functions that get called depending on the current type and mode. Say you have to draw lines and the mode can be set to LINE or DOTS. You could have two functions that draw a line and are specific to a mode or another:
void Graph::draw_line_line(line l)
{
// draw a line
}
void Graph::draw_line_dots(line l)
{
// draw a dots along the line
}
Now you can define a type which represents that type of render functions and a variable member for it:
typedef void (Graph::*draw_line_func)(line l);
draw_line_func m_draw_line;
With that in hands, you can program your set_mode() function, something like this:
void Graph::set_mode(mode_t mode)
{
m_mode = mode; // save for get_mode() to work
switch(mode)
{
case LINE:
m_draw_line = &Draw::draw_line_line;
break;
case DOTS:
m_draw_line = &Draw::draw_line_dots;
break;
...
}
}
Now when you want to render the line, you do call this specialized function and you do not need to know whether it is a LINE or a DOTS...
void Graph::draw_line(line l)
{
this->*m_draw_line(l);
}
This way you create an indirection and make it a lot cleaner in the existing large functions that have large switch or many if() statements without breaking up the existing "powerful" class in many pieces that may become hard to use (because if it's that big it's probably already in use...)

C++: avoiding library-specific types in public interface

I'm currently working on a little game engine project in C++ using DirectX for rendering. The rendering part of the engine consists of classes such as Model and Texture. Because I would like to keep it (relatively) simple to switch to another rendering library (e.g. OpenGL) (and because I suppose it's just good encapsulation), I would like to keep the public interfaces of these classes completely devoid of any references to DirectX types, i.e. I would like to avoid providing public functions such as ID3D11ShaderResourceView* GetTextureHandle();.
This becomes a problem, however, when a class such as Model requires the internal texture handle used by Texture to carry out its tasks - for instance when actually rendering the model. For simplicity's sake, let's replace DirectX with an arbitrary 3D rendering library that we'll call Lib3D. Here is an example demonstrating the issue I'm facing:
class Texture {
private:
Lib3DTexture mTexture;
public:
Texture(std::string pFileName)
: mTexture(pFileName)
{
}
};
class Model {
private:
Texture* mTexture;
Lib3DModel mModel;
public:
Model(std::string pFileName, Texture* pTexture)
: mTexture(pTexture), mModel(pFileName)
{
}
void Render()
{
mModel.RenderWithTexture( /* how do I get the Lib3DTexture member from Texture? */ );
}
};
Of course, I could provide a public GetTextureHandle function in Texture that simply returns a pointer to mTexture, but this would mean that if I change the underlying rendering library, I would also have to change the type returned by that function, thus changing the public interface of Texture. Worse yet, maybe the new library isn't even structured the same way, meaning I'd have to provide entirely new functions!
The best solution I can think of is making Model a friend of Texture so that it can access Texture's members directly. This seems slightly unwieldy, however, as I add more classes that make use of Texture. I have never used friendship much at all, so I'm not sure if this is even an acceptable usage case.
So, my questions are:
Is declaring Model a friend of Texture an acceptable use of
friendship? Would it be a good solution?
If no, what would you
recommend? Do I need to redesign my class structure
completely? In that case, any tips?
PS: I realize that the title is not very descriptive and I apologize for that, but I didn't really know how to put it.
Whether it is an acceptable use of friendship is debatable. With every feature, even good ones, that you use, you risk that anti-patterns form in your code. So just use it with moderation and be cautious for anti-patterns.
While you can use friendships you can also simply use inheritance i.e. IGLTexture : ITexture and cast to the appropriate interface wherever implementation detail needs to be accessed. For instance IGLTexture could expose everything opengl related.
And there is even another paradigm that could be used. pimpl which stands for
private implementation. In short rather than exposing implementation detail
within the class, you just supply all implementation detail in a class whose implementation is unspecified publicly. I've been using this approach myself with little second regrets.
//header
class Texture
{
int width, height, depth;
struct Impl;
char reserved[32];
*Impl impl;
Texture();
...
};
//cpp
struct Texture::Impl
{
union
{
int myopenglhandle;
void* mydirectxpointer;
};
};
Texture::Texture()
{
impl = new (reserved) Impl();
}
You need to abstract this mo-fo.
class TextureBase{
public:
virtual Pixels* getTexture() = 0;
virtual ~TextureBase(){}
};
class Lib3DTexture: public TextureBase {
private:
Lib3DTexture mTexture;
public:
Texture(std::string pFileName)
: mTexture(pFileName)
{
}
Pixels* getTexture(){ return mTexture.pixels(); }
};
class Renderable{
public:
virtual void render()const = 0;
virtual ~Renderable(){}
};
class ModelBase: public Renderable{
public:
virtual ModelData* getModelData() = 0;
virtual ~ModelBase(){}
};
class Lib3DModel : ModelBase{
private:
TextureBase* texture;
ModelBase* model;
public:
Lib3DModel(std::string pFileName, Texture* pTexture): mTexture(pTexture), mModel(pFileName){}
void render()const{
model.renderWithTexture( texture.getPixels() );
}
};
class World: public Renderable{
private:
std::vector< std::shared_ptr<Renderable> > visibleData;
public:
void render()const{
for_each(visiableData.begin(),visiableData.end(),std::mem_fun(Renderable::render));
}
};
you get the idea, not guaranteeing it compiles but just to give you an idea.Also check out user2384250 comment, good idea as well.
Make Texture a template with a default template parameter using DirectX.
So you can do this:
template<typename UnderlyingType = Lib3DTexture> class Texture {
private:
UnderlyingType mTexture;
public:
Texture(std::string pFileName)
: mTexture(pFileName)
{
}
UnderlyingType UnderlyingTexture(); //returns UnderlyingType, no matter which library you use
};
I think this could be a clean way of solving that problem, and easily allowing the switching out of underlying libraries.
Since the 2 APIs are mutually exclusive and since you probably don't need to switch between the 2 at runtime, I think you should aim at building 2 different executables, one for each of the underlying API.
By that I mean use:
#if OpenGL_implementation
...
#else // DirectX
...
#if
This may or may not be the sexy solution you were looking for. But I believe this is the cleaner and simpler solution. Going with heavy template use (resp. heavy polymorphic behaviour) will probably cause even more code bloat than an #if solution and it will also compile (resp. run) slower as well. :)
In other words, if you can afford to have the 2 behaviours you want in 2 different executables, you should not allow this to have an impact on your software architecture. Just build 2 sexy, twin software solutions instead of 1 fat one. :)
From my experience, using C++ inheritance for those sort of problems often ends a quite complex and unmaintainable project.
There are basically two solutions:
Abstract all data types, making them not depend on the rendering layer at all. You will have to copy some data structures from rendering layer, but you only need to replace rendering code.
Choose a portable render layer (OpenGL) and stick to it.