C# Artemis Entity System Tutorial


Artemis is a high performance Entity System framework for games, originally written in Java by Arni Arent and Tiago Costa, now ported to C#.
Its goal is to provide a clean API to abstract your game world organization into entities, components and systems.
Artemis has no dependencies (for PC, in Xbox and Windows Phone 7 we have one) and can be used with any game framework or library, 2D or 3D, and even multiplatform, if you use it with Mono/MonoTouch/Mono4Android.

Differences from the original version

We support all the features included in the original Java version, but we’ve also added the following features:

  • Multithreading Support (two ways of doing this)
  • Specialized System templates for your multithreading needs
  • Communication between Systems using a Blackboard approach
  • Bugs fixed, performance improvements
  • Xbox/WP7/Mono(Android/Linux/Mac/iOS) support
  • Events for intercepting adding/removal of entities/components
  • Blackboard for sharing common objects between systems
  • Entity Pool (to make objects reusable, minimize garbage collection activity, improve performance)
  • Small goodies, like feeding the EntityWorld with whole Entities(maybe loading from external resources), enabling/disabling systems and entities, getting Entity tag, API shortcuts(see unit tests for more on this), etc.

Getting Started

  • Entities are only an aggregation of Components, identified by a unique id
  • Components are only data
  • Systems publish/subscribe to Components, creating behavior

There is much more to tell about this paradigm and we already have rich articles which inspired this framework. Some of them:

And many more can be found here.

Your components must inherit from the class Component or ComponentPoolable if you want it to use the Artemis Component Pool. Example:

//Add this Attribute and extend ComponentPoolable if you want your Component to use Artemis Component Pool
[Artemis.Attributes.ArtemisComponentPool(InitialSize=5,Resizes=true, ResizeSize=20, isSupportMultiThread=false)]
class Velocity : ComponentPoolable
{
        private float velocity;
        private float angle;

        public Velocity() { }

        public Velocity(float vector)
        {
            velocity = vector;
        }

        public Velocity(float velocity, float angle)
        {
            this.velocity = velocity;
            this.angle = angle;
        }

        public float Speed {
            get { return velocity;}
            set { velocity = value; }
        }

        public float Angle
        {
            get { return angle; }
            set { angle = value;}
        }

        public void AddAngle(float a)
        {
            angle = (angle + a) % 360;
        }

        public float AngleAsRadians
        {
            get { return (float)Math.PI * angle / 180.0f; }
        }

        //obligatory for poolable Components
        public void Cleanup()
        {
             coords = Vector3.Zero;
        }
}

A sample for entity assembling:

Entity e = world.CreateEntity(); // you can pass an unique ID as first parameter.
e.AddComponent(new Transform(200,400));
e.AddComponentFromPool(new Velocity(2.4f,0.9f)); // use AddComponentFromPool if the Component extend from ComponentPoolable
e.Refresh();// always call Refresh() when adding/removing components!

Your systems should inherit from one of the following templates:

  • EntitySystem – the simplest system template, not tied to components, good for stuff like collision
  • EntityProcessingSystem – a template for processing many entities, tied to components
  • IntervalEntitySystem – a simple system template, not tied to components, process periodically, based on world delta.
  • IntervalEntityProcessingSystem – a template that process entities periodically, based on world delta, tied to components.
  • ParallelEntityProcessingSystem – a template to leverage your multicore CPU for processing many entities, tied to components
  • ProcessingSystem – a template that process whichever logic you desire, without being tied to components
  • QueueProcessingSystem – instead of filter by components, this system process entities that are added to its public queue
  • HybridQueueProcessingSystem – process entities by queue and components
  • QueueProcessingSystemThreadSafe – process entities by a public static thread safe queue
  • FQueueSystemProcessingThreadSafe – process anything (not only entities) added to its public static thread safe queue
  • TagSystem – a simple system template, not tied to components, process a tagged entity
  • IntervalTagSystem – a simple system template, not tied to components, process a tagged entity periodically, based on world delta.
  • DelayedEntitySystem – a simple system template that starts process after a given time, based on world delta.
  • DelayedEntityProcessingSystem – a template that starts processing entities after a given time, based on world delta. Tied to components

And here is a system example, using Velocity and Transform components to create the Movement behavior:

