Making a simple particle system - c++

I had a question regarding the way I am designing my particle system.
Right now I have a class P, which stores all the information about a particle such as speed, position, direction, type, etc. I also have a main file I will be drawing these particles, updating and instantiating them in. I want to create a list of these particles using the c++ std list library, so initially I did
std::list<P> listOfParticles;
in the main file. Here is the problem. By doing this I will essentially be forced to make my update and draw functions in the main file. I feel like this is bad practice, and that everything to do with the particle should be kept in one class, but I am unsure where to go from here in terms of best practice. Would it be a good idea to just create a list of particles in the class P where I am defining what a particle is? I feel like this isn't a smart idea though..
If anyone could guide me in the right direction I would really appreciate it.

"By doing this I will essentially be forced to make my update and draw functions in the main file"
No one is stopping you from putting declarations/definitions of class members in same/different .h/.cpp files.
EDIT:-
That's what I said, better it would be if you make this List a member of some other class where you would put all functions to manipulate this list.

Your list of particles most probably deserves its own class, let C, that will handle storage, initial spatial distribution, temporal updates... i.e. all global operations on the particle cloud. If you are sure that you will ever handle a single list, you can make it a static member.
The class that represents the individual particles (P) can be nested into (C) if there is no need to see it from outside. It will encapsulate particle data and possibly also model pairwise interaction with another particle and other single-particle operations.

Related

C++ Class Access Management

I'm developing a game using OpenGL. I have a Game class that contains all the environment variables (by environment, I mean things like gravity or tile sets). There's only one Game object. I also have another class called Entity, which contains properties to display objects on the screen.
I'm finding myself needing access to more and more Game variables in my Entity class. At the moment i'm just using parameters to pass data into each function, but I'm considering just passing a pointer to the Game class? Is there anything wrong with that? Is there a better way?
I think this is good practice. It is good idea to replace a group of parameters with a parameter object.
Just make sure that Game remains cohesive. The variables contained within Game should be related.
Make Entity a Friend of the Game class.
Please see
http://msdn.microsoft.com/en-us/library/465sdshe.aspx
Note: If this is ever done in C#, there isn't a friend keyword or exact equivalent.

Entity Systems in C++

