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.
Related
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.
I am designing an application, where multiple geometric primitive types (all inheriting the base Primitive class) are stored in an object of class Scene.
Instead of having a function in my main() that programmatically creates a scene by constructing the primitives and then calling Scene::add(...), I'd like to have some sort of configuration file that is read at runtime.
This would save me from having to recompile every time I change something about the scene, and seems like a general good idea (in case someone else that can't program might need to use my program sometime)
I've devised a little scheme that defines the scene through a .ini file like so:
[primitivefoo]
type = sphere
pos = 10 20 30
radius = 5.5
[primitivebar]
type = triangle
vertexA = 10 10 -10
vertexB = ...
...
You get the idea.
My plan is to have each subclass of Primitive register their own method interpretINI(...) in the class Scene. Scene would need some sort of map that maps string->void* (...), so that I know which type-string from the .ini file corresponds to which subclass of Primitive.
If this entire approach is bad design, and there is already a much more elegant way to achieve what I want to achieve, I would love to hear it. If not, I would be very grateful if someone could help me realize my design. I'm stuck on how to iterate over all Primitive subclasses to have them register themselves in Scene...
Your approach sounds good to me, with the exception that the names should map to a function returning Primitive* (instead of void*). This is a factory pattern (on two levels)
One limitation of this approach is that the factory functions registered will have to accept the same number/type of parameters. [Update: upon reading your comment to your question, this should not be a problem in your case].
I do not know of any automatic way of enumerating subclasses of a particular class, you will need to manually register the known classes (in main, or a special register function)
Update: you could get around the subclass enumeration by using static variables (in-class or otherwise) that will run a "register" function specific to the class-in-question:
class MyShape : public Shape
{
static int reg;
// appropriate constructor
};
int registerMyShape();
int MyShape::reg = registerMyShape(); // this will be called at program startup
The only problem is, there is no guarantee about the static initialization order in separate compilation units. Maybe if you can make the shapes module-like and "load" them after the registry class is fully initialized?
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 ®ionStart,
const Dimension ®ionSize,
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.
Right now, the GUI API for games I''m developing has an abstract Image and Font class. Depending on whether they use a GL, SDL etc Font, they load fonts like this:
Font *segoe = Font::load("segoe.ttf");
There is also a corresponding destroy() static function as well.
I like this design, but I was wondering if it would be a good idea to wrap it so that no pointers needed. Something like this (with better naming conventions)
WrappedFont segoe = WrappedFont(Font::load("segoe.ttf"));
It would also have overloaded = and a copy ctor, and a destructor.
Is it generally more desired for a game gui for the user to manage their Images and Fonts, or is a wrapped pattern more desirable?
Thanks
Basically, that's a custom smart pointer type to handle the load/destroy logic. This is very idiomatic and the way to go in C++. Resource management should be automatic.
So your wrapper is fine, but perhaps you are reinventing the wheel here. You may consider rewriting the font system that the work done by destroy is moved to the Font destructor, in which case you could use a regular boost::shared_ptr (also available from std in C++0x respectively std::tr1 in older compilers with support for the Technical Report 1). With your current code you can use shared_ptr as well, but you need to supply a custom deleter, which I find a bit cumbersome.
Yes, that's the way to go. Minor point: why not just have
WrappedFont segoe = WrappedFont("segoe.ttf");
You don't need to expose every detail to the user. The simpler it is, the fewer errors. If they really need to know the font involved, add a Font getFont() method.
This is always a personal choice. If you decide to allocate in constructor/init methods and destroy in destructor then it's a good idea (for that you have shared_ptr<> also.
But be informed that, if it's polymorphic then the virtual calls outside the class scope will be something like,
WrappedFont segoe = WrappedFont(Font::load("segoe.ttf"));
seogoe.getFontPtr()->VirtualFunction(); // more text !
You could yes, but the idea is to simplify the user life.
I usually introduce 2 classes for this:
Font: a base non-virtual class, which acts as a wrapper and resource manager and delegate the calls to an implementation (internal)
FontInterface: a pure interface
Customization comes by deriving from FontInterface and then somehow hooking into Font. In the case where I have full control over the code, I usually ask that an enum member be added for each derived class, the constructor for Font switches on this enum to instantiate the right derived class.
This is, indeed, a mix of Strategy and Factory pattern:
class Font
{
public:
enum Type { Segoe };
explicit Font(Type type);
void call1() const { _impl->call1(); }
void call2() const { _impl->call2(); }
private:
std::unique_ptr<FontInterface> _impl;
};
What's really interesting here is that the interface is stable in the face of redesign (for the user). The fact that there is an internal implementation which depends from the font selected is completely hidden.
Indeed, it is easy enough to move toward a FlyWeight pattern, for in the case of fonts the Font itself is normally stateless, only specifying behavior. Just change the std::unique_ptr for a std::shared_ptr, and have a simple cache system to maintain in memory the currently loaded fonts (using weak_ptr) and hand them over as necessary.
I've been trying to read through different implementations of Scene Graphs for 3D engine development to learn design patterns used in this domain, but unfortunately the code bases are too big for me grasp (yet, hopefully).
So, let's say we have a class Model that stores pointers to geometry, shaders, textures etc.
and we want to allow animation of each of the members separately, say GeometryAnimator, TextureAnimator and so on, but a Model could also be static of course.
What I see is that both the strategy pattern (with no-op for static entities) and the decorator pattern could be used to achieve this. What are the benefits/drawbacks of each in this application? Or do I over complicate matters?
Thanks for your help!
A simple yet perfectly fine solution for this is to establish interfaces/abstact base classes for all the various things that a scene node can represent.
class Texture
{
...
};
class Geometry
{
...
};
// etc
class SceneNode
{
public:
// The following return null by default but
// can be overriden by SceneNode subclasses
// to return interface pointers.
virtual Geometry* geometry()
{
return 0;
}
virtual Texture* texture()
{
return 0;
}
};
class Model: public SceneNode, public Texture, public Geometry
{
public:
// Override the functions of inherited interfaces
virtual Geometry* geometry()
{
return this;
}
virtual Texture* texture()
{
return this;
}
};
This is actually the approach that high-end 3D packages take in some form or another. With it, given any scene node, you can query it if it supports a particular interface (ex: a texture one) and then do animation through that, e.g.
Maya and XSI do this but with an interface method capable of returning all interfaces that returns void* which the client has to cast accordingly. They then create reference types that hide the casting required.
You don't need to always resort to classic design patterns for all of your programming solutions. Consider them as tools and suggestions but always asking which design pattern would work for a given problem will not always lead to the most straightforward solution. You have to think for yourself but design patterns can help you.
The Decorator pattern is usually used for structures that can't be modified. The Strategy pattern can be used in structures that you control completely, but will also let you allow others to change the behavior without having to write "around" it, like a Decorator.
I think that you over complicate. Maybe one class (Model) is sufficient? Remember to encapsulate only things that vary.
If you think it is not sufficient then strategy is ok. For example if you want to use many different TextureAnimator classes and be able to switch them in runtime.
Decorator pattern is like subclassing but can be done in runtime (and supports multiple inheritance). It is also slow (I guess you are coding a game). IMO this is not a solution.
In this case I'd code one class. If I needed strategy in the future I'd refactor the code.