Note:I have stopped development on Ember. While it works fine the ideas have been refined in Richards Lords Ash I recommend you check that out.

the Game

If your new to entity systems then you may want to read my posts on Game Architecture and Entity Systems first to get an over view. You can download the code for this example GettingStarted

Ok so first step to making games on the Ember frame work is to create you games main class. This has the same role as an applications context in robotlegs.  Its main role is the initialization and tearing-down of you game.

package{
    import com.tomseysdavies.ember.base.Game;

    public class MyGame extends Game{
        override protected function startUp():void{

        }
    }
}

we can now launch the game from felx like so and pass it a reference to the display object that we want to become the games view.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:local="*">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <local:MyGame contextView="{gameView}" />
    </fx:Declarations>
    <mx:UIComponent id="gameView" />
</s:Application>

Components

So our game is now launching and has a reference to its view so we can now look at creating our first component. A component is a value object its highly portable and normal has no methods only data. For this tutorial we will need two.

package components
{
    public class PositionComponent
    {
        public var x:Number = 0;
        public var y:Number = 0;
    }
}
package components
{
    import flash.display.Bitmap;

    public class GraphicsComponent
    {
        public var asset:Bitmap;
    }
}

Entities

Now lets go back to our start up function. So here we first create that our components then next we create an entity and add our components to it. Think of an entity as an empty container to which we can add components. We create entities with the entityManager.

override protected function startUp():void{
    var positionComponent:PositionComponent = new PositionComponent();
    positionComponent.x = 100;
    positionComponent.y = 100; 
           
    var graphicsComponent:GraphicsComponent = new GraphicsComponent();
    graphicsComponent.asset = new Tree();
           
    var entity:IEntity = entityManager.createEntity();
    entity.addComponent(positionComponent);
    entity.addComponent(graphicsComponent);

}

Systems

The final building block in Ember is the systems these have all the logic for the game that acts on the entities data. Ember uses SwiftSuspenders for its dependency injection if you have used robotlegs then hopefully this should be familiar and its well documented there so I wont cover it into much detail. All systems must implement ISystem and the onRegister and destroy functions that come with that. Any initiation code needs to go in to onRegister which is automatically called after the injection has occurred. The destroy() function is used to clean up any event listeners etc. Have a quick look at the code bellow then I will explain it.

package systems
{
    import com.tomseysdavies.ember.base.EntityManager;
    import com.tomseysdavies.ember.core.IEntity;
    import com.tomseysdavies.ember.core.ISystem;
   
    import components.GraphicsComponent;
    import components.PositionComponent;
   
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.DisplayObjectContainer;
    import flash.geom.Point;
    import flash.geom.Rectangle;
   
    public class RenderingSystem implements ISystem
    {
        [Inject] public var contextView:DisplayObjectContainer;
        [Inject] public var entityManager:EntityManager;       
        private var _family:IFamily;
        private var _viewPort:Bitmap;
       
        public function onRegister():void{
            _family = entityManager.getEntityFamily(PositionComponent,GraphicsComponent);
            _family.iterator.add(renderEntity);
           
            _viewPort = new Bitmap()
            _viewPort.bitmapData = new BitmapData(400,400);
            contextView.addChild(_viewPort);
           
            render()
        }
       
        private function render():void{
            _viewPort.bitmapData.fillRect(new Rectangle(0,0,400,400),0xFFFFCC);
            _family.startIterator();
        }

        private function renderEntity(position:PositionComponent,graphics:GraphicsComponent):void{
            _viewPort.bitmapData.copyPixels(graphics.asset.bitmapData,graphics.asset.bitmapData.rect,new Point(position.x,position.y),null,null,true);
        }
       
        public function destroy():void  {
             _family.iterator.remove(renderEntity);
            _viewPort.bitmapData.dispose();
        }
    }
}

This system as it name suggests renders our entity to the screen. First we we set up a viewport where we will render our graphics (note contextview is again injected). Next the most important line in onRegister is this(note that the reference to the entityManager is injected above).

_family = entityManager.getEntityFamily(PositionComponent,GraphicsComponent);

This allows us to “look up” all entities from the entityManager that have all the specified components. Here we are asking for all entities that have both the PositionComponent and the GraphicsComponent. The entityManager returns a pointer to a family instance. We store a reference to this so we don’t have to request it every time we render the game. We can listen to signals dispatched by the family to see if entities have been added or removed or iterate over all entities in the family. We are going to add a handler to the iterator signal. we do that like this

_family.iterator.add(renderEntity);

Bellow is what that handler function looks like. Notice it accepts components as arguments in the same order as those that we asked for when we called getEntityFamily. If these don’t match you will get a runtime error.

private function renderEntity(position:PositionComponent,graphics:GraphicsComponent):void{
      _viewPort.bitmapData.copyPixels(graphics.asset.bitmapData,graphics.asset.bitmapData.rect,new Point(position.x,position.y),null,null,true);
}