In game development there is a notion of Entity System which is aiming to simplify the game loop by gaining a flexible architecture. For details see the links below:
http://www.richardlord.net/blog/what-is-an-entity-framework
http://shaun.boyblack.co.za/blog/2012/08/04/games-and-entity-systems/
Now I wonder how it is possible to realize automatic Node creation when a Component is added to an Entity in C++? Please tell me the principle of identifying what Nodes can be spawned from a specific Entity, i.e. you should have list of Component and classes that aggregate components. And you should understand what classes can be created with the list of data.
For example I have Components:
class PositionComponent
{
int m_x;
int m_y;
int m_rotation;
};
class VelocityComponent
{
int m_vX;
int m_vY;
int m_vAngular;
};
class RenderableComponent
{
Sprite m_view;
};
And nodes:
class MoveNode
{
PositionComponent m_position;
VelocityComponent m_velocity;
};
class RenderNode
{
RenderableComponent m_rend;
PositionComponent m_position;
};
Now if I create an Entity like this:
Entity * e = new Entity;
e.add(new PositionComponent);
e.add(new VelocityComponent);
Then I want to have a code that creates a MoveNode automatically, and if I add also this:
e.add(new RenderableComponent);
Then I want to know that also RenderNode is created. Consequently, when I delete it:
e.remove(new RenderableComponent);
the RenderNode should be deleted. And this process, of course, should not be bind to the specific Nodes and Components I have defined.
How is it possible to realize this in C++?
I am slightly confused, since it appears to mix concepts. I will try to shed some light on the two concepts.
Entity & Component
The entity component system is quite common in game engines, for example Unity implements it quite visibly. It tries to address the issue that simple inheritance does not work well in many cases, such as mixing rendering and collision information; is a Collidable also a Renderable? And since multiple inheritance is a scary thing for many and not supported in many languages, the only way out of this is the Entity/Component design. (Actually not the only solution, but that is a different issue.)
The design for entity component is quite simple, you have a class Entity that takes multiple objects of type Component. There will be multiple components that "do" something, like a MeshRenderer, TriMeshCollision or RigidBodyMotion. As stated in the articles, the actual logic does not need to be implemented in the components themselves. The component just "flags" the entity for specific logic. It makes sense to delegate the actual work to be done in a tight loop in a system, maybe even in a different thread, but more to that later.
Then the actual entity is composed. There are two basic ways to do this, in code or in data.
For example you compose objects in code that represent one "real world" object; the object of type Goblin exists and it is derived from the class Entity. The constructor from Goblin will then create all components and register them on itself. Inheritance is now only done for high level logic, for example the FastGoblin is derived from Goblin and only has a different material and speed setting.
The second way to create objects is through data, that is you have some form of object description language. (Take something in XML or JSON) This will then create in a factory method something based on a given template in that is defined in this object description language.
Node Based Work Scheduling
It may make sense to have objects that are fully defined, but the logic not being executed. Think about objects on the server or in the editor. On the server you do not want the rendering code to be in the way. So the basic approach is to create components that contain no data. The problem to solve is, how do you efficiently get things done without iterating through the entire scene each frame and typecasting the objects around?
What your second link describes is basically a botched version of Designing the Framework of a Parallel Game Engine
There needs to be a way to schedule the work in an efficient way. The proposed solution is to have "nodes" that each do a specific task. The nodes are then scheduled, by submitting them to either a work scheduler or a specific system.
Take for example rendering. You have an entity and it has a MeshRenderer component. This component will create a RenderNode and submit it to the RenderSystem. Then when it is time to render the frame the RenderSystem will simply iterate over each RenderNode and call its display method. In the display method the actual rendering is done.
Alternatively the system, engine or entity can create nodes based on specific component configurations. Take for example physics. The Entity has the TriMeshCollision and RigidBodyMovement components. The PhysicsSystem seeing this configuration creates a RigidBodyNode that takes the two components as inputs and thus implements rigid body motion. Should the entity only have a TriMeshCollision component the PhysicsSystem would then create a StaticColliderNode to implement the behavior.
But like the construction mechanic for components from data, the nodes can also be created and attached to the entity through a factory function. This can be part of either the object definition or a rule based system.
Mapping this design into C++ should be straight forward. The rather difficult bit is to figure out a way how the different bits get connected; for example, how the MeshRenderer gets access to the RenderSystem so it can submit its RenderNode. But this can be solved with a singleton (shudder) or by passing a Game/Engine object around at the construction of the Entity or Component.
Is this good design?
But the issue I want to address here is: Is this good design?
I have troubles with your second link (Games And Entity Systems), since I think the design will fall flat on its nose quite quickly. This is true for other aspects like physics, but this will become quite inefficient when considering modern 3D rendering.
When you need to organize the scene spatially to efficiently cull hidden objects, organize the objects into batches for lighting and reduce resource switching then the entire "list of nodes" concepts is moot since you need a separate organisational structure anyway.
At this point you can let the components "talk" directly to the systems and each system has its own unique specific API that is fit for its specific purpose. The requirements of rendering, sound and input are each significantly different and tying to cram them into on API is futile.
See Also
Entity/Component based engine rendering separation from logic

Let a Class store unknown Data

Issue about Storeing unknown Data in a Class
How can I provide a class in C++ which is able to store any number of variables each of any type? From inside and outside of the class I would like to read, add, modify and delete these data.
So what I am looking for is maybe a list where the datatypes can vary.
Example how the Usage could look like
Class Object();
Object->Storage->Create("position", "float"); // create
Object->Storage->Write("position", 42.0f); // write
int Result = Object->Storage->Read("position"); // read
Object->Storage->Delete("position"); // delete
How to do that or why to do it in another Way
My question is if there is a common approach for this problem and what a good solution is. If my thoughts were not correct and there is another technique or place to store data for my aim (next paragraph) please tell me.
Optional Background Information and Context
The reason behind this need is that I am writing a kind of component based game engine. There are Components and Systems. A System could be the title menu or a world level and I can add as many Components to it as I wish. Every game tick, the System calls a specified method over all of its Components. Components are e.g. Physics, Terrain, Draw, Characters, Sound, ... The mentioned unknown data structure is what a Component should be able to store in its System. The Component is nearly static and its state depends on the storage it uses. This Storage system is (together with the event manager) used to communicate between Components.
Edit:
By researches I figured out that what I want is called Data Centered or Data Oriented in software design. Now I have a starting point to do more research on this topic. Thank you Michael Anderson for your answer, probably I will use that.
You probably want to use boost::any for this kind of thing.
Your code will look like this:
std::map<std::string,boost::any> object;
object["position"] = 42.0f;
//This will throw if the type is wrong
int Result = boost::any_cast<float>(object["position"]);
object.erase("position");
Does the Standard Template Library (STL) - more specifically, the use of a map - not work for your needs?
http://en.cppreference.com/w/cpp/container/map
You can use the map to hold values which are either:
1) a "CustomObject", which is a union of all possible variable / object types.
2) a pointer to the actual objects / variables.

