c++ particle system inheritance - c++

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.)

Related

Extending Class via Multiple Private Inheritance - Is this a thing?

I'm trying to encapsulate existing functionality in a wide swathe of classes so it can be uniformly modified (e.g. mutexed, optimized, logged, etc.) For some reason, I've gotten it into my head that (multiple) private inheritance is the way to go, but I can't find what led me to that conclusion.
The question is: what is the name for what I am trying to do, and where I can see it done right?
What I think this isn't:
Decorator: All the descriptions I see for this pattern wrap a class to provide extra methods as viewed from the outside. I want to provide functionality to the inside (extract existing as well as add additional.)
Interface: This is close, because the functionality has a well-defined interface (and one I would like to mock for testing.) But again this pattern deals with the view from the outside.
I'm also open to alternatives, but the jackpot here is finding an article on it written by someone much smarter than me (a la Alexandrescu, Meyers, Sutter, etc.)
Example code:
// Original code, this stuff is all over
class SprinkledFunctionality
{
void doSomething()
{
...
int id = 42;
Db* pDb = Db::getDbInstance(); // This should be a reference or have a ptr check IRL
Thing* pThing = pDb->getAThing(id);
...
}
}
// The desired functionality has been extracted into a method, so that's good
class ExtractedFunctionality
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
protected:
Thing* getAThing(int id)
{
Db* pDb = Db::getDbInstance();
return pDb->getAThing(id);
}
}
// What I'm trying to do, or want to emulate
class InheritedFunctionality : private DbAccessor
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
}
// Now modifying this affects everyone who accesses the DB, which is even better
class DbAccessor
{
public:
Thing* getAThing(int id)
{
// Mutexing the DB access here would save a lot of effort and can't be forgotten
std::cout << "Getting thing #" << id << std::endl; // Logging is easier
Db* pDb = Db::getDbInstance(); // This can now be a ptr check in one place instead of 100+
return = pDb->getAThing(id);
}
}
One useful technique you might be overlooking is the non-virtual interface (NVI) as coined by Sutter in his writings about virtuality. It requires a slight inversion of the way you're looking at it, but is intended to address those precise concerns. It also tackles those concerns from within as opposed, to say, decorator which is about extending functionality non-intrusively from the outside.
class Foo
{
public:
void something()
{
// can add all the central code you want here for logging,
// mutex locking/unlocking, instrumentation, etc.
...
impl_something();
...
}
private:
virtual void impl_something() = 0;
};
The idea is to favor non-virtual functions for your public interfaces, but make them call virtual functions (with private or protected access) which are overridden elsewhere. This gives you both the extensibility you typically get with inheritance while retaining central control (something otherwise often lost).
Now Bar can derive from Foo and override impl_something to provide specific behavior. Yet you retain the central control in Foo to add whatever you like and affect all subclasses in the Foo hierarchy.
Initially Foo::something might not even do anything more than call Foo::impl_something, but the value here is the breathing room that provides in the future to add any central code you want -- something which can otherwise be very awkward if you're looking down at a codebase which has a boatload of dependencies directly to virtual functions. By depending on a public non-virtual function which depends on an overridden, non-public virtual function, we gain an intermediary site to which we can add all the central code we like.
Note that this can be overkill too. Everything can be overkill in SE, as a simple enough program might actually be the easiest to maintain if it just used global variables and a big main function. All of these techniques have trade-offs, but the pros begin to outweigh the cons with sufficient scale, complexity, changing requirements*.
* I noticed in one of your other questions that you wrote that the right tool for the job should have zero drawbacks, but everything tends to have drawbacks, everything is a trade-off. It's whether the pros outweigh the cons that ultimately determines whether it was a good design decision, and it's far from easy to realize all of this in foresight instead of hindsight.
As for your example:
// What I'm trying to do, or want to emulate
class InheritedFunctionality : private DbAccessor
{
void doSomething()
{
...
int id = 42;
Thing* pThing = getAThing(id);
...
}
}
... there is a significantly tighter coupling here than is necessary for this example. There might be more to it than you've shown which makes private inheritance a necessity, but otherwise composition would generally loosen the coupling considerably without much extra effort, like so:
class ComposedFunctionality
{
...
void doSomething()
{
...
int id = 42;
Thing* pThing = dbAccessor.getAThing(id);
...
}
...
private:
DbAccessor dbAccessor;
};
Basically what you're doing is decoupling the way you getAThing from the way you doSomething. Looks a lot like the Factory Method object-oriented design pattern. Have a look here:
Factory Method Pattern

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.

C++ virtual method: best way to use base implementation with an addition