Once iteration has been triggered this will be called once for each entity in the family. It uses the data in the position component to copy the asset in the graphics component to the screen. So now to trigger the iteration we just call

_family.startIterator();

Our final task is to add our system to the game. So at the end of our games start up function we add

systemManager.addSystem(RenderingSystem);

OK and that’s all we need to draw our asset to the screen. Not much use by its self but next post ill show how to send events between systems by injecting signals.

There are now upto date demos complete with source code here

 

48 Responses to Getting started with Ember

  1. Plamen says:

    Hi there, I like your system and I would like to try it. But there are some things that I don’t understand.
    - what is SystemManager and where do I use it? It only have add/remove/destory methods. I can’t extract anything from it.. Is it just a helper for the Game ?
    - Should I call update somwhere? How should I update my game? For example, if I have enterFrame events firing… what should I call?..

    In other words, I need simple example how to use it. Sorry, I’m a noob, I know.. but yet I like your approach and it would be really helpful to explain a bit more :)

    Thanks,
    Plamen

  2. Plamen says:

    While trying to understand how to work with Ember I found something that seems to me like a bug.

    public function destroy():void{
        _entityManger.removeEntity(_id);
    }
    public function removeEntity(entityId:String):void {
        for each(var component:Object in _components[entityId]){               
            removeEntityFromFamilies(entityId,getClass(component));
        }
        delete _components[entityId];   }

    You never truly destroy Entity objects. Entity is not nullified anywhere. Also, the entity has a reference to the EntityManager which is not nullified in the Entity.destroy().

    Please correct me if I’m wrong. Also, I’m still not sure how to use it :(

    I’m thinking about a simple game just to understand how to use it.
    Asteroids game:
    RenderingSystem > render stuff and position them
    InputSystem > ??? not sure what to do. I would add InputComponent to my ShipEntity and probably InputSystem will push updated keys to the InputComponent but who and when will process these keys? Is the ShipEntity responsible for processing that info? Entity doesn’t have update() method, so when should I process taht info?
    CollisionSystem – this will collide the entities on the screen

    - Plamen

  3. Plamen says:

    Sorry, the tags seems to not work .. so, I’m reposting..

    While trying to understand how to work with Ember I found something that seems to me like a bug.

    public function destroy():void{
    _entityManger.removeEntity(_id);
    }
    public function removeEntity(entityId:String):void {
    for each(var component:Object in _components[entityId]){
    removeEntityFromFamilies(entityId,getClass(component));
    }
    delete _components[entityId];
    }

    You never truly destroy Entity objects. Entity is not nullified anywhere. Also, the entity has a reference to the EntityManager which is not nullified in the Entity.destroy().

    Please correct me if I’m wrong. Also, I’m still not sure how to use it :(

    I’m thinking about a simple game just to understand how to use it.
    Asteroids game:
    RenderingSystem > render stuff and position them
    InputSystem > ??? not sure what to do. I would add InputComponent to my ShipEntity and probably InputSystem will push updated keys to the InputComponent but who and when will process these keys? Is the ShipEntity responsible for processing that info? Entity doesn’t have update() method, so when should I process taht info?
    CollisionSystem – this will collide the entities on the screen

    - Plamen

  4. Plamen says:

    Hi again,

    one more thing that I can’t get.. Are the Entities just a higher level ValueObjects or just a container for ValueObjects without methods and if so.. why does Entity has ability to get components if it’s not going to use them? How should I update them or am I even supposed to? Is everything doing updates should be placed in a System?

    - Plamen

  5. admin says:

    Glad you like it. Looks like I need to get on and finish that next post. Ok ill try and answer most of these questions in turn.

    How do I update my game?

    I’m going to do a post on that but for now look at this class in the demo it should get you moving

    Removing entities.

    You correctly point out all you need to do is call _entityManger.removeEntity(_id); There is no need to set it to null as no reference to the entity object is ever stored. It is important to never store a reference to an entity in your code always ask the entity manager for one. This makes garbage collection easy and means when your done you can call removeAll()

    What are entities?

    A string. Its a unique ID against which the components are stored so they can be looked up. The entity class is just there to make coding cleaner. So entitiy.getComponent(Component) is really just this entityManger.getComponent(entitiy.id,Component).

    How to use it

    Well you on the right lines you will need a RenderingSystem, InputSystem, CollisionSystem and more. These do ALL the processing so for example your InputSystem for example could check every update to see which keys are held down and then update the entities position Compoments x and y values.

  6. Plamen says:

    Hi,

    I started reading T-Machine’s blog to further expand my knowledge about ES and it seems very powerful to me even for small games. I hope that I understand everything (I hope, because my initial attitude was totally wrong).. I’ll finish today reading posts 4 and 5 (and the comments) and come back to you.

    Regard entities destroying… Not sure whether entties are destroyed or not. GC uses reference counting and mark and sweep. So the only references are inside EntityManager and destroying the entity suppose to mark it for destroy, but it seems to me that the _entityManager reference inside the Entity keeps entities alive because you have a backdoor to use other objects. Hm.. confused. Never mind, it’s not that important as understanding the whole picture about ES.

    Edit: actually, you don’t hold direct reference to Entity anywhere at all. All you save is the id which is used to lookup components. I think that this will proof that entities are not destroyed, because if you can use them and there is no reference to them.. they are already islands.. and the only way to force them for GC is to remove all references inside Entity class to your living program. Also, I’m curious what will happen if I have something like that:
    var arr:Array = [new Entity(), new SuperHero];
    arr = null;

    Will the GC trash the elements used in the array? (Sorry if I annoy you regard the GC, just can’t stop thinking about it).

    Thank you for replying and I’m looking forward to explore more. :)

  7. admin says:

    no you are right to focus on garbage collection its often overlooked. I have focused on making thing easy for the developer so you have function such as removeAll() which removes all the games entities automatically. Ember does all of this for you and although Its not quite straightforward (as the entity families complicate things) you can look at it as no references to the entity objects them selves are kept. Its very important not to store references to entities or you will have problems. You can store a pointer to an entity family with out issue though. In you array example that would be disposed at the end of the function if no reference to arr is kept. I should point out that in Ember you don’t create entities with new Entity() but use entitymanager.createEntity()

  8. Plamen says:

    Sorry, the example wasn’t clear enough because EntityManager actually pass himself to the Entity
    So the exmpale is:
    var arr:Array = [new Entity(this, id)];
    arr = null;

    Will this be detroyed?

  9. admin says:

    The answer is yes it will be GC’ed

  10. Plamen says:

    Hi, you are right :) I had to read about GC before I post.. I skimmed through gskinner GC articles and get to know about “Mark sweeping”.
    I’m reading 4 & 5th posts at T-Machine. ALso took a look at your Ember_demo.That looks awesome!
    I’ll finish T-machines articles and try to do something with te example you’ve made. This explains lot’s of stuff to me (but I still have to get grasp on injections as well since its new to me). For now, I think I’ll use your Ember framework because it looks very promising and they way you program your game and you think about it looks more straightforward.

    Thanks for posting!
    See you later

  11. Plamen says:

    I was curious..
    if you need the systems to run in a particular order what would you do? Use deluxe signals with priority? For example, if I need preprocessing of all objects before next system do something…

    - Plamen

  12. admin says:

    Where ever possible I would avoid having to run systems in a particular order it implies dependacies which sould be avoided. In some cases though you have to do this I would then create a event for each. So in you main game loop you may have somthing like

    AITick.dispatch()
    render.dispatch()

    Its really up to you but I avoid using event priorites wherever posible.

  13. Plamen says:

    Hey thanks for answering my questions and the attention! You really help me a lot.

    Ah right, makes sense. Thanks, it will be simpler your way to have separate signals than using priorities.
    I have another issue now and I’m not sure how to procede. I have a case where I think that it will be good to have more components of the same class in 1 entity (for example, if I have a car it has 4 wheels). How do you solve such problems? I don’t really want to make separate component for everything and just rename them LeftBlah RightBlah.. etc, also this way I can’t add them dynamically. Did you had such problems before?

    - Plamen

  14. Plamen says:

    I’m curious how do you implement screens or level switching?
    Do you use Ember for everything or you have minigames (representing levels) which are loaded from the main app?
    (sorry to post another comment.. I can’t edit the previous one)

  15. admin says:

    Firstly i’d would probably use flex and a frame work like robotlegs to handle the splash screens and even the UI its what they are good at. Ember is for the game its self. Second I cant think of many situations where you would want components of the same type they are simply for storing data. Are your cars wheels are going to all be diffident in some way. You could just create a vector of WheelVO’s in your car component if this is the case? I must try and set up a forum for this kind of discussion.

  16. Plamen says:

    Isn’t robotlegs some type of injection as well? Why would you use robotlegs instead of SwiftSuspenders?
    Forum is good idea, since I’m interested in improving my design skills and using Ember for that purpose. Many people think that using frameworks like Ember is overkill but I do find benefits in your framework and reusability is key feature I like in it. Also the separation between data and logic. Nevermind, I’ll follow you if you create a forum :)

  17. admin says:

    Robotlegs is a framework that uses SwiftSuspenders for its injection. Frameworks are good as they promote a common set of practices and stop people reinventing the wheel (often badly).

  18. Plamen says:

    Hi there,

    can you help me a bit with my experiment. I’m trying to understand better Ember and I’m doing little game experiment.. but even in the beginning I feel overwhelmed and I can’t handle the HUD updating. I haven’t added the enemy ships at all…

    This file contains the source for my game.
    http://www.reevgames.com/SpaceShip.zip

    Plamen

    P.S. I thought that it’s easier to show the source rather explaining everything..
    Also if I get this game finished, we could add it to the Ember examples/demos..

  19. astrocreep says:

    hi tom,

    the entity system looks very promising. but i have some questions regarding the implementation of systems. in your examaple the renderingsystem works like a charm, cause the system itself is based on the list of entities provided by the entity manager. same with your physics example.

    but what about implementing systems that rely on on add and remove methods? i.e. a renderer based on the display list. or a box2d system? how would you handle adding and removing of entities in the systems? one option could be an internal list of already contained objects and synching the list provided by the entity manager on every tick. but that does not feel right when looking on the performance. maybe providing a signal or event which is dispatched by the entity manager when entities are added or removed to families?

  20. admin says:

    This is a really good question. I have thought about it my self and come up with the same idea of turning a family into an Object that has a vector of entities but also dispatches signals when they are added or removed for systems like the flash display list. In the world of console game engines that use scene graphs are out of fashion for these reasons. I guess I better make this a priority as it could effect any work people are doing. I’m currently working on a simple 2d engine and a demo so people can get a better idea of how to go about making games using an entity system. Id love people to get involved if you want to help out.

  21. admin says:

    Hi, some of what you have done looks very good and your work around for the display list integration is clever. I will do what I can to implement the changes talked about above quickly so its a lot simpler. As for the HUD personally I wouldn’t handle that in Ember unless its actually part of the game (like a enemies health) id lay it over the top. I’m not sure what your trying to achieve with the screens it sort of look like a state machine. I would take the time to learn robotlegs or PureMVC for your splash screens I know it seems like overkill for a simple game but its really very straightforward and you will learn a lot about good programming practices.

  22. Scot White says:

    Crazy.

    ember for the core, injectors to pass data, and signal for events. All of that for pure data. Wicked.

    What exactly is the difference between robotlegs or pureMVC other than MVC orientated? And which would you prefer?

    I’m learning, and I want to get a clear picture of exactly how graphics are handled.

    Looking forward to your demo!

  23. admin says:

    Ill probably get shot for saying this but robotlegs is basically puremvc with injection (they are both based on MVC). Robotlegs also does some clever stuff with mediators and views but it is flash specific. Unless you plan to port your game to other languages id choose robotlegs every time.

  24. Louis-Philippe Maurice says:

    Love the “family” idea. I’ve been working on a component framework along the same line as yours and the family paradigm solves one of my problems. I have a couple of comments/questions though:

    - How do you deal with an entity having to instances of a component e.g. a character having two SwordComponent?
    - While the iterator approach is very clean, isn’t it too costly to have a function call per (valid) entity per system?
    - also on the iterator subject: Wouldn’t sorting or comparing would be more complex and/or less efficient than if done in a loop inside of your update() (render() in the case of you example)?

    I’ll try to post my own framework on github over the next few days. Comparing notes is always interesting and valuable :) But first, it needs to be cleaned up a bit…

  25. admin says:

    cool look forward to seeing your take on this. To answear your questions one by one. First off don’t have two instances if you can avoid it. Instead have a compoment that contains a vector of value objects. If you do really want two then just extend a common base class. Second you can access the vector of entites in a family directly and loop over it if you like. This is avaible for the reason you bring up in your next question. I have focused on making things as simple and as clean as I can for the programer but you should find that signals are pretty fast. In my experience optimsation should always be done from the top down and thats a lot easier with nice clean modular code.

  26. Louis-Philippe Maurice says:

    Cool for the answers to questions #2 and #3. And I agree i.e. Signals. I’m also using as3Signals and SwiftSuspender in my framework.

    But concerning not having 2 or more of a given component for a single entity: I did the same thing you did (having a list of components nested in another component) but I’m still not sold. Thing is, I want to have an editor and the minute I’ll put it in the hands of a designer I know it will come up.

    Are you on twitter?

  27. admin says:

    In most cases I can think of you would want to limit your designers to single components Physics, AI etc. so you would have to have some way to manage that. Multiple components would add a fair amount of complexity and my instinct tells me that the simplest solution is probably best. Personally I haven’t yet hit situation where this is an issue.

    http://twitter.com/#!/tomsdavies

  28. Tim says:

    Hey guys,

    Interesting discussion! I’m building a component based entity framework myself at the moment.

    First an answer to one of the questions I saw:

    - How do you deal with an entity having to instances of a component e.g. a character having two SwordComponent?

    I would avoid using two components of the same family/type, but instead create multiple states inside one components. So for a car with 4 wheels, create one “wheel” component that has a front-left, front-right, rear-left and rear-right wheel. Another example of this would be a player that has hitpoints for different bodyparts. Just create a Hitpoints component that has an array of bodyparts (with their hitpoints).

    While creating my framework I also ran across some nasty problems:

    Consider a game where we have 2 players (player A and B). At the exact same time they start an attack on eachother (A attacks B and B attacks A). Player A has 5 hitpoints and player B has 2 hitpoints.

    Now if I update() player A first, check for input, attack player B (send a message to that entity saying he got attacked for 3 damage). If the player B entity processes that message right away, then when update() for player B runs, the game logic will say player B can’t attack because he’s dead. That’s unfair to player B because within one update() cycle, every event is happening in parallel. The outcome of this should be that A hits B and B hits A and after hitting eachother, player B drops dead.

    One way of handling this might be to store the message to player B in a queue and process it once update() for player B is executed. That way I could prioritize the component that processes the moves for player B and have player B attack before the damage is substracted from his hitpoints (killing him). However, the problem here is that update() for player A is already finished. So player B send a message to player A with damage aswell, but it won’t be processed before the next update() cycle. And if I process messages after processing moves, then player A will be allowed to move in cycle 2 while he’s actually dead…

    Any ideas on this?

  29. admin says:

    Good to see other people using entities. I think the issue you raise isn’t confined to entity systems and is more a general game programming issue. I’m not sure if your entity system works like mine but if it does then you have an two simple solutions depending on the desired out come.

    They both die. In the system up loop through all the entities and update there health values based on the attacks but don’t remove them. Then loop through them again removing any entities with a health value less then 1.

    The weakest dies. Sort all the entities in order of descending health values. Loop through process the attacks and remove any entities where the health is less than 1

  30. John says:

    Hi!

    I’ve been trying to build up an Entity System (using the T-machine.org articles philosophy).
    It does look great in theory but I run across many problems when attempting to implement it. I’m losing a lot of time >_<

    One of my current problems is indeed "what if an entity has 2 components of the same type?".
    This brings many problems, yet "only one component of type T" has its own limitations… Here are problems that I stumbled upon so far, how would you go about solving them concretely?

    1- An entity can have multiple boosts that have their own animation, duration and even sometimes, their own hit radius (e.g. an aura around the player or an enemy).
    I could add to this entity an animation component and a hit radius one, but how to keep track of which components to remove and when? I'm guessing, by using a "Boost" component that holds refs to its brother components, since it's created with them and killed with them.
    But then there's my main problem with this: How to ensure that the several animations are run correctly? An entity may have a "Run" animation and an "Attack" one, and obviously having one active MUST mean the other stays inactive, but many other animations (like boosts) would still need to be rendered alongside the main "unique" ones.
    How on earth would you handle this without introducing data dependency within unrelated components? Using a "isMainAnimation" and "isActive" pair for main animations sound like an example of ugly data dependency (what if I mistakenly let two main animations be active at once)

    2- Now if I only allow one component of type T, it's a lot easier at first (like entityManager.getComponent finally sends back components and not arrays that we have to invent ways to sort as we intend, like "which animation is rendered above which, and which should not be rendered at all", encumbering the AnimationSystem). I could also group all main animations within one unique "MainAnimationComponent" and there goes another problem, but what now with secondary animations like boosts? They can't be unique. Grouping them within a special "SecondaryAnimationsComponent" set to run several anims concurrently sounds weird though it may be the right thing to do, I don't know, it seems to break the ES philosophy. Components are supposed to be interchangeable units that can be attached to any entity, not holders for many subcomponents or garbage cans…

    3- Maybe make boosts be separate entities attached to the boosted player/enemy entity? Would you choose this option? If so, how would you implement it concretely? Especially since the boost animation may have a part of itself drawn below the player/enemy and another one above, yet entities tend to be rendered at only one depth.

    I would really appreciate any help you're willing to give. :)

  31. admin says:

    I’m not too surprised your having trouble figuring this out because you confused the hell out of me :) I’ll try and break this down and tackle some of the main issues.

    1) Single component vs. multiple components
    I personally think single components are the way to go. I can’t think of many scenarios where having multiple components is useful but I can think of lots where insuring only one component per Entity is. However not everyone agrees Louis Maurice has a framework that allows multiple components https://github.com/lpmaurice/TinyGentleman here.

    2) Managing Animation
    This is very difficult to give a definitive answer not even knowing if you’re using sprite sheets or movie clips (i’m guessing clips from your issue). I only support a single animation playing at a time. I have a single “AnimationCompoment” to which I can add “Animations” these have a string to id them and contain the details of the animation (frame id, playing etc). The animation system then quizzes the AnimationCompoment each frame gets the active animation checks its status and plays it or stops it accordingly.
    It would be easy to modify this to allow multiple animations to play at once. Insuring uniqueness would then be data management issue. Attentively creating a “BoostAnimationCompoment” that allows multiples and a “MainAnimationCompoment” that doesn’t is perfectly fine as long as they don’t reference each other and you keep everything data driven. You could have a concept of animation channels that insure uniqueness on a channel basis if you wanted a catch all approach.

    3) Managing collisions based on animations.
    This is a complicated area and you need to find the solution that fits your game best. Often using sprite sheets for animation they are associated with data that holds the bounding box for each frame. With MovieClips you can obviously hit test on the shape or you can do a pixel perfect test described here http://troygilbert.com/2007/06/pixel-perfect-collision-detection-in-actionscript3/
    Hope all this helps a bit and good luck

  32. John says:

    Hi!

    Thanks for the reply, you were quite on the spot despite being confused by whatever I muttered :D

    I’ll try to be more precise this time. First, a precision on how I deal with animations could help:
    I use MovieClips converted to BitmapDatas so that they can be either attached to their own Bitmap or blitted to a big Bitmap canvas. One of the many advantages I see in converting vectors at runtime is that I can convert subclips independently from one another for each frame of the main clip animation. Say I want to convert a vector art attack animation of a humanoid with a custom weapon, a custom hat and some fancy boots. With MovieClips custom items are not an issue, but they are when dealing with BitmapData. What if the animated character wants to wield another weapon? The solution I found is to make all parts of the attack animation invisible during the conversion process, except one, and convert it to its own BitmapData “attack animation”. And repeat for all parts of the animation (body, boots, weapon, hat). I save items to some repository where they can be used by other humanoids, since all humanoids have the same attack animation.
    And I blit these items at the correct depth when drawing said humanoid (for instance, a left hand weapon would be drawn behind hats, boots, right hand weapon, …)
    I don’t know if there are better ways to make custom items compatible with pre-rendered animations (pre-rendered as opposed to vectors)

    Feel free to give your opinion or critics on that if you want even though that’s a little off topic :)

    Back to the main point, you’ve given me a few things to ponder…
    On the matter of “an entity has only one component of a given type”, despite some advantages, can’t it sometimes break the ES philosophy? As I understand it, I should be able to take any component from any entity, move it to another entity and have that new guy acquire the component’s features instantly (be it camera, controller, or some metamorphic magic effect changing a mage into a troll (ie. mage skills become dormant, troll skills pop in, appearance change, movement too, …).
    But if a component is unique, aren’t there times where it starts holding too much data? If I put 20 animations inside a component, that’s 20 duplicates of the exact same group of properties (in OOP that would be 20 different instances of an Animation class). Isn’t it uncompatible with what a component is supposed to be?

    Uhhh… Okay, let me reverse the reasoning and try to solve a real situation instead of babbling and making no sense. With the following 2 thought experiments I think you’ll be able to un-confuse me :p

    1- What would YOU do if you had a mage, AI or player controlled, casting a metamorphose spell on himself. The spell lasts only for so long, and during that time the caster cannot do any mage related stuff. He gains troll abilities, i.e. he’s a lot better at physical attacks, regenerates health, moves faster, has a bunch of new graphics and animations, his weapon is changed to “bare claws” and whatever else. When the spell vanishes everything gets back to what is was and troll data is deleted.

    That’s a lot of components to keep track of, and assuming you enforce unique components there may be SOME comps that will need to be modified in weird ways in order to work properly, and you could end up mixing some troll and mage data in the same components…no? How would you go about this?

    2- Second experiment: What if a mage (what’s up with me and mages anyway?) casts protection spells on himself. Let’s say he casts 3, one vanishes after a minute, another after an hour and the last is permanent until dispelled. They all have their own graphical animated effects (let’s assume we use my way to make animations unless you’re not comfortable with my description of it).
    One of the spells reacts when an hostile creature is within a 10 meters radius from the caster, another within 5 meters and we don’t care about the 3rd one.
    The mage of course has his own collisions to check for (so he doesn’t walk through walls ^^).
    How would you organize your components and systems to account for:
    A- The different animations staying with the mage no matter what’s his main animation (walk, attack, …). For this I guess you already replied, a “BoostAnimationComponent” that can exist in multiple instances as an exception to the uniqueness rule (and handled as such by the AnimationSystem)
    B- The different hit areas that have to be tested on each game tick
    C- How many components are created per spell, and how/where to keep track of them so they are all deleted properly when time is up or when they are dispelled. If no additional component is created then existing ones receive the spell data, but the question still applies
    D- Anything else :p

    That’s it, I’m sorry it went so long and I hope it won’t be a hassle for you to reply (better if you find it interesting actually :p)

    Thanks for Ember and keep up the good work!

    (By the way, the link you gave me to Louis Maurice’s framework on GitHub says 404 >_<)

  33. admin says:

    Havn’t got to long so this will be brief

    Bitmap(blitting) vs movieclips)

    lots of info on this. Blitting is faster but its harder to do thing like change the scale of you game 1/2 way through.

    Question 1)

    great example of something that is easy to do with and entity systems. Just keep the “player input component” and may be the “players health component” remove the rest and load in the trolls component data. easy.
    You shouldn’t be mixing up any data.

    Question 2)

    Not sure if you got what i was trying to say in my last post. Im saying a single component my contain lists(vectors) of objects as long as its only data. As long as everything is data driven then you cant really go wrong.

    For your spells you may have a “ranged spell component” which may have a vector of “effects”. Each effect may have a radius, damage, target group, lifespan and elapsed time data.

    They system then picks up all entities with that component and then for each of the “effects” it would check for collisions in the “radius” with the “target group” and apply the damage. Each tick it would also increment the elapsed time and if its now greater than the lifespan remove the effect.

    Entity systems our powerful but you have to relearn what you know about game dev.
    Sorry I’d dint realise Louis repository is private.

  34. John says:

    Thank you, I think I understand better what you mean now.

    As far as I can see, I understood correctly the part where you put lists of objects inside a single component. That’s what seemed to go against T-machine’s ES philosophy to me, but it seems to work smoothly the way you put it so I will give it some more thought.

    About question 1: but where do you put the mage data? You can’t ditch it like that if you have to restore it and the values are not the default entity template anymore. Put references to them in a “PreviousFormComponent”? O_o (sounds against the philosophy but…)
    Then when the spell ends, the MetamorphoseSystem (isn’t that system too specific though?) would ditch troll components, restore those in PreviousFormComponent and ditch that one too?

    Uhh, I think I’m diverging from your blog post’s topic though… Sorry, I just can’t find knowledgeable help on Entity Systems anywhere else, I’m kind of on my own. (Adam from T-machine has been silent on this for a month. I don’t blame him of course after all the help he gave to people in his articles’ comments and the wiki)

    So yeah thanks again dude, I’ll try not to spam your blog post with this any longer :D

  35. Hi Tom,

    In your bunny speed test example I noticed something that is bothering me. You’ve duplicated the boundries in BounceSystem and RenderSystem. In every game there is data that could be shared among all the objects like the size of the screen in your case. The first thing that comes in mind is to use component to hold the data since components are the only data holders we have, right? What approach would you take for such global date without duplicating it?

            private const _maxX:int = 640;
            private const _minX:int = 0;
            private const _maxY:int = 480;
            private const _minY:int = 0;

    Regards,
    Plamen

  36. Also,

    I would like to see the inter-system-communication exmaple :).

    OK and that’s all we need to draw our asset to the screen. Not much use by its self but next post ill show how to send events between systems by injecting signals.

    Btw, how is the 2d engine you are working on? Any progress on it? What I really need are more complex examples so I can see Ember in action from different angles in full glory. Oversimplified examples are good for explaining the concept but sometimes not enough to get clear picture :)

    - Plamen

  37. admin says:

    Quite right this data should not be duplicated. Its becuase I was copying this in a bit of a hurry getting ready for a talk. Probably the best way to deal with data that needs to be shared between systems is to create a model class and register that with the injector. You can then inject where ever its needed.

  38. admin says:

    Palamen,

    In the bunny demo’s there are examples of inter-system-communication. In the game context we map a signal class like this

    injector.mapSingleton(Tick);

    then we can inject it into a system needed

    [Inject]public var tick:Tick;

    Simple as that. Not much progress on the engine at the moment im afraid. Im over busy with other work but hopefully I will get a chance later this year.

    Tom

  39. Hi Tom,

    thanks for the info. Nice presentation :). I’ll check your blog at a later time for updates. Good luck with your stuff.

    - Plamen

  40. jayden says:

    I tried to build the bunny demo but I get the following error:

    Error: Injector is missing a rule to handle injection into target [object RenderSystem]. Target dependency: com.tomseysdavies.ember.base::EntityManager

    ill go through the swiftsuspenders/robotlegs docs since im new to dependency injection, but is there any possibility of getting a complete working demo, or a hint to fix the problem.

    After reading up on the entity system approach, im thinking its worthwhile using it for a game engine im working on now, since its rendering code would be interchangable/easier to replace with future gpu enhanced methods etc. in theory anyway, id like to keep that door as open as I can.

    -Jayden

  41. admin says:

    Jayden, Richard Lord correclty suggested the EntityManager should be injected with its interface so that change was made. In the demo change the injection points to IEntityManager and you should be fine. Some more major changes may be due soon which is why nothing is cuttenlty being kept upto date.
    As you correctly point out one of the many advantages of this is being able to swap the rendering system easily. In therory you could acutaly do this at run time!

  42. jayden says:

    Thanks for the response,
    before I read your comment I managed to get it working by adding

    override protected function mapInjectors():void{
    injector.mapValue(EntityManager, entityManager);
    super.mapInjectors();
    }

    to SpeedTestGame.as of the bunny demo

    Ill probably hold of on too much more blind fiddling in eager anticipation of the updates now. :)

    I think its a great system so far.
    thanks.

  43. jayden says:

    I have been doing some more playing with the framework, and I’ve hit a brick wall with how to handle graphics layering on the current system.

    I came up with some not so optimal solutions, so I was wondering if the next iteration of ember has a solution built in, or whether there is a clean way to sort nodes.

    My solution involved having an array in the render system which contained the rendernodes and can be signalled to update/re-sort when a rendernode is added/removed. – its obviously a bit hacky and defeats the purpose of the system.

  44. admin says:

    Hi sorry for the dealy in the response. This is not somthing i’ve really thought about so its always good to here these usercase. As this isnt going to be too common I think your solution is pretty good. However it would mean you can’t change the depth of an entity once its been added. I guess in that case you would have to create a sorted list every frame. I suppose in the same vein you could possibly also want to include in this some way to filter nodes. Certainly somthing for me to think about. If only we had generics in AS3 then we could just create a vector of nodes and sort that.

  45. jayden says:

    Its not too bad I guess, heres the implementation for anyone interested. The native array sort is fast so its likely the whole game will run slow with or without it if you have too many entities being added/removed or changing layers.

    —–in the game class—–

    private var _resortLayers:ResortLayers = new ResortLayers(); //ResortLayers is a signal the same as Render/Update etc..

    override protected function startUp():void
    {
    var renderNodes:IFamily = entityManager.getEntityFamily(RendererNode);
    renderNodes.entityAdded.add(renderableEntityAdded);

    injector.mapValue(ResortLayers, _resortLayers);
    }

    private function renderableEntityAdded(renderNode:RendererNode):void
    {
    _resortLayers.dispatch();
    }

    //! there will also need to be a dispatch sent for when an entity changes its layer depth and when an entity is removed.

    —–in the rendering & sorting system—–
    public class RenderSystem implements ISystem
    {
    [Inject]
    public var render:Render;

    [Inject]
    public var resortLayers:ResortLayers;

    private var _sort:Array = [];

    public function onRegister():void
    {
    render.add(onRender);
    resortLayers.add(onResortLayers);
    resortLayers.dispatch(); //without this the array will stay empty if the system is created after the last entity.
    }

    public function onResortLayers():void
    {
    _sort = [];
    for (_renderNodes.start(); _renderNodes.hasNext; _renderNodes.next())
    {
    _sort.push(_renderNodes.currentNode);
    }
    _sort.sortOn(“layer”);
    }

    public function onRender():void
    {
    for (var i:int = 0; i < _sort.length; i++) //maybe this is actually faster than using the _renderNodes access methods anyway?
    {
    node = _sort[i];
    //the usual….
    }
    }
    }

    —–change to give renderNode a property to sort on—–

    public class RendererNode extends Node
    {
    public static const componentClasses:Array = [SpacialComponent, GraphicComponent];

    public var spacialComponent:SpacialComponent;
    public var graphicComponent:GraphicComponent;

    public function get layer():int
    {
    return graphicComponent.layer; //graphics can now have their rendering order changed with an added layer property.
    }

    public function RendererNode(entityID:String, components:Dictionary)
    {
    super(entityID, components);
    spacialComponent = components[SpacialComponent];
    graphicComponent = components[GraphicComponent];
    }
    }

  46. Mangan says:

    I’m still new to Entity Systems, but found this page through my researching.
    Anyway, in response to the mage transforming into a troll questioning, although a bit late:

    Couldn’t the “TrollTransform” System do the following:
    1) Create a new “TransformedTroll” Component, which has troll-data as well as an empty list of the blocked Components.
    2) Remove all the mage’s Components that should be blocked, moving them to the “TransformedTroll” Component’s list of blocked Components.
    3) Apply the “TransformedTroll” Component to the mage.

    Then the System that eventually cancels (removes) the “TransformedTroll” Component would reapply the removed Components, which it would have access to through the “TransformedTroll” Component. In essence, the removed Components are just blocked (unseen by the Entity & Systems that would use them), and treated as data as part of the “TransformedTroll” Component.

    Only downside that immediately pops out at me is that two Systems rely on one another in this example, unless there was a clean way to do it in a single system… I can think of an easy way off the top of my head, but it seems like a hack:

    When the mage is to be turned into a troll, simply apply the “TransformedTroll” component with a boolean data flag marking that it has yet to change. The “TrollTransform” System would depend on this one component, and could handle both stages of the troll: transform into troll and transform back to normal.

    Comments/opinions/criticism welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>