C++ Game - Signalling a parent class, circular dependency issue

I'm having a little circular-dependency problem. It works fine, but it makes for ugly-seeming code. It's in the context of a Snake game.
I have a class, Snake, which contains a vector of SnakeSegments, and manages their interaction (for instance moving and growing as a unit, rather than as separate entities).
When a SnakeSegment collides with a Food object, it flips its hasEaten member to true. The Snake routinely queries the SnakeSegments, essentially for this member. If any of the queries return positive (i.e. one has hit food), then the Snake will grow as a unit (i.e. expand the head and shrink the tail). This is all fine and good, but I'd much prefer a more signal-based approach, where, when a SnakeSegment hits food, it sends an alert (signal, interrupt, etc.) to the Snake class, which tells it to grow. This means I wouldn't have ugly code in my Snake's Update function, checking all the segments; and I would instead have an OnEat() function in my Snake class.
However, this leads to circular dependencies; the Snake contains a vector of SnakeSegments, and the SnakeSegments have a Snake& or Snake* member, which tells them whom to alert when they eat. In the code, I essentially just have to pre-declare the Snake class:
class Snake;
class SnakeSegment
{
...
Snake* alertOnEat;
...
};
and my Snake class just works normally
#include "SnakeSegment.hpp"
class Snake
{
...
std::vector segments;
...
void OnEat();
...
};
Are there any nicer designs to this? Note that it isn't just a problem occuring here; a similar problem occurs in a number of areas (e.g. the GameWorld contains a Snake member, and the Snake alerts the GameWorld when it dies), so a solution specific to Snake and SnakeSegment isn't what I'm looking for.
Your current design is perfectly fine in most situations. Yes, it creates a circular dependency, but it also is the simplest and the clearest way to do it.
However, you should limit those dependencies between interfaces or base classes rather than to the derived classes directly. The world-snake dependency is a good example. You probablly don't necessarily want the World class to know about all the possible game object types. However, what you can do is derive all your game objects from a common GameObject class and make World and GameObject interdependant.
There are also more complicated ways to avoid dependencies all with their pros and cons, they mostly differ on the level of separation and clarity. Among those, function pointers, delegates, observers, listerners, functors, etc.
In the end, it always come down to how much complexity you are ready to introduce to your architecture in exchange of flexibility and clear separation of concerns.
Never forget that design is compromise.
What you may want to look at for this problem is the Observer/Observable design pattern. It allows you to create objects that observe (Snake) observable objects (SnakeSegment) and get notified right away when their state has changed.
Wikipedia has a good example of it written in many languages including C++.
It's a common pattern used in a lot of GUI development so the View layer can change when any of the underlying Model data changes.

Structure for hierarchal Component storage

