Basic Component Based Entity

Started by
67 comments, last by crancran 12 years, 5 months ago
[color=#1C2837][size=2]Communication for me has probably been one of the hardest aspects of using this pattern. I am still by no means comfortable with my current approach but its a crude, elementary, but working solution that I look at being something I can tune and refine at a later point. [/quote]

This tends to be my problem too. I'm not yet comfortable with my own design skills which is why I created this topic in the first place. I am feeling more comfortable with my current system now than I was before with the help of the people here. Now if my design is actually practical is totally another story. I'll find out soon after I get my entityFactory finished and parsing the levels I've already made.
Advertisement

[color="#1C2837"]Communication for me has probably been one of the hardest aspects of using this pattern. I am still by no means comfortable with my current approach but its a crude, elementary, but working solution that I look at being something I can tune and refine at a later point.


This tends to be my problem too. I'm not yet comfortable with my own design skills which is why I created this topic in the first place. I am feeling more comfortable with my current system now than I was before with the help of the people here. Now if my design is actually practical is totally another story. I'll find out soon after I get my entityFactory finished and parsing the levels I've already made.
[/quote]

My first pass at my CBES project was using singletons. I knew that wasn't the route I wanted to go long-term, but it made coding much easier and I didn't have to worry about dealing with inter-communication as much. Basically the update() loops on my subsystems would use the singletons to get the components for my entity if they existed, worked a certain way if those components existed, and other ways if they didn't. Was that practical; nope :).

Several iterations ago I decided to rewrite my code and I decided to take a radically different approach to communication. Instead of using singletons and exposing portions of each system to another, I introduced an event mediator class. This class handles all inter-communication between subsystems in the entire framework. Any subsystem can register callback handlers based on specific events they are interested in. Events that are dispatched to the mediator can either be:

1. Queued for delayed delivery either at the next frame or some future time
2. Immediately

The first scenario is more aligned with a typical message loop described in windows or any double dispatch type event handler. I use this mechanic when a situation is reached in code during the current frame where I should impact another subsystem on the next frame. This is for non-critical events along with where I am not interested in getting any form of a response. It's your send it and forget type of trigger.

The second scenario is more like your typical boost signals or libsig++ mechanic where an event/signal is raised and those interested are immediately notified. The benefit of this approach would be where a subsystem reaches a state where it needs to know something immediately. The nature of my event class allows me to dispatch the event and the callback(s) all can modify the event object. When the callback finishes, the subsystem that made the call gets control again and can examine the event object and based on the data collected, proceed accordingly. This has been useful where say my physics engine needs a piece of data from my render engine and some information from my transform component. Rather than dispatching two events, I can create a single event, both subsystems are dispatched in sequence, they add their data to the event object and voila. :)

Again, is my approach ideal, probably not. But it's an interesting concept and likely not something used mainstream, unless someone here comments and tells me otherwise :P.

EDIT: I should also add that my mediator does not use an interface callback handler but instead allows the registering class to provide a class member function as the callback. The mediator essentially invokes those methods with the event object under both scenarios. This avoids the need for virtual methods and allows me to specify specific methods for specific conditions without needing to use switch statements or other conditionals.

Examples:

void OnEntityAddedToScene(CEvent* pEvent); // Render system dispatches this when node is added to scene
void OnMeshLoaded(CEvent* pEvent); // Dispatched by the mesh system when a mesh is loaded and added to a scene node
void OnTransformUpdate(CEvent* pEvent); // Dispatched by my transform system when an entity's position is changed
As I continue to add subsystems and components to my design, I feel there are problems with my approach that is leading to portions of code that should be simple and short appearing to be more bloated/boilerplate coding than I would have expected or even where I suspect separation of concerns is breached. I've decided to hold off on adding any more subsystems and components until I can address the design issues and I hope others can help.

Entities are first created by the entity manager being given a template definition. The template defines the necessary components to create that entity along with the properties to initialize each component of that entity. The entity system looks up the components from the definition in the component factory, gets the pointer to the create method that the component subsystem registered with the factory and invokes that method. The entity id along with the XML definition for that specific component are passed to the create method function pointer so that the subsystem can instantiate the component, initialize it, and add that component to its internal entity<->component map. Once an entity has been created, none of the components know anything about one another. The only thing that is known are the dependencies that a specific component type has for another component and the functionality/attributes that component provides for that entity's instance. For example, our render and physics components wants to know initial position/orientation along with the physics having interest in the rendered mesh's bounding box size and any scale modifiers while my animation system is interested in mesh information so that animation states can be extracted and used.