//Add this attribute so the EntityWorld knows the systems it should execute, use the Layer to determine execution order
[Artemis.Attributes.ArtemisEntitySystem(ExecutionType = ExecutionType.UpdateSynchronous, Layer = 1)]
public class MovementSystem : EntityProcessingSystem {

    public MovementSystem() : base(Aspect.All(typeof(Transform), typeof(Velocity))) { }

    public override void Initialize() {}

    public override void Process(Entity e) {
        Velocity velocity = e.getComponent();
        float v = velocity.Speed;

        Transform transform = e.getComponent();

        float r = velocity.AngleAsRadians;

        float xn = transform.X + (TrigLUT.Cos(r) * v * world.Delta);
        float yn = transform.Y + (TrigLUT.Sin(r) * v * world.Delta);

        transform.SetLocation(xn, yn);
    }
}

On your game initialization, create a new EntityWorld and initialize it:

var world = new EntityWorld();
world.InitializeAll(true); // pass true/false to enable/disable DataAttributes on Systems

Update or Draw the World:

world.Update();
world.Draw(); // do this on a different loop, e.g: every 15 ms

And you are good to go. The Entity object has some intuitive methods like Delete(), GetComponent(), RemoveComponent(), which you can see in action on the example game.

Aspects

Aspects are used in the constructor of your entity systems to tell them which components they should be interested. At the moment we have three methods to build Aspects:

  • Aspect.All(params Type[] types) – Most of the time you will use this option, so the system processes entities which have all components of the Aspect.
  • Aspect.One(params Type[] types) – The system will process entities which have at least one of the components of the Aspect.
  • Aspect.Exclude(params Type[] types) – The system will not process entities which have at least one of the components of the Aspect.

You can also compose your Aspect utilizing these methods together, example:

public LogEnemySystem() : base(Aspect.All(typeof(Health)).One(typeof(Koopa),typeof(Goomba),typeof(Magikoopa)).exclude(typeof(Ghost))) {}

Extending Systems

It’s quite simple to extend the EntitySystem with your own logic, an example can be found here, which gives us less setup on systems which only uses Aspect.All(), example:

[Artemis.Attributes.ArtemisEntitySystem(ExecutionType = ExecutionType.UpdateSynchronous, Layer = 1)]
public class MovementSystem : EntityComponentProcessingSystem {
    public override void Process(Entity e,Transform transform, Velocity velocity) {
        float v = velocity.Speed;
        float r = velocity.AngleAsRadians;

        float xn = transform.X + (TrigLUT.Cos(r) * v * world.Delta);
        float yn = transform.Y + (TrigLUT.Sin(r) * v * world.Delta);

        transform.SetLocation(xn, yn);
    }
}

Templates

Create your entity templates to avoid manually creating and configuring entities:

[Artemis.Attributes.ArtemisEntityTemplate("BulletExplosion")]
public EnemyTemplate : Artemis.IEntityTemplate {
	public Entity BuildEntity(Entity e,EntityWorld entityWorld, params object[] args) {
		e.AddComponent(new Transform(200,400));
		e.AddComponent(new Velocity(2.4f,0.9f));
	}
}

Create your entities with the template applied:

var enemy = world.CreateEntityFromTemplate("BulletExplosion",array_of_parameters); // you can also use an alternative signature passing a custom unique id as the first parameter.
enemy.Refresh();

Blackboard

You can easily share common objects between systems using the blackboard, here is a XNA example, on the game initialization:

EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
EntitySystem.BlackBoard.SetEntry("GraphicsDevice", GraphicsDevice);
EntitySystem.BlackBoard.SetEntry("SpriteBatch", spriteBatch);

Then you can retrieve the objects inside systems like this:

this.device = EntitySystem.BlackBoard.GetEntry("GraphicsDevice");
this.spriteBatch = EntitySystem.BlackBoard.GetEntry("SpriteBatch");
this.contentManager = EntitySystem.BlackBoard.GetEntry("ContentManager");

Games created with Artemis C#

Magnetic by Nature – by Tripleslash Studios. They also have a Kickstarter running for the game, support it!

Discussion, issues, suggestions

We have a forum section here.

 Use It !!!