I've been batting this problem around in my head for a few days now and haven't come to any satisfactory conclusions so I figured I would ask the SO crew for their opinion. For a game that I'm working on I'm using a Component Object Model as described here and here. It's actually going fairly well but my current storage solution is turning out to be limiting (I can only request components by their class name or an arbitrary "family" name). What I would like is the ability to request a given type and iterate through all components of that type or any type derived from it.
In considering this I've first implemented a simple RTTI scheme that stores the base class type through the derived type in that order. This means that the RTTI for, say, a sprite would be: component::renderable::sprite. This allows me to compare types easily to see if type A is derived from type B simply by comparing the all elements of B: i.e. component::renderable::sprite is derived from component::renderable but not component::timer. Simple, effective, and already implemented.
What I want now is a way to store the components in a way that represents that hierarchy. The first thing that comes to mind is a tree using the types as nodes, like so:
component
/ \
timer renderable
/ / \
shotTimer sprite particle
At each node I would store a list of all components of that type. That way requesting the "component::renderable" node will give me access to all renderable components regardless of derived type. The rub is that I want to be able to access those components with an iterator, so that I could do something like this:
for_each(renderable.begin(), renderable.end(), renderFunc);
and have that iterate over the entire tree from renderable down. I have this pretty much working using a really ugly map/vector/tree node structure and an custom forward iterator that tracks a node stack of where I've been. All the while implementing, though, I felt that there must be a better, clearer way... I just can't think of one :(
So the question is: Am I over-complicating this needlessly? Is there some obvious simplification I'm missing, or pre-existing structure I should be using? Or is this just inheritly a complex problem and I'm probably doing just fine already?
Thanks for any input you have!
You should think about how often you need to do the following:
traverse the tree
add/remove elements from the tree
how many objects do you need to keep track of
Which is more frequent will help determine the optimum solution
Perhaps instead of make a complex tree, just have a list of all types and add a pointer to the object for each type it is derived from. Something like this:
map<string,set<componenet *>> myTypeList
Then for an object that is of type component::renderable::sprite
myTypeList["component"].insert(&object);
myTypeList["renderable"].insert(&object);
myTypeList["sprite"].insert(&object);
By registering each obejct in multiple lists, it then becomes easy to do something to all object of a given type and subtypes
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(),renderFunc);
Note that std::set and my std::map construct may not be the optimum choice, depending on how you will use it.
Or perhaps a hybrid approach storing only the class heirarchy in the tree
map<string, set<string> > myTypeList;
map<string, set<component *> myObjectList;
myTypeList["component"].insert("component");
myTypeList["component"].insert("renderable");
myTypeList["component"].insert("sprite");
myTypeList["renderable"].insert("renderable");
myTypeList["renderable"].insert("sprite");
myTypeList["sprite"].insert("sprite");
// this isn't quite right, but you get the idea
struct doForList {
UnaryFunction f;
doForList(UnaryFunction f): func(f) {};
operator ()(string typename) {
for_each(myTypeList[typename].begin();myTypeList[typename].end(), func);
}
}
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(), doForList(myFunc))
The answer depends on the order you need them in. You pretty much have a choice of preorder, postorder, and inorder. Thus have obvious analogues in breadth first and depth first search, and in general you'll have trouble beating them.
Now, if you constraint the problem a litle, there are a number of old fashioned algorithms for storing trees of arbitrary data as arrays. We used them a lot in the FORTRAN days. One of them had the key trick being to store the children of A, say A2 and A3, at index(A)*2,index(A)*2+1. The problem is that if your tree is sparse you waste space, and the size of your tree is limited by the array size. But, if I remember this right, you get the elements in breadth-first order by simple DO loop.
Have a look at Knuth Volume 3, there is a TON of that stuff in there.
If you want to see code for an existing implementation, the Game Programming Gems 5 article referenced in the Cowboy Programming page comes with a somewhat stripped down version of the code we used for our component system (I did a fair chunk of the design and implementation of the system described in that article).
I'd need to go back and recheck the code, which I can't do right now, we didn't represent things in a hierarchy in the way you show. Although components lived in a class hierarchy in code, the runtime representation was a flat list. Components just declared a list of interfaces that they implemented. The user could query for interfaces or concrete types.
So, in your example, Sprite and Particle would declare that they implemented the RENDERABLE interface, and if we wanted to do something to all renderables, we'd just loop through the list of active components and check each one. Not terribly efficient on the face of it, but it was fine in practice. The main reason it wasn't an issue was that it actually turns out to not be a very common operation. Things like renderables, for example, added themselves to the render scene at creation, so the global scene manager maintained its own list of renderable objects and never needed to query the component system for them. Similarly with phyics and collision components and that sort of thing.