Each of my subsystems manage two or more lists of components which are based upon the component's state. When components are created by a subsystem, they are added to the active and update lists. My thought was that rather than having the update() method loop over all components in a particular subsystem, I could reduce that cost by only iterating over components which were modified. First, is this good or bad? Secondly, about the initial "wiring up" among components, I don't like the idea of having checks in my update() method to handle lazy-initialization, but maybe this is the norm ??

My current scenario is:
  • Iterate over the updated transforms and create a transform update event. This event when dispatched invokes methods on the render/physics systems to update their components.
  • Iterate over the updated meshes and create a mesh update event. This event when dispatched invokes methods on the physics/animation systems to update their components.
  • Iterate over the updated physics and create the physics component's rigid bodies and add them to the simulation. Then step the simulation.
  • If a collision was detected, a physics update event is fired and the transform system updates components accordingly, marking components as 'updated'
  • Iterate ALL animations and transition states and/or step animation phases.
  • Iterate over the updated renders and create the scene nodes if one does not exist else update scene node's position.

The very first thing that bothers me is how I handle this transform component. I opted to have the transform do a broadcast to the entity with the position/orientation to aid in the setup of any component that may require that information. This allowed for when the position/orientation changed from another component, every component of that entity gets updated on the next game loop. When the player has force applied and physics changes the position, the physics subsystem sends an event that the transform subsystem intercepts, modifies the position and then re-broadcasts the updates to everyone. But this seems a bit redundant on the event system to a degree, but it does allow updates to the position to happen in 1 place and then replicated by the component subsystem to those interested in the changes. Is this the typical approach?

Do others have any suggestions of variant ways to approach this? If code snippets would help, I can certainly provide.
Is it ok not to have my components inheriting from a component base class? All of my systems deal with their own component type so the never use the base class and it's causing me issues like overloading the init function. Not all of the components need a CSpatial but it seems I have to overload it in the base class first then give each component derived off of it the function just to please my compiler.

Is it ok not to have my components inheriting from a component base class? All of my systems deal with their own component type so the never use the base class and it's causing me issues like overloading the init function. Not all of the components need a CSpatial but it seems I have to overload it in the base class first then give each component derived off of it the function just to please my compiler.


I would suggest they all derive from some base class yes. There are a number of approaches you can take to solve this problem. My suggestion would be to consider having two derived classes from your base component class where one takes the spatial and the other does not. This will give you two types of classes to then base all your components from or you could always base some from the original parent base class if you saw the need. Remember, inheritance isn't bad if used properly :P.

But my approach to initialization was slightly different. My approach is to keep all my behavioral logic in my subsystems and treat my components mainly as data handlers. In my approach, I don't create the components directly but my subsystem does by being provided an entity reference and a list of initialization parameters. The subsystem in turn pulls creates a new component, passing the entity id and component id into the constructor. This will probably turn into a common "init" method soon when I add object pooling to my subsystems. Then the subsystem inspects the initialization parameters and calls the appropriate set methods accordingly. If parameters aren't provided and set during this call, they accept the default values dictated by the subsystem or the component's constructor.

All components typically hold a reference to their entity (whether it be a pointer or the id) and some form of a type identifier (in my case a component id). Rather than duplicate this functionality in all components, place it in a super base class and then reuse it in your hierarchy :P.

EDIT: My rule of thumb is if I have to write something more than once, it gets factored out. If I have conflicts between two objects, common stuff factors out to a base class and I derived two children from that parent :).
I ended up having to cheat a little when it came to my animation. I ended up tucking my start and end frames into my spatial object and having the render object read it. That way the AI/Behavior components can change them when needed. I'll keep this way until I get my message system capable of sending the data itself. Or is it ok to keep it like it is?
I would definitely remove it because a lot of things have a position/orientation/scale in 3D space but have nothing to do with animation (based on separation of concerns).

