C++ / OOP: Class with implicit dependency on other class - c++

I'm writing a program in OpenGL. There is a Gfx class which holds an OpenGL context and wraps the OpenGL library.
There is also a Texture class which wraps OpenGL texture names (including generation and deletion). The Texture class naturally has an implicit dependency on the Gfx class. But I want RAII, no pointers, and therefore think that the Texture class must be publicly accessible.
What is the cleanest way to express the dependency on a constructed Gfx instance?

Assuming the texture cannot exist without the context, looks like the constructor argument is proper in this case, possibly a std::shared_ptr<Gfx> (hope this is excused from your no-pointer policy - I consider it a C++ construct). This way Gfx will linger as long as at least one Texture is not disposed.

Related

"Implementation" of the object hierarchy - "the easiest way" or how to avoiding virtual inheritance?

I have some quite complex, virtual objects hierarchy that represents all the elements in 3D Engine as abstract classes (interfaces).
For example, I have Renderable which parent is Sizeable (with getSize() method). Sizeable inherits from Positionable (with getPosition()) etc.
That structure is fine and logic (e.g. 3D Model is Renderable, bone of skeleton for skinning is Sizeable, and the Camera is only Positionable).
There is also one "uber-class", Engine3D.
My aim is:
I have to write the "implementation" for that "graphic things" (module). It will be DirectX "implementation". The aim: the programmer that uses my "implementation" can switch to other fast and simple (which implementation he uses is almost transparent to him).
I would like to keep it that way:
//choosing module "implementation" ("implementation" mentioned here only)
Engine3D * engine = new MyEngine3D();
Renderable * model = engine->createModel(...);
//line above will return MyRenderable class in fact,
//but user (programmer) will treat it as Renderable
Why I want to create "own" versions of Renderable and all others? Because they will share some "implementation"-specific data (pointers for DirectX structures etc.).
My problem is:
But that way, I would create a "mirror" - a copy of the original module's objects hierarchy with My in front of each class name. Moreover, MyRenderable would have to inherit both from Renderable (to overwide render()) and MySizeable (to get the DirectX matrices etc.).
And that involves the virtual inheritance and really complicates the structure.
Is there an easier way?
I'm speaking mainly about avoiding virtual multi-inheritance (just multi-inheritance is fine, I guess).
You should definitely avoid a strong coupling of object hierarchy and rendering implementation. My suggestion would be to move all the DirectX specific code to a class outside of your object hierarchy, for example an IRenderer interface together with a DirectXRenderer implementation. Add a reference or pointer to IRenderer to all the classes which have to draw something (Renderable, etc). All object classes must use your own implementations of matrices etc. to keep them independent from the data structures of the actual rendering backend.

Setting a function from one object to called by another object in arduino library

I'm a little new to writing in C so I hope I'm not to far off base here.
I'm working on a library to handle the control of multiple types of LED ICs. There are a ton of different types of RGB Pixel libraries each with their own unique naming, but all really perform the same basic actions. A "strip" or "strand" object is created, each pixel gets a color value set, and the strip then gets updated.
My library handles getting pixel color values from software in the back ground and providing the user with the most recent values from an array belonging to the object.
What I would like is to allow the user to initiate their LED strip object and pass a reference to that object to my library, and then allow them to pass their objects "setPixelColor()" function and "UpdateStrip()" function to the library as well. If this is achievable then I believe my library could then handle all of light control operations for any given PixelLibrary.
I believe what I'm looking for is the proper way to pass a functions pointer between objects? Not looking for someone to do this for me, but just looking for directed guidance. Been searching google for while this morning, but I don't know that I'm even using the proper terms. Any advice or guidance would be a big help. Thanks!
Sounds like what you need is a base class or virtual base/interface. You define a class with common data and methods which work across all your LEDs. This common or abstract class defines the common functions. Each of your LED strand types will then inherit the base class/interface and implement the specific functions to set an LED for example.
Using this approach the application code works using the Base class/interface methods treating all the strands the same way.
If you use this approach, I also recommend you create a static factory method which returns a base class/interface pointer after creating the specifically required object.
abstractController=CreateLEDStrandController("Strand Type");//Creates the right object, returns an abstracted base class pointer.
abstractController.SetLEDColor("RED"); //Actually calls the specific object SetLEDColor

Design: GraphicManager, TexturesPool, Texture

I have system in which present class sigleton GraphicManager, class TexturePool and class Texture.
Texture have some subtles in creation. Then it constructing itself they use DirectX stuff from GraphicManager and some d3d constants. Now i use CreateInstance method and private cons in Texture class, but as for me its not goot what Texture now so much about real engine, may be better to build it from GraphicManager? Do i need use for it friend function or may be else approach?
I really couldn't understand your question, but I'll try to give you some tips. It's ok if you use Singleton in GraphicManager or in TexturePool, but you have to be careful, because singleton allows you to use the unique instance even when you shouldn't. Singleton can make the code easier to type, but a quite dangerous too. As I could understand you are now using Singleton in Texture class, but I think that in your system you can have more than one Texture, so it doesn't make sense. However, you can create a method in your TexturePool class to load a texture from a image file. Something like:
Texture* TexturePool::loadTexture(std::string fileName);
Then, anything that you need to use to create a texture, you should get from GraphicsManager's unique instance. I hope this could be useful for you.

Is this a good design?

Right now my gui is abstract and basically has a Bitmap class which holds a void* to the native bitmap type. The way it works is I have an abstract bitmap loader which returns a void pointer to the image data given a path string. the loader is a static pointer in the Bitmap data type and is set by the user for whatever backend used. The Graphics class is abstract and a pointer to it is asked for by the Gui class. When the backend for the Graphics class draws an image it does something like this:
void Allegro5GraphicsManager::drawImage( const Bitmap &bmp,
const Point &position,
const Point &regionStart,
const Dimension &regionSize,
const float &opacity /*= 1.0f*/ )
{
al_draw_tinted_bitmap_region((ALLEGRO_BITMAP*)bmp.getBitmap(),
al_map_rgba_f(opacity,opacity,opacity,opacity),
regionStart.getX(),regionStart.getY(),
regionSize.getWidth(),regionSize.getHeight(),
position.getX() + getOffset().getX(),position.getY() + getOffset().getY(), 0);
}
So as you can see it mearly type casts the void* to what it needs.
The problem is I hear void*s are not a good idea in C++.
The other solution I thought of is for something like Allegro5Bitmap which would inherit from Bitmap.
The problem I had with this method was that the user would then have to plaster Allegro5Bitmap all over their code. And this defeats the concept of my API which is for all code written to be portable to other backends like sdl, etc, by simply initializing the Gui class with sdl manager pointers.
What could I do?
Thanks
No, this is bad design. void* is what you definitely want to get rid of in C++.
It is not fully clear to me what problem you are trying to solve. Is it only about abstracting I/O of images or also drawing of them?
the typical solution to the I/O problem is to have ImageReader/ImageWriter abstract classes. Then their implementations are based on image type or I/O backend. These classes are basically factories for Image objects.
What you are handling in your code afterwards is still a generic Image (btw. you know that a "bitmap" actually is a black+white image?).
Note: Even if you need to have different types of Image objects (derivations), the factory is the typical pattern to resolve your issue while staying generic in your other code. You obtain an Image object from the factory, that in fact is an AllegroImage or whatever other type. You only call the base class methods on the Image so you don't care.

Is creating a base class for all applications of a particular type good design?

I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.