Say I have the following classes:
class Airplane
{
virtual bool Fly(uint64_t destinationID)
{
//Do what an airplane does to be flown.
}
/*
* More function and data members.
*/
}
class SomeModel: public Airplane
{
virtual bool Fly(uint64_t destinationID);
{
//Do something that SomeModel specifically should do before it gets flying.
//Do exactly what Airplane::Fly does.
}
}
My question is how to implement SomeModel::Fly. One simple way is as follows:
virtual bool SomeModel::Fly(uint64_t destinationID)
{
//Do something that SomeModel specifically should do before it gets flying.
Airplane::Fly(destinationID);
}
Is there a nicer way of doing it? Or is there another reason for choosing another way. I know this is a general question but it's the first time I have to implement such a method so I want to make sure I'm not missing anything.
EDIT
I find it worth to emphasize that Airplane is not a general or abstract class, many Airplane in the company are just airplanes and appear as such without any inhritance, there is one specific model though that has some specific behavior.
This really depends on what you are trying to achieve. Your example is certainly valid and one solution to one type of problem (where a some setup or other variations are required early on).
Another variant on this theme is to use a virtual setup, and then a common "fly" method.
So:
class Airplane
{
bool Fly(uint64_t destinationID)
{
SetupForFlight();
// do actual flying stuff
...
...
}
virtual void SetupForFlight() { // do nothing for standard airplane }
}
class Boeing747: public Airplane
{
...
void SetupForFLight()
{
... do stuff that needs to be set up here.
}
...
}
There are benefits with both of these methods, and it will probably depend on what you are modelling which is better.
Of course, you could have a AfterLanding type function at the end of Fly as well.
Just out of curiousity, are there so many destinations that you need a 64-bit value for them - I've never really considered it, just curious.
Edit: I think what I'm describing is a "Template method pattern". I'm not great with names for these things, I just know how it's working....

C++ Help on refactoring a monster class

I have a C background and am a newb on C++. I have a basic design question. I have a class (I'll call it "chef" b/c the problem I have seems very analogous to this, both in terms of complexity and issues) that basically works like this
class chef
{
public:
void prep();
void cook();
void plate();
private:
char name;
char dish_responsible_for;
int shift_working;
etc...
}
in pseudo code, this gets implemented along the lines of:
int main{
chef my_chef;
kitchen_class kitchen;
for (day=0; day < 365; day++)
{
kitchen.opens();
....
my_chef.prep();
my_chef.cook();
my_chef.plate();
....
kitchen.closes();
}
}
The chef class here seems to be a monster class, and has the potential of becoming one. chef also seems to violate the single responsibility principle, so instead we should have something like:
class employee
{
protected:
char name;
int shift_working;
}
class kitchen_worker : employee
{
protected:
dish_responsible_for;
}
class cook_food : kitchen_worker
{
public:
void cook();
etc...
}
class prep_food : kitchen_worker
{
public:
void prep();
etc...
}
and
class plater : kitchen_worker
{
public:
void plate();
}
etc...
I'm admittedly still struggling with how to implement it at run time so that, if for example plater (or "chef in his capacity as plater") decides to go home midway through dinner service, then the chef has to work a new shift.
This seems to be related to a broader question I have that if the same person invariably does the prepping, cooking and plating in this example, what is the real practical advantage of having this hierarchy of classes to model what a single chef does? I guess that runs into the "fear of adding classes" thing, but at the same time, right now or in the foreseeable future I don't think maintaining the chef class in its entirety is terribly cumbersome. I also think that it's in a very real sense easier for a naive reader of the code to see the three different methods in the chef object and move on.
I understand it might threaten to become unwieldy when/if we add methods like "cut_onions()", "cut_carrots()", etc..., perhaps each with their own data, but it seems those can be dealt with by having making the prep() function, say, more modular. Moreover, it seems that the SRP taken to its logical conclusion would create a class "onion_cutters" "carrot_cutters" etc... and I still have a hard time seeing the value of that, given that somehow the program has to make sure that the same employee cuts the onions and the carrots which helps with keeping the state variable the same across methods (e.g., if the employee cuts his finger cutting onions he is no longer eligible to cut carrots), whereas in the monster object chef class it seems that all that gets taken care of.
Of course, I understand that this then becomes less about having a meaningful "object oriented design", but it seems to me that if we have to have separate objects for each of the chef's tasks (which seems unnatural, given that the same person is doing all three function) then that seems to prioritize software design over the conceptual model. I feel an object oriented design is helpful here if we want to have, say, "meat_chef" "sous_chef" "three_star_chef" that are likely different people. Moreover, related to the runtime problem is that there is an overhead in complexity it seems, under the strict application of the single responsibility principle, that has to make sure the underlying data that make up the base class employee get changed and that this change is reflected in subsequent time steps.
I'm therefore rather tempted to leave it more or less as is. If somebody could clarify why this would be a bad idea (and if you have suggestions on how best to proceed) I'd be most obliged.
To avoid abusing class heirarchies now and in future, you should really only use it when an is relationship is present. As yourself, "is cook_food a kitchen_worker". It obviously doesn't make sense in real life, and doesn't in code either. "cook_food" is an action, so it might make sense to create an action class, and subclass that instead.
Having a new class just to add new methods like cook() and prep() isn't really an improvement on the original problem anyway - since all you've done is wrapped the method inside a class. What you really wanted was to make an abstraction to do any of these actions - so back to the action class.
class action {
public:
virtual void perform_action()=0;
}
class cook_food : public action {
public:
virtual void perform_action() {
//do cooking;
}
}
A chef can then be given a list of actions to perform in the order you specify. Say for example, a queue.
class chef {
...
perform_actions(queue<action>& actions) {
for (action &a : actions) {
a.perform_action();
}
}
...
}
This is more commonly known as the Strategy Pattern. It promotes the open/closed principle, by allowing you to add new actions without modifying your existing classes.
An alternative approach you could use is a Template Method, where you specify a sequence of abstract steps, and use subclasses to implement the specific behaviour for each one.
class dish_maker {
protected:
virtual void prep() = 0;
virtual void cook() = 0;
virtual void plate() = 0;
public:
void make_dish() {
prep();
cook();
plate();
}
}
class onion_soup_dish_maker : public dish_maker {
protected:
virtual void prep() { ... }
virtual void cook() { ... }
virtual void plate() { ... }
}
Another closely related pattern which might be suitable for this is the Builder Pattern
These patterns can also reduce of the Sequential Coupling anti-pattern, as it's all too easy to forget to call some methods, or call them in the right order, particularly if you're doing it multiple times. You could also consider putting your kitchen.opens() and closes() into a similar template method, than you don't need to worry about closes() being called.
On creating individual classes for onion_cutter and carrot_cutter, this isn't really the logical conclusion of the SRP, but in fact a violation of it - because you're making classes which are responsible for cutting, and holding some information about what they're cutting. Both cutting onions and carrots can be abstracted into a single cutting action - and you can specify which object to cut, and add a redirection to each individual class if you need specific code for each object.
One step would be to create an abstraction to say something is cuttable. The is relationship for subclassing is candidate, since a carrot is cuttable.
class cuttable {
public:
virtual void cut()=0;
}
class carrot : public cuttable {
public:
virtual void cut() {
//specific code for cutting a carrot;
}
}
The cutting action can take a cuttable object and perform any common cutting action that's applicable to all cuttables, and can also apply the specific cut behaviour of each object.
class cutting_action : public action {
private:
cuttable* object;
public:
cutting_action(cuttable* obj) : object(obj) { }
virtual void perform_action() {
//common cutting code
object->cut(); //specific cutting code
}
}

How to write an elegant collision handling mechanism?

I'm in a bit of a pickle: say I'm making a simple, 2D, Zelda-like game.
When two Objects collide, each should have a resulting action. However, when the main character collides with something, his reaction depends solely on the type of the object with which he collided. If it's a monster, he should bounce back, if it's a wall, nothing should happen, if it's a magical blue box with ribbons, he should heal, etc. (these are just examples).
I should also note that BOTH things are part of the collision, that is, collision events should happen for both the character AND the monster, not just one or the other.
How would you write code like this? I can think of a number of incredibly inelegant ways, for instance, having virtual functions in the global WorldObject class, to identify attributes - for instance, a GetObjectType() function (returns ints, char*s, anything that identifies the object as Monster, Box, or Wall), then in classes with more attributes, say Monster, there could be more virtual functions, say GetSpecies().
However, this becomes annoying to maintain, and leads to a large cascading switch (or If) statement in the collision handler
MainCharacter::Handler(Object& obj)
{
switch(obj.GetType())
{
case MONSTER:
switch((*(Monster*)&obj)->GetSpecies())
{
case EVILSCARYDOG:
...
...
}
...
}
}
There's also the option of using files, and the files would have things like:
Object=Monster
Species=EvilScaryDog
Subspecies=Boss
And then the code can retrieve the attributes without the need for virtual functions cluttering everything up. This doesn't solve the cascading If problem, however.
And THEN there's the option of having a function for each case, say CollideWall(), CollideMonster(), CollideHealingThingy(). This is personally my least favourite (although they're all far from likeable), because it seems the most cumbersome to maintain.
Could somebody please give some insight into more elegant solutions to this problem?
Thanks for any and all help!
I would do it vice versa - because if the character collides with an object, an object collides with the character as well. Thus you can have a base class Object, like this:
class Object {
virtual void collideWithCharacter(MainCharacter&) = 0;
};
class Monster : public Object {
virtual void collideWithCharacter(MainCharacter&) { /* Monster collision handler */ }
};
// etc. for each object
Generally in OOP design virtual functions are the only "correct" solution for cases like this:
switch (obj.getType()) {
case A: /* ... */ break;
case B: /* ... */ break;
}
EDIT:
After your clarification, you will need to adjust the above a bit. The MainCharacter should have overloaded methods for each of the objects it can collide with:
class MainCharacter {
void collideWith(Monster&) { /* ... */ }
void collideWith(EvilScaryDog&) { /* ... */ }
void collideWith(Boss&) { /* ... */ }
/* etc. for each object */
};
class Object {
virtual void collideWithCharacter(MainCharacter&) = 0;
};
class Monster : public Object {
virtual void collideWithCharacter(MainCharacter& c)
{
c.collideWith(*this); // Tell the main character it collided with us
/* ... */
}
};
/* So on for each object */
This way you notify the main character about the collision and it can take appropriate actions. Also if you need an object that should not notify the main character about the collision, you can just remove the notification call in that particular class.
This approach is called a double dispatch.
I would also consider making the MainCharacter itself an Object, move the overloads to Object and use collideWith instead of collideWithCharacter.
How about deriving all collidable objects from one common abstract class (let's call it Collidable). That class could contain all properties that can be changed by a collission and one HandleCollision function. When two objects collide, you just call HandleCollision on each object with the other object as the argument. Each object manipulates the other to handle the collision. Neither object needs to know what other object type it just bounced into and you have no big switch statements.
Make all colidable entities implement an interface (lets say "Collidable") with a collideWith(Collidable) method.
Then, on you collision detection algorithm, if you detect that A collides with B, you would call:
A->collideWith((Collidable)B);
B->collideWith((Collidable)A);
Assume that A is the MainCharacter and B a monster and both implement the Collidable interface.
A->collideWith(B);
Would call the following:
MainCharacter::collideWith(Collidable& obj)
{
//switch(obj.GetType()){
// case MONSTER:
// ...
//instead of this switch you were doing, dispatch it to another function
obj->collideWith(this); //Note that "this", in this context is evaluated to the
//something of type MainCharacter.
}
This would in turn call the Monster::collideWith(MainCharacter) method and you can implement all monster-character behaviour there:
Monster::CollideWith(MainCharacter mc){
//take the life of character and make it bounce back
mc->takeDamage(this.attackPower);
mc->bounceBack(20/*e.g.*/);
}
More info: Single Dispatch
Hope it helps.
What you call "an annoying switch statement" i would call "a great game" so you are on the right track.
Having a function for every interaction/game rule is exactly what I would suggest. It makes it easy to find, debug, change and add new functionality:
void PlayerCollidesWithWall(player, wall) {
player.velocity = 0;
}
void PlayerCollidesWithHPPotion(player, hpPoition) {
player.hp = player.maxHp;
Destroy(hpPoition);
}
...
So the question is really how to detect each of these cases. Assuming you have some sort of collision detection that results in X and Y collide (as simple as N^2 overlap tests (hey, it works for plants vs zombies, and that's got a lot going on!) or as complicated as sweep and prune + gjk)
void DoCollision(x, y) {
if (x.IsPlayer() && y.IsWall()) { // need reverse too, y.IsPlayer, x.IsWall
PlayerCollidesWithWall(x, y); // unless you have somehow sorted them...
return;
}
if (x.IsPlayer() && y.IsPotion() { ... }
...
This style, while verbose is
easy to debug
easy to add cases
shows you when you have
logical/design inconsistencies or
omissions "oh what if a X is both a
player and a wall due to the
"PosessWall" ability, what then!?!"
(and then lets you simply add cases
to handle those)
Spore's cell stage uses exactly this style and has approximately 100 checks resulting in about 70 different outcomes (not counting the param reversals). It's only a ten minute game, that's 1 new interaction every 6 seconds for the whole stage - now that's gameplay value!
If I am getting your problem correctly, I would sth like
Class EventManager {
// some members/methods
handleCollisionEvent(ObjectType1 o1, ObjectType2 o2);
// and do overloading for every type of unique behavior with different type of objects.
// can have default behavior as well for unhandled object types
}