,

  1. #1 by (PANERAI)パネライコピー時計 on 16 de julho de 2017 - 10:57 pm

    http://www.museumrudana.com/ポールピココピー
    [url=http://www.explorenusapenida.com/](PANERAI)パネライコピー時計[/url]

  2. #2 by CharlesDiado on 16 de julho de 2017 - 11:16 pm

    wh0cd638756 [url=http://buyfluoxetine.us.org/]fluoxetine hcl 40 mg[/url]

  3. #3 by http://www.counterweight.org/shoeswomen.aspx on 16 de julho de 2017 - 11:56 pm

    We have bought that brand to bracelet some times. Every one is ultra attractive, established very well, does not tarnish and significant based on that an individual you buy furthermore which people bring that it in order to.

  4. #4 by dobdok on 17 de julho de 2017 - 2:11 am

    「映画を見ながら泣くことがある」と本人も明言しており、また2004年夏に出演した「24時間テレビ」では、番組後半の相葉雅紀がメンバー宛に書いた手紙に真っ先に泣き出し、結局松本は番組が終わるまでほぼ泣き通しだった。 (>_<) 気が付いたガンジュンは、「ナワ~!」と叫びましたが、これは縄で縛られたからではなく(当たり前)、ナワ~(出てこい~)の意味ですね…。 [url=http://m-tanpopo.com/doctor/dvdbox_1/index.html]大門 ミチコ[/url]
    どのくらい上までなら付き合える?「前は『お父さんより年下の方だったら』と言ってたんですけど、お父さんも結構歳を取ってきちゃったので(笑)。 客観だからこそ、ゆるく判断することが許される(部分もある)D 主観新人賞ベスト30新しい物事に対して、人は、正しく判断できない(気がする)。
    [url=http://ofeqinst.com/nide/dvdbox_1/index.html]君の名は 動画[/url] 業績上方修正やターゲットバリュエーション基準期を来18.3期に変更したことなどを背景に、目標株価は引き上げ。 一方、キム・ソヨンは全51話のドラマ『家和萬事成』で、初めて母親演技に挑戦した。
    [url=http://avanzar.in/wp-content/nvdan/dvdbox_1/index.html]美女 の 誕生 ネタバレ[/url]
    「戦争放棄」の日本が「戦争をする国」に変えられてしまった。 にしても、どうかそのままどこか別の場所へ行ってください。 [url=http://www.interexpo.si/wp-content/qiyue/dvdbox_1/index.html]結婚 エピソード[/url]
    これまで世界中のトップアーティストが出演し、独創的で個性あふれるアコースティックライブの源流としてその歴史を刻んできた。 突っ込まれた思い出に帰り写メしておきました。
    [url=http://chinese.bacvietluat.vn/shiba/dvdbox_1/index.html]ボクらの勇気 未満都市 逮捕[/url] でも、コツコツ演技をしてきて・・・注目され始めた俳優です。 一方、今年カンヌ国際映画祭フィルムマーケットにはカン・ドンウォンが主役を演じた新しい映画『ゴールデンスランバー』が、マーケット関係者たちに初めて披露された。
    [url=http://www.gefsc.com/haizei/dvdbox_1/index.html]ワンピース dvd box[/url]

  5. #5 by funny on 17 de julho de 2017 - 4:32 am

    Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.

  6. #6 by bankruptcy attorney in oxnard ca on 17 de julho de 2017 - 4:52 am

    Hey there! Someone in my Facebook group shared this website with us so I came to take a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Excellent blog and terrific style and design. Keep up the really good work!

  7. #7 by Pets on 17 de julho de 2017 - 4:54 am

    I gotta bookmark this web site it seems handy invaluable

  8. #8 by http://www.ecova.es/weddingshoes.asp on 17 de julho de 2017 - 5:33 am

    Your device is in such a very good amount I never thought the excellence is therefore excellent. Its gorgeous. This one mama may love they concerning Christmas time early morning anytime she opens up gifts and it appears as though I devoted way more, then again rates had been really ideal!!

  9. #9 by http://www.indianmilkproducts.com/sneakers.asp on 17 de julho de 2017 - 5:33 am

    I have purchased our brand name to bracelet various instances. Every one is super pretty, manufactured very well, does not tarnish and also meaningful based on which kind of an individual you buy plus just who shoppers promote that to.

  10. #10 by 出産後 on 17 de julho de 2017 - 5:44 am

    産後のママは子育てや家の仕事で大変です。
    寝不足、夜中の授乳、育児のストレスなど男には理解できないと思います。
    そのような時、朝起きてみたらたくさん自分の抜け毛を見ると
    心配になります。
    はじめはビックリするかもしれません。
    抜け毛が激しくて頭の地肌が見えたら頭の中が混乱する事も
    あることでしょう。
    でも、産後の抜け毛はどんなお母さんでも経験しています。
    なのでそう心配しなくても大丈夫です。
    しかし、抜け毛ケアを怠ると後で大変な事になるかもしれません。
    出産後の抜け毛ケアはしっかり絶対行いましょう。

  11. #11 by Liberty Dentist on 17 de julho de 2017 - 6:04 am

    It’s very simple to find out any matter on web as compared to textbooks, as I found this post at this website.

  12. #12 by home warranty on 17 de julho de 2017 - 6:16 am

    Everyone loves it whenever people come together and share views. Great website, stick with it! Is it OK to post on Tumblr? Keep up the terrific work!

  13. #13 by home warranty on 17 de julho de 2017 - 6:42 am

    I like this! I havenÕt ever found a post as interesting as yours. It’s very cool. Is it OK to share on Twitter? Keep up the superb work!

  14. #14 by Dorislom on 17 de julho de 2017 - 6:47 am

    Revolutional update of SEO/SMM software “XRumer 16.0 + XEvil”:
    captchas breaking of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
    and more than 8400 another categories of captchas,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

    Interested? You can find a lot of demo videos about XEvil in YouTube.
    Good luck 😉

    XRumer201707

  15. #15 by hermes bracelet replica on 17 de julho de 2017 - 6:52 am

    I’ve bought it brand name to bracelet some instances. Every a person is super sweet, manufactured well, does not tarnish to significant depending on that one you purchase additionally just who you award information technology towards.

  16. #16 by home warranty on 17 de julho de 2017 - 7:05 am

    Is it OK to share on Google+? I am sure this article will drive a lot of users, its really really nice Keep up the wonderfull work!

  17. #17 by AlfredZob on 17 de julho de 2017 - 7:20 am

    wh0cd712225 [url=http://buyclonidine.us.org/]buy clonidine[/url] [url=http://hydrochlorothiazide.us.org/]hydrochlorothiazide[/url]

  18. #18 by Colorado home warranty on 17 de julho de 2017 - 8:17 am

    Hey! Someone in my Facebook group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Great blog and outstanding design. Keep up the fantastic work!

  19. #19 by how bitcoin really works on 17 de julho de 2017 - 8:17 am

    Aw, this was a really nice post. In idea I would like to put in writing like this additionally ? taking time and actual effort to make a very good article? but what can I say? I procrastinate alot and by no means seem to get something done.

  20. #20 by CharlesDiado on 17 de julho de 2017 - 9:16 am

    wh0cd22342 [url=http://buy-propecia.store/]propecia online cheap[/url] [url=http://elimite.shop/]elimite[/url] [url=http://buy-trazodone.reisen/]50 mg of trazodone[/url] [url=http://levaquin.zone/]levaquin[/url] [url=http://buysuhagra.store/]suhagra[/url] [url=http://metformintablets.pro/]metformin xl[/url] [url=http://cafergot.fail/]cafergot online[/url] [url=http://amoxicillin500mg.store/]amoxicillin 500 mg without prescription[/url]

  21. #21 by bankruptcy attorney in oxnard ca on 17 de julho de 2017 - 9:43 am

    Saved as a favorite, I really like your blog! Is it OK to share on Google+? Keep up the good work!

  22. #22 by Allegro Zgrzewarka Do Rur on 17 de julho de 2017 - 9:45 am

    I like what you guys are up too. Such smart work and reporting! Carry on the superb works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my website :).

  23. #23 by http://www.sundbirsta.com/ukclreplica.asp on 17 de julho de 2017 - 10:16 am

    Your device had been in that ideal pricing I never consideration all high quality would be quite exceptional. It’s gorgeous. Your mama will likely love they at Holiday morning after she opens up gifts and it styles like I invested way more, and yet cost had been simply great!!

  24. #24 by cheap louboutin shoes replica on 17 de julho de 2017 - 10:16 am

    I’ve purchased it brand name to bracelet some times. Every a person is very cute, made very well, does not tarnish and also important based on which kind of any you purchase and who we present this in order to.

  25. #25 by سالن آرایش تیکا اهواز on 17 de julho de 2017 - 10:23 am

    please take a look at the web-sites we stick to, including this one, as it represents our picks from the web

  26. #26 by Check Out Your URL on 17 de julho de 2017 - 10:50 am

    just beneath, are various completely not connected web pages to ours, nonetheless, they may be surely really worth going over

  27. #27 by Bennyempal on 17 de julho de 2017 - 10:55 am

    wh0cd389709 [url=http://amoxil.zone/]amoxil[/url] [url=http://inderal.world/]inderal[/url] [url=http://clomid.systems/]clomid[/url] [url=http://cymbalta.mba/]buy cymbalta online[/url]

  28. #28 by home warranty on 17 de julho de 2017 - 11:07 am

    Woah! I’m really digging the template/theme of this site. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness and visual appearance. I must say that you’ve done a very good job with this. In addition, the blog loads extremely quick for me on Firefox. Excellent Blog! Is it OK to post on Google+? Keep up the excellent work!

  29. #29 by home warranty on 17 de julho de 2017 - 11:34 am

    This is a wonderful blog. A great read. Is it OK to share on Pinterest? Keep up the amazing work! I’ll certainly be back.

  30. #30 by big boobs on 17 de julho de 2017 - 11:40 am

    Vist site for best live sex shows

  31. #31 by my blog on 17 de julho de 2017 - 11:42 am

    I constantly emailed this website post page to all my friends, as if like to read it next my contacts will too.

  32. #32 by click here on 17 de julho de 2017 - 11:42 am

    These are really enormous ideas in regarding blogging. You have touched some pleasant things here. Any way keep up wrinting.

  33. #33 by cheap louboutin shoes replica on 17 de julho de 2017 - 11:49 am

    We have purchased the brand to bracelet a few instances. Every single a person is super adorable, has made very well, does not tarnish as well as significant based on what an you purchase and/or whom people provide they and.

  34. #34 by cialis cheapest lowest price on 17 de julho de 2017 - 12:09 pm

    where to buy cialis in usa
    cialis blue pills
    buy cialis sydney
    [url=http://tadalafilopm.com/index.html#]cheap brand name cialis[/url]
    can you order cialis online for canada

  35. #35 by why not try this out on 17 de julho de 2017 - 12:21 pm

    Every the moment inside a whilst we choose blogs that we read. Listed beneath would be the most up-to-date web sites that we pick out

  36. #36 by hermes h belt replica on 17 de julho de 2017 - 12:26 pm

    We have bought it brand to bracelet various period. Every a person is very sweet, made very well, cannot tarnish furthermore meaningful based on which kind of any you buy furthermore whom we provide that it on.

  37. #37 by best porn videos and GIFs on 17 de julho de 2017 - 12:32 pm

    Watch live sex

  38. #38 by AlfredZob on 17 de julho de 2017 - 12:39 pm

    wh0cd932646 [url=http://lisinopril.zone/]lisinopril[/url] [url=http://buy-indocin.work/]indocin 50 mg tablets[/url] [url=http://buytadalis.reisen/]buy tadalis[/url] [url=http://buy-phenergan.reisen/]phenergan[/url] [url=http://buymedrol.reisen/]medrol[/url] [url=http://vardenafil.news/]vardenafil[/url] [url=http://prednisoloneacetate.pro/]buy prednisolone online[/url]

  39. #39 by http://www.ttsq.fr/bottomshoes.asp on 17 de julho de 2017 - 12:56 pm

    It system ended up being in that great pricing I not thought the particular excellence would be so exceptional. Its beautiful. It mom is going to like they on Xmas morning anytime she starts gift and it styles as though I devoted significantly more, and yet prices had been exclusively very good!!

  40. #40 by diabetes how to control on 17 de julho de 2017 - 1:08 pm

    I?d have to check with you here. Which is not something I usually do! I enjoy reading a post that will make people think. Also, thanks for allowing me to comment!

  41. #41 by home warranty on 17 de julho de 2017 - 1:13 pm

    This is a topic that’s near to my heart… Take care! Is it OK to post on Twitter? Keep up the terrific work!

  42. #42 by Jewelry on 17 de julho de 2017 - 1:28 pm

    You have mentioned very interesting details! ps decent web site.

(não será publicado)