Additionally, I do more than just set an animation into motion based on game actions. For example, when my avatar strafes left or right, I actually work with the mesh's bone structure to rotate the head of the character in the direction i am strafing. If the character is strafing while moving forward, I rotate the bottom of the body to face the angled direction while keeping the head facing forward. When the avatar is idle, it periodically switches between 3 variants of idle animation to give the illusion that the character is "real". Also, the "jump" animation is split out into various animations depending upon whether the character jumps from the ground up and back down or jumps off a ledge and free falls to the ground a far distance. So as you see, animation for me is complex and that doesn't even scratch the surface of animations when it comes to in-combat actions, various other game actions like working with trade skills, etc. I simply have the animation system tied into listening for "movement" events and other game action "events" and it fires the appropriate animations based on those. Once you have your event framework up and running, you'll see how easy it is to move that out into it's own little world and that it just sits there and compliments the other systems without them even knowing what it is doing :P.
Right now I think I have insufficient communication abilities between my components/systems. I need to rethink my messaging system. Especially when it comes to data sending in events. Void pointers to specific data objects does not cut it. Do you do your animation in an animation component or the render component? Also since as you said animations are more complex for you especially your player entity do you have multiple rendering/animation component types?

Right now I think I have insufficient communication abilities between my components/systems. I need to rethink my messaging system. Especially when it comes to data sending in events. Void pointers to specific data objects does not cut it. Do you do your animation in an animation component or the render component? Also since as you said animations are more complex for you especially your player entity do you have multiple rendering/animation component types?


I chose to use a very crude approach in the beginning for messaging because I wanted to not worry too much about how they would communicate but be able to bring together a number of core components and work on the inner workings of their component functionality without being bothered. Void pointers to a defined structure would be fine assuming that you are using some form of a callback functor so that when the function call is invoked by the event framework, you know exactly what to recast that void pointer to with a static cast.


When it comes to the animation system, it exposes a great deal of features via events. So when writing the logic for moving forward in the movement component, it applies a force based on the game's movement speed and time and signals physics. Additionally, the component notifies the animation state to begin playing the walk forward animation. In the case of strafing, I have a special event that allows me to rotate the skeletal structures so I can keep my head forward but adjust the body on direction of movement. What I aim for is that the core component/systems such as animation should not be tied at all to my game but provide functionality that I can leverage while making a game. That allows it to be highly reused.

Another way to handle it would be to create a game specific animation system that listens for game-specific events and then internally works with the core engine's animation system. This way the game itself mirrors that of your engine and allows your engine to be reused in multiple games but allowing you to model your game code similarly and abstract the entire engine's systems into your own :). I have found this helpful in a few places where the engine was so modular that rather than remembering when case A needs to trigger 3 events in the engine, I simply send 1 event in my game code and a game code system receives that and dispatches those 3 events. This probably isn't the "fastest" way but keeps me from duplicating lots of code in various places :).
So you seem to have kind of a game view system going on then don't you?

So if I'm understanding right your animation system isn't in a component then? For my purposes I'm thinking of making it a component that just listens to events from it's ID.

I'm thinking of changing my event system to use more type specific events inheriting from a base event.
Currently my events look like this:
struct Event
{
EventType type;
EventCategory category;
void* data;
};



type and category are large enum lists. When an event is called the dispatcher sends it to the handlers registered to receive specific categories. I'm thinking of changing it so I can get rid of *data and just make more detailed events. Since the handler will know what it is based on the category and type it'll know what to cast it as to get the data from it.

Also I'm thinking I'm not using it as much as I should. Right now it's just used to give the stateManager feedback on the states it controls like if in the menu a button that should make it switch states is pressed. Or in my CGame class (the engine class that controls if the game is running, sets up application stuff, ect) it uses Irrlicht's eventReciever to get keyboard inputs and broadcasts that. I hadn't thought about have entities use it to send that it moved or not.

Also what is a good way to manage the event objects produced? They aren't pointers I make them like this:

Event event;
event.type=E_CREDITSSTATE;
event.category=E_GAME;
CEventDispatcher::inst()->sendEvent(event);



That sends to the stateManager (who is registered to listen to game events) an event from the menu state to switch to the credit state. Do I need to delete the event after it gets used or will it go out of scope and disappear itself?

The CEventDispatcher calls all of the IEventHandlers->handleEvent(e) functions in the registration list for that particular category. It's up to the handlers to decide if they ignore the event or not.

This topic is closed to new replies.

Advertisement