<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Richard Lord &#187; Richard Lord&#8217;s Blog</title>
	<atom:link href="http://www.richardlord.net/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://www.richardlord.net</link>
	<description>Actionscript/Flex, PHP and Java developer</description>
	<lastBuildDate>Mon, 23 Jan 2012 17:07:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Game architecture is different</title>
		<link>http://www.richardlord.net/presentations/game-architecture-is-different</link>
		<comments>http://www.richardlord.net/presentations/game-architecture-is-different#comments</comments>
		<pubDate>Thu, 19 Jan 2012 14:49:03 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
		
		<guid isPermaLink="false">http://www.richardlord.net/?page_id=976</guid>
		<description><![CDATA[Presented at try{harder}, 6 October 2011 In this session, I compared building a game (Asteroids) using an entity framework (Ember) and an MVC framework (Robotlegs) and concluded that the entity framework was more suited to this task. I then attempted to explain why. I also wrote a blog post that covers much of the material [...]]]></description>
			<content:encoded><![CDATA[<p>Presented at</p>
<ul>
<li><a href="http://www.tryharder.org.uk/">try{harder}</a>, 6 October 2011</li>
</ul>
<p>In this session, I compared building a game (Asteroids) using an entity framework (<a href="https://github.com/tdavies/Ember">Ember</a>) and an MVC framework (<a href="https://github.com/robotlegs/robotlegs-framework">Robotlegs</a>) and concluded that the entity framework was more suited to this task. I then attempted to explain why.</p>

<p>I also <a href="/blog/what-is-an-entity-framework">wrote a blog post</a> that covers much of the material in this presentation.</p>

<p>These are the slides from the presentation at try{harder} on Thursday, 6 October 2011.</p>

<div class="spaced" style="text-align:center"><div id="swf4f2e70798510c">
<p><b>Flash required:</b> You need version 10 or later of the free Flash player from Adobe to use this content. To download and install the free player from Adobe's web site <a href="http://get.adobe.com/flashplayer/">click here</a>.</p>
</div>
<script type="text/javascript">
var params = {loop:"false",quality:"high",allowfullscreen:"true",allowscriptaccess:"always"};
var flashvars = {};
swfobject.embedSWF("http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=try-harder-120119082446-phpapp01&#038;stripped_title=game-architecture-is-different", "swf4f2e70798510c", "595", "380", "10.0.0", "/swf/expressInstall.swf", flashvars, params, {} );
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/presentations/game-architecture-is-different/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is an entity framework for game development?</title>
		<link>http://www.richardlord.net/blog/what-is-an-entity-framework</link>
		<comments>http://www.richardlord.net/blog/what-is-an-entity-framework#comments</comments>
		<pubDate>Thu, 19 Jan 2012 13:28:57 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=961</guid>
		<description><![CDATA[Last week I released Ash, an entity framework for Actionscript game development, and a number of people have asked me the question &#8220;What is an entity framework?&#8221;. This is my rather long answer. Entity systems are growing in popularity, with well-known examples like Unity, and lesser known frameworks like Actionscript frameworks Ember2, Xember and my [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I released <a href="https://github.com/richardlord/Ash">Ash</a>, an entity framework for Actionscript game development, and a number of people have asked me the question &#8220;What is an entity framework?&#8221;. This is my rather long answer.</p>

<p>Entity systems are growing in popularity, with well-known examples like <a href="http://unity3d.com/">Unity</a>, and lesser known frameworks like Actionscript frameworks <a href="https://github.com/tdavies/Ember2">Ember2</a>, <a href="https://github.com/alecmce/xember">Xember</a> and my own <a href="https://github.com/richardlord/Ash">Ash</a>. There&#8217;s a very good reason for this; they simplify game architecture, encourage clean separation of responsibilities in your code, and are fun to use.</p>

<p>In this post I will walk you through how an entity based architecture evolves from the old fashioned game loop. This may take a while. The examples will be in Actionscript because that happens to be what I&#8217;m using at the moment, but the architecture applies to all programming language.</p>

<p>This is based on <a href="/presentations/game-architecture-is-different">a presentation</a> I gave at <a href="http://www.tryharder.org.uk/">try{harder}</a> in 2011.</p>

<h3>The examples</h3>

<p>Throughout this post, I&#8217;ll be using a simple <a href="http://en.wikipedia.org/wiki/Asteroids_(video_game)">Asteroids</a> game as an example. I like to use Asteroids as an example because it involves simplified versions of many of the systems required in larger games &#8211; rendering, physics, ai, user control of a character, non-player characters.</p>

<h3>The game loop</h3>

<p>To understand why we use entity systems, you really need to understand the old-fashioned <a href="http://en.wikipedia.org/wiki/Game_programming#Game_structure">game loop</a>. A game loop for Asteroids might look something like this</p>

<pre class="code">function update( time:Number ):void
{
  game.update( time );
  spaceship.updateInputs( time );
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.updateAI( time );
  }
  spaceship.update( time );
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.update( time );
  }
  for each( var asteroid:Asteroid in asteroids )
  {
    asteroid.update( time );
  }
  for each( var bullet:Bullet in bullets )
  {
    bullet.update( time );
  }
  collisionManager.update( time );
  spaceship.render();
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.render();
  }
  for each( var asteroid:Asteroid in asteroids )
  {
    asteroid.render();
  }
  for each( var bullet:Bullet in bullets )
  {
    bullet.render();
  }
}</pre>

<p>This game loop is called on a regular interval, usually every 60th of a second or every 30th of a second, to update the game. The order of operations in the loop is important as we update various game objects, check for collisions between them, and then draw them all. Every frame.</p>

<p>This is a very simple game loop. It&#8217;s simple because</p>

<ol>
<li>The game is simple</li>
<li>The game has only one state</li>
</ol>

<p>In the past, I have worked on console games where the game loop, a single function, was over 3,000 lines of code. It wasn&#8217;t pretty, and it wasn&#8217;t clever. That&#8217;s the way games were built and we had to live with it.</p>

<p>Entity system architecture derives from an attempt to resolve the problems with the game loop. It addresses the game loop as the core of the game, and pre-supposes that simplifying the game loop is more important than anything else in modern game architecture. More important than separation of the view from the controller, for example.</p>

<h3>Processes</h3>

<p>The first step in this evolution is to think about objects called processes. These are objects that can be initialised, updated on a regular basis, and destroyed. The interface for a process looks something like this.</p>

<pre class="code">interface IProcess
{
  function start():Boolean;
  function update( time:Number ):void;
  function end():void;
}</pre>

<p>We can simplify our game loop if we break it into a number of processes to handle, for example, rendering, movement, collision resolution. To manage those processes we create a process manager.</p>

<pre class="code">class ProcessManager
{
  private var processes:PrioritisedList;

  public function addProcess( process:IProcess, priority:int ):void
  {
    if( process.start() )
    {
      processes.add( process, priority );
      return true;
    }
    return false;
  }

  public function update( time:Number ):void
  {
    for each( var process:IProcess in processes )
    {
      process.update( time );
    }
  }

  public function removeProcess( process:IProcess ):void
  {
    process.end();
    processes.remove( process );
  }
}</pre>

<p>This is a somewhat simplified version of a process manager. In particular, we should ensure we update the processes in the correct order (identified by the priority parameter in the add method) and we should handle the situation where a process is removed during the update loop. But you get the idea. If our game loop is broken into multiple processes, then the update method of our process manager is our new game loop and the processes become the core of the game.</p>

<h3>The render process</h3>

<p>Lets look at the render process as an example. We could just pull the render code out of the original game loop and place it in a process, giving us something like this</p>

<pre class ="code">class RenderProcess implements IProcess
{
  public function start() : Boolean
  {
    // initialise render system
    return true;
  }

  public function update( time:Number ):void
  {
    spaceship.render();
    for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
    {
      flyingSaucer.render();
    }
    for each( var asteroid:Asteroid in asteroids )
    {
      asteroid.render();
    }
    for each( var bullet:Bullet in bullets )
    {
      bullet.render();
    }
  }
  
  public function end() : void
  {
    // clean-up render system
  }
}</pre>

<h3>Using an interface</h3>

<p>But this isn&#8217;t very efficient. We still have to manually render all the different types of game object. If we have a common interface for all renderable objects, we can simplify matters a lot.</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.<IRenderable>;

  public function start() : Boolean
  {
    // initialise render system
    return true;
  }

  public function update( time:Number ):void
  {
    for each( var target:IRenderable in targets )
    {
      target.render();
    }
  }
  
  public function end() : void
  {
    // clean-up render system
  }
}</pre>

<p>Then our spaceship class might contain some code like this</p>

<pre class="code">class Spaceship implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<p>This code is based on the flash display list. If we were blitting, or using stage3d, it would be different, but the principles would be the same. We need the image to be rendered, and the position and rotation for rendering it. And the render function does the rendering.</p>

<h3>Using a base class and inheritance</h3>

<p>In fact, there&#8217;s nothing in this code that makes it unique to a spaceship. All the code could be shared by all renderable objects. The only thing that makes them different is which display object is assigned to the view property, and what the position and rotation are. So lets wrap this in a base class and use <a href="http://en.wikipedia.org/wiki/Inheritance_(computer_science)">inheritance</a>.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Spaceship extends Renderable
{
}</pre>

<p>Of course, all renderable items will extend the renderable class, so we get a simple class heirarchy like this</p>

<img src="/images/blog/entity1.png" alt="" width="439" height="234" />

<h3>The move process</h3>

<p>To understand the next step, we first need to look at another process and the class it works on. So lets try the move process, which updates the position of the objects.</p>

<pre class="code">interface IMoveable
{
  function move( time:Number );
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.<IMoveable>;
  
  public function start():Boolean
  {
    return true;
  }

  public function update( time:Number ):void
  {
    for each( var target:IMoveable in targets )
    {
      target.move( time );
    }
  }
  
  public function end():void
  {
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship extends Moveable
{
}</pre>

<h3>Multiple inheritance</h3>

<p>That&#8217;s almost good, but unfortunately we want our spaceship to be both moveable and renderable, and many modern programming languages don&#8217;t allow <a href="http://en.wikipedia.org/wiki/Multiple_inheritance">multiple inheritance</a>.</p>

<p>Even in those languages that do permit multiple inheritance, we have the problem that the position and rotation in the Moveable class should be the same as the position and rotation in the Renderable class.</p>

<p>One common solution is to use an inheritance chain, so that Moveable extends Renderable.</p>

<pre class="code">class Moveable extends Renderable implements IMoveable
{
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship extends Moveable
{
}</pre>

<p>Now the spaceship is both moveable and renderable. We can apply the same principles to the other game objects to get this class hierarchy.</p>

<img src="/images/blog/entity2.png" alt="" width="439" height="331" />

<p>We can even have static objects that just extend Renderable.</p>

<img src="/images/blog/entity2a.png" alt="" width="439" height="343" />

<h3>Moveable but not Renderable</h3>

<p>But what if we want a Moveable object that isn&#8217;t Renderable? An invisible game object, for example? Now our class hierarchy breaks down and we need an alternative implementation of the Moveable interface that doesn&#8217;t extend Renderable.<p>

<pre class="code">class InvisibleMoveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<img src="/images/blog/entity3.png" alt="" width="439" height="343" />

<p>In a simple game, this is clumsy but manageable, but in a complex game using inheritance to apply the processes to objects rapidly becomes unmanageable as you&#8217;ll soon discover items in your game that don&#8217;t fit into a simple linear inheritance tree, as with the force-field above.</p>

<h3>Favour composition over inheritance</h3>

<p>It&#8217;s long been a sound principle of object-oriented programming to <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance">favour composition over inheritance</a>. Applying that principle here can rescue us from this potential inheritance mess.</p>

<p>We&#8217;ll still need Renderable and Moveable classes, but rather than extending these classes to create the spaceship class, we will create a spaceship class that contains an instance of each of these classes.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship
{
  public var renderData:IRenderable;
  public var moveData:IMoveable;
}</pre>

<p>This way, we can combine the various behaviours in any way we like without running into inheritance problems.</p>

<img src="/images/blog/entity4.png" alt="" width="645" height="234" />

<p>The objects made by this composition, the Static Object, Spaceship, Flying Saucer, Asteroid, Bullet and Force Field, are collectively called entities.

<p>Our processes remain unchanged.</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.<IRenderable>;

  public function update(time:Number):void
  {
    for each(var target:IRenderable in targets)
    {
      target.render();
    }
  }
}</pre>

<pre class="code">interface IMoveable
{
  function move();
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.<IMoveable>;

  public function update(time:Number):void
  {
    for each(var target:IMoveable in targets)
    {
      target.move( time );
    }
  }
}</pre>

<p>But we don&#8217;t add the spaceship entity to each process, we add it&#8217;s components. So when we create the spaceship we do something like this</p>

<pre class="code">public function createSpaceship():Spaceship
{
  var spaceship:Spaceship = new Spaceship();
  ...
  renderProcess.addItem( spaceship.renderData );
  moveProcess.addItem( spaceship.moveData );
  ...
  return spaceship;
}</pre>

<p>This approach looks good. It gives us the freedom to mix and match process support between different game objects without getting into spagetti inheritance chains or repeating ourselves. But there&#8217;s one problem.</p>

<h3>What about the shared data?</h3>

<p>The position and rotation properties in the Renderable class instance need to have the same values as the position and rotation properties in the Moveable class instance, since the Move process will change the values in the Moveable instance and the Render process will use the values in the Renderable instance.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  <b>public var position:Point;</b>
  <b>public var rotation:Number;</b>

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  <b>public var position:Point;</b>
  <b>public var rotation:Number;</b>
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship
{
  public var renderData:IRenderable;
  public var moveData:IMoveable;
}</pre>

<p>To solve this, we need to ensure that both class instances reference the same instances of these properties. In Actionscript that means these properties must be objects, because objects can be passed by reference while primitives are passed by value.</p>

<p>So we introduce another set of classes, which we&#8217;ll call components. These components are just value objects that wrap properties into objects for sharing between processes.</p>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<pre class="code">class Renderable implements IRenderable
{
  public var display:DisplayComponent;
  public var position:PositionComponent;

  public function render():void
  {
    display.view.x = position.x;
    display.view.y = position.y;
    display.view.rotation = position.rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;

  public function move( time:Number ):void
  {
    position.x += velocity.velocityX * time;
    position.y += velocity.velocityY * time;
    position.rotation += velocity.angularVelocity * time;
  }
}</pre>

<p>When we create the spaceship we ensure the Moveable and Renderable instances share the same instance of the PositionComponent.</p>

<pre class="code">class Spaceship
{
  public function Spaceship()
  {
    moveData = new Moveable();
    renderData = new Renderable();
    moveData.position = new PositionComponent();
    moveData.velocity = new VelocityComponent();
    renderData.position = moveData.position;
    renderData.display = new DisplayComponent();
  }
}</pre>

<p>The processes remain unaffected by this change.</p>

<h3>A good place to pause</h3>

<p>At this point we have a neat separation of tasks. The game loop cycles through the processes, calling the update method on each one. Each process contains a collection of objects that implement the interface it operates on, and will call the appropriate method of those objects. Those objects each do a single important task on their data. Through the system of components, those objects are able to share data and thus the combination of multiple processes can produce complex updates in the game entities, while keeping each process relatively simple.</p>

<p>This architecture is similar to a number of entity systems in game development. The architecture follows good object-oriented principles and it works. But there&#8217;s more to come, starting with a moment of madness.</p>

<h3>Abandoning good object-oriented practice</h3>

<p>The current architecture uses good object-oriented practices like <a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)">encapsulation</a> and <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility</a> &#8211; the IRenderable and IMoveable implementations encapsulate the data and logic for single responsibilities in the updating of game entities every frame &#8211; and <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance">composition</a> &#8211; the Spaceship entity is created by combining implementations of the IRenderable and IMoveable interfaces. Through the system of components we ensured that, where appropriate, data is shared between the different data classes of the entities.</p>

<p>The next step in this evolution of entity systems is somewhat counter-intuitive, breaking one of the core tenets of object-oriented programming. We break the encapsulation of the data and logic in the Renderable and Moveable implementations. Specifically, we remove the logic from these classes and place it in the processes instead.</p>

<p>So this</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class Renderable implements IRenderable
{
  public var display:DisplayComponent;
  public var position:PositionComponent;

  public function render():void
  {
    display.view.x = position.x;
    display.view.y = position.y;
    display.view.rotation = position.rotation;
  }
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.<IRenderable>;

  public function update( time:Number ):void
  {
    for each( var target:IRenderable in targets )
    {
      target.render();
    }
  }
}</pre>

<p>Becomes this</p>

<pre class="code">class RenderData
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.<RenderData>;

  public function update( time:Number ):void
  {
    for each( var target:RenderData in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<p>And this</p>

<pre class="code">interface IMoveable
{
  function move( time:Number );
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;

  public function move( time:Number ):void
  {
    position.x += velocity.velocityX * time;
    position.y += velocity.velocityY * time;
    position.rotation += velocity.angularVelocity * time;
  }
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.<IMoveable>;

  public function move( time:Number ):void
  {
    for each( var target:Moveable in targets )
    {
      target.move( time );
    }
  }
}</pre>

<p>Becomes this</p>

<pre class="code">class MoveData
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.<MoveData>;

  public function move( time:Number ):void
  {
    for each( var target:MoveData in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<p>It&#8217;s not immediately clear why we&#8217;d do this, but bear with me. On the surface, we&#8217;ve removed the need for the interface, and we&#8217;ve given the process something more important to do &#8211; rather than simply delegate its work to the IRenderable or IMoveable implementations, it does the work itself.</p>

<p>The first apparent consequence of this is that all entities must use the same rendering method, since the render code is now in the RenderProcess. But that&#8217;s not actually the case. We could, for example, have two processes, RenderMovieClip and RenderBitmap for example, and they could operate on different sets of entities. So we haven&#8217;t lost any flexibility.</p>

<p>What we gain is the ability to refactor our entities significantly to produce an architecture with clearer separation and simpler configuration. The refactoring starts with a question.</p>

<h3>Do we need the data classes?</h3>

<p>Currently, our entity</p>

<pre class="code">class Spaceship
{
  public var moveData:MoveData;
  public var renderData:RenderData;
}</pre>

<p>Contains two data classes</p>

<pre class="code">class MoveData
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class RenderData
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<p>These data classes in turn contain three components</p>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<p>And the data classes are used by the two processes</p>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.<MoveData>;

  public function move( time:Number ):void
  {
    for each( var target:MoveData in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.<RenderData>;

  public function update( time:Number ):void
  {
    for each( var target:RenderData in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<p>But the entity shouldn&#8217;t care about the data classes. The components collectively contain the state of the entity. The data classes exist for the convenience of the processes. So we refactor the code so the spaceship entity contains the components rather than the data classes.</p>

<pre class="code">class Spaceship
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
  public var display:DisplayComponent;
}</pre>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<p>By removing the data classes, and using the constituent components instead to define the spaceship, we have removed any need for the spaceship entity to know what processes may act on it. The spaceship now contains the components that define its state. Any requirement to combine these components into other data classes for the processes is some other class&#8217;s responsibility.</p>

<h3>Systems and Nodes</h3>

<p>Some core code within the entity framework (which we&#8217;ll get to in a minute) will dynamically create these data objects as they are required by the processes. In this reduced context, the data classes will be mere nodes in the collections (arrays, linked-lists, or otherwise, depending on the implementation) used by the processes. So to clarify this we&#8217;ll rename them as nodes.</p>

<pre class="code">class MoveNode
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class RenderNode
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<p>The processes are unchanged, but in keeping with the more common naming I&#8217;ll also change their name and call them systems.</p>

<pre class="code">class MoveSystem implements ISystem
{
  private var targets:Vector.<MoveNode>;

  public function move( time:Number ):void
  {
    for each( var target:MoveNode in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<pre class="code">class RenderSystem implements ISystem
{
  private var targets:Vector.<RenderNode>;

  public function update( time:Number ):void
  {
    for each( var target:RenderNode in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<pre class="code">interface ISystem
{
  function update( time:Number ):void;
}</pre>

<h3>And what is an entity?</h3>

<p>One last change &#8211; there&#8217;s nothing special about the Spaceship class. It&#8217;s just a container for components. So we&#8217;ll just call it Entity and give it a collection of components. We&#8217;ll access those components based on their class type.</p>

<pre class="code">class Entity
{
  private var components : Dictionary;
  
  public function add( component:Object ):void
  {
    var componentClass : Class = component.constructor;
    components[ componentClass ] = component'
  }
  
  public function remove( componentClass:Class ):void
  {
    delete components[ componentClass ];
  }
  
  public function get( componentClass:Class ):Object
  {
    return components[ componentClass ];
  }
}</pre>

<p>So we&#8217;ll create our spaceship like this</p>

<pre class="code">public function createSpaceship():void
{
  var spaceship:Entity = new Entity();
  var position:PositionComponent = new PositionComponent();
  position.x = Stage.stageWidth / 2;
  position.y = Stage.stageHeight / 2;
  position.rotation = 0;
  spaceship.add( position );
  var display:DisplayComponent = new DisplayComponent();
  display.view = new SpaceshipImage();
  spaceship.add( display );
  game.add( spaceship );
}</pre>

<h3>The core Game class</h3>

<p>We mustn&#8217;t forget the system manager, formerly called the process manager.</p>

<pre class="code">class SystemManager
{
  private var systems:PrioritisedList;

  public function addSystem( system:ISystem, priority:int ):void
  {
    systems.add( system, priority );
    system.start();
  }

  public function update( time:Number ):void
  {
    for each( var system:ISystem in systemes )
    {
      system.update( time );
    }
  }

  public function removeSystem( system:ISystem ):void
  {
    system.end();
    systems.remove( system );
  }
}</pre>

<p>This will be enhanced and will sit at the heart of our entity framework. We&#8217;ll add to it the functionality mentioned above to dynamically create nodes for the systems.</p>

<p>The entities only care about components, and the systems only care about nodes. So to complete the entity framework, we need code to watch the entities and, as they change, add and remove their components to the node collections used by the systems. Because this is the one bit of code that knows about both entities and systems, we might consider it central to the game. In Ash, I call this the Game class, and it is an enhanced version of the system manager.</p>

<p>Every entity and every system is added to and removed from the Game class when you start using it and stop using it. The Game class keeps track of the components on the entities and creates and destroys nodes as necessary, adding those nodes to the node collections. The Game class also provides a way for the systems to get the collections they require.</p>

<pre class="code">public class Game
{
  private var entities:EntityList;
  private var systems:SystemList;
  private var nodeLists:Dictionary;

  public function addEntity( entity:Entity ):void
  {
    entities.add( entity );
    // create nodes from this entity's components and add them to node lists
    // also watch for later addition and removal of components from the entity so
    // you can adjust its derived nodes accordingly
  }

  public function removeEntity( entity:Entity ):void
  {
    // destroy nodes containing this entity's components
    // and remove them from the node lists
    entities.remove( entity );
  }

  public function addSystem( system:System, priority:int ):void
  {
    systems.add( system, priority );
    system.start();
  }

  public function removeSystem( system:System ):void
  {
    system.end();
    systems.remove( system );
  }

  public function getNodeList( nodeClass:Class ):NodeList
  {
    var nodes:NodeList = new NodeList();
    nodeLists[ nodeClass ] = nodes;
    // create the nodes from the current set of entities
    // and populate the node list
    return nodes;
  }

  public function update( time:Number ):void
  {
    for each( var system:ISystem in systemes )
    {
      system.update( time );
    }
  }
}</pre>

<img src="/images/blog/entity5.png" alt="" width="459" height="251" />

<p>To see one implementation of this architecture, <a href="https://github.com/richardlord/Ash">checkout the source code for Ash</a>, and see <a href="https://github.com/richardlord/Ash/tree/master/examples/no-dependencies">the example Asteroids implementation there</a> too.</p>

<h3>Conclusion</h3>

<p>So, to summarise, entity systems originate from a desire to simplify the game loop. From that comes an architecture of entities, which represent the state of the game, and systems, which operate on the state of the game. Systems are updated every frame &#8211; this is the game loop. Entities are made up of components, and systems operate on the entities that have the components they are interested in. The game monitors the systems and the entities and ensures each system has access to a collection of all the entities that have the appropriate components.</p>

<p>However, systems don&#8217;t generally care about the entity as a whole, just the specific components they require. So, to optimise the architecture and provide additional clarity, the systems operate on statically typed node objects that contain the appropriate components, where those components all belong to the same entity.</p>

<p>An <b>entity framework</b> provides the basic scaffolding and core management for this architecture, without providing any actual entity or system classes. You create your game by creating the appropriate entities and systems.</p>

<p>An <b>entity based game engine</b> will provide many standard systems and entities on top of the basic framework.</p>

<p>Three entity frameworks for Actionscript are my own <a href="https://github.com/richardlord/Ash">Ash</a>, <a href="https://github.com/tdavies/Ember2">Ember2</a> by <a href="http://www.tomseysdavies.com/">Tom Davies</a> and <a href="https://github.com/alecmce/xember">Xember</a> by <a href="http://alecmce.com/">Alec McEachran</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/what-is-an-entity-framework/feed</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Mobile Apps</title>
		<link>http://www.richardlord.net/apps</link>
		<comments>http://www.richardlord.net/apps#comments</comments>
		<pubDate>Sat, 14 Jan 2012 19:31:58 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
		
		<guid isPermaLink="false">http://www.richardlord.net/?page_id=925</guid>
		<description><![CDATA[Stick Sports I am CTO at Stick Sports where I am involved in the development of these apps. Stick Cricket Super Sixes Platform: iOS Price: $0.99 A revolutionary new batting game! Instead of facing mere mortals, your opponent is the state-of-the-art Bowlomatic 3000: a sadistic bowling machine that is hell bent on wiping you out. [...]]]></description>
			<content:encoded><![CDATA[<table class="layout">
<tr><td colspan="3"><h2>Stick Sports</h2>

<p>I am CTO at <a href="http://www.sticksports.com">Stick Sports</a> where I am involved in the development of these apps.</p>

<h3>Stick Cricket Super Sixes</h3></td></tr>

<tr><td><p><img src="/images/sticksports/supersixes.gif" width="72" height="72" style="padding:0 20px 10px 0" /></p></td>

<td><p>Platform: iOS<br />
Price: $0.99</p>
<p>A revolutionary new batting game! Instead of facing mere mortals, your opponent is the state-of-the-art Bowlomatic 3000: a sadistic bowling machine that is hell bent on wiping you out.</p></td>

<td align="right"><p><a href="http://itunes.apple.com/app/id483135193?ls=1&#038;mt=8"><img src="/images/stores/AppleAppStore.gif" width="161" height="54" style="padding:0 20px 10px 0" /></a></p></td></tr>

<tr><td colspan="3"><h3>Stick Cricket</h3></td></tr>

<tr><td><p><img src="/images/sticksports/stickcricketicon.gif" width="72" height="72" style="padding:0 20px 10px 0" /></p></td>

<td><p>Platform: iOS &#038; Android<br />
Price: Free</p>
<p>Pad up and bat for your country in the world’s most popular cricket game! Stick Cricket® sees you face up to the best bowlers from around the globe. Can you smash them out of the park?</p></td>

<td align="right"><p><a href="http://itunes.apple.com/app/id406781620?ls=1&#038;mt=8"><img src="/images/stores/AppleAppStore.gif" width="161" height="54" style="padding:0 20px 10px 0" /></a><br /><a href="http://market.android.com/details?id=com.sticksports.stickcricket"><img src="/images/stores/AndroidMarket.gif" width="156" height="60" style="padding:0 20px 10px 0" /></a></p></td></tr>

<tr><td colspan="3"><h2>Personal</h2>

<p>A little experimental project I made in my spare time.</p>

<h3>Particle Soup</h3></td></tr>

<tr><td><p><img src="/images/particlesoup/icon.png" width="72" height="72" style="padding:0 20px 10px 0" /></p></td>

<td><p>Platform: Blackberry Playbook<br />
Price: $0.99</p>
<p>An interactive particle visualizer. Thousands of little points of light flying around the screen, all under your control.</td>

<td align="right"><p><a href="http://appworld.blackberry.com/webstore/content/24571"><img src="/images/stores/BBAppWorld.png" width="176" height="48" style="padding:0 20px 10px 0" /></a></p></td></tr>

</table>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/apps/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ash &#8211; a new entity framework for Actionscript games</title>
		<link>http://www.richardlord.net/blog/introducing-ash</link>
		<comments>http://www.richardlord.net/blog/introducing-ash#comments</comments>
		<pubDate>Wed, 11 Jan 2012 20:31:00 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=910</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of stuff with entity systems recently. At try{harder} I gave a presentation about entity systems, which was warmly received and led to many interesting conversations. I also created example projects with the Ember and Xember frameworks and had fruitful conversations with Tom and Alec about their projects, even contributing a [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of stuff with entity systems recently. At <a href="http://www.tryharder.org.uk/">try{harder}</a> I gave <a href="/presentations/game-architecture-is-different">a presentation about entity systems</a>, which was warmly received and led to many interesting conversations. I also created example projects with the <a href="https://github.com/tdavies/Ember">Ember</a> and <a href="https://github.com/alecmce/xember">Xember</a> frameworks and had fruitful conversations with <a href="http://www.tomseysdavies.com/">Tom</a> and <a href="http://alecmce.com/">Alec</a> about their projects, even contributing a few minor bits of code to them.</p>

<p>But now I&#8217;ve written an entity framework of my own. It&#8217;s called <a href="https://github.com/richardlord/Ash">Ash</a> and you can <a href="https://github.com/richardlord/Ash">find it on Github</a>.</p>

<p>A few of the features of Ash are</p>

<ul>
<li>Uses the most performant linked list format <a href="/blog/linked-list-performance-test">from my tests here</a>.</li>
<li>Optional, but not required, integration with <a href="https://github.com/tschneidereit/SwiftSuspenders">SwiftSuspenders</a> and <a href="http://www.robotlegs.org/">Robotlegs</a>.</li>
<li>The process manager is a core part of the framework.</li>
</ul>

<p>At this stage, I don&#8217;t see this as a major open-source project, like <a href="http://flintparticles.org">Flint</a>, but rather a chance to explore and explain what I think is important in an entity system, by building one. I plan to build a game with Ash, so more features will come as I need them, and more posts on this blog. Meanwhile, if you&#8217;re building an actionscript game why not <a href="https://github.com/richardlord/Ash">take Ash for a spin</a>. And for comparison, check out <a href="https://github.com/tdavies/Ember2">Ember2</a> and <a href="https://github.com/alecmce/xember">Xember</a>.</p>

<p><a href="http://www.tomseysdavies.com/">Tom</a> in particular has done a lot of work to develop the ideas behind entity systems on the Flash platform. Without that work to feed my ideas machine I wouldn&#8217;t have built Ash, so thank you Tom.</p>

<p>And thank you to <a href="http://www.tillschneidereit.de/">Till</a> who added a feature to <a href="https://github.com/tschneidereit/SwiftSuspenders">SwiftSuspenders</a> to enable me to inject linked lists based on their content type.</p>

<h3>Update</h3>

<p>Here is a <a href="http://www.richardlord.net/blog/introducing-ash">follow-up post explaining entity frameworks</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/introducing-ash/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>So what are Adobe up to with Flash?</title>
		<link>http://www.richardlord.net/blog/so-what-are-adobe-up-to-with-flash</link>
		<comments>http://www.richardlord.net/blog/so-what-are-adobe-up-to-with-flash#comments</comments>
		<pubDate>Mon, 14 Nov 2011 15:32:08 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Air]]></category>
		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=883</guid>
		<description><![CDATA[It has been an interesting week in the Flash world. Various announcements and clarifications about the future of Flash, which seem to add up to Adobe will stop development of the Flash mobile browser plug-in, but mobile operating system and hardware developers are free to continue developing on top of Adobe&#8217;s existing source code if [...]]]></description>
			<content:encoded><![CDATA[<p>It has been an interesting week in the Flash world. Various <a href="http://blogs.adobe.com/conversations/2011/11/flash-focus.html">announcements</a> and <a href="http://www.mikechambers.com/blog/2011/11/11/clarifications-on-flash-player-for-mobile-browsers-the-flash-platform-and-the-future-of-flash/">clarifications</a> about the future of Flash, which seem to add up to</p>

<ol>
<li>Adobe will stop development of the Flash mobile browser plug-in, but mobile operating system and hardware developers are free to continue developing on top of Adobe&#8217;s existing source code if they wish to license it from Adobe.</li>
<li>The Flex framework will be <a href="http://blogs.adobe.com/flex/2011/11/your-questions-about-flex.html">freed from Adobe&#8217;s control</a>, and will become more open under the guidance of an as yet undecided open source foundation which will include Adobe contributors and the <a href="http://www.spoon.as/">Spoon project</a>.</li>
<li>Development of the Flash plug-in for desktop browsers continues as normal.</li>
<li>Development of Adobe Air, including publishing for mobile apps, continues as normal.</li>
<li>There&#8217;s renewed emphasis on the Flash platform as a platform for game development.</li>
<li>There has been some movement of jobs on the Flash CS Professional team, but <a href="http://www.mikechambers.com/blog/2011/11/10/flash-professional-and-the-future/">the team still exists and the next version of the product is in development</a>.</li>
</ol>

<p>There&#8217;s been a lot of hand-wringing as Flash developers struggle to figure out what this means for them. I don&#8217;t propose to resolve that here &#8211; what this means for you depends on both your skill-set and your job. But I guess if I had one bit of advice it would be, if Actionscript is the only development language you know it&#8217;s well past time for you to diversify your skills. Learning a second programming language makes you a better programmer in general, and learning a third, fourth, etc becomes easier with each language. I have lost track of the number of programming languages I have learnt, but each one has made me a better programmer.</p>

<p>What follows is merely my personal take on the situation. Make of it what you will. I&#8217;ll start with an important question.</p>

<h3>Why did Adobe buy Macromedia?</h3>

<p>For some time I&#8217;ve been meaning to write a blog post about why Adobe bought Macromedia (it only happened six years ago <img src='http://www.richardlord.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ). I don&#8217;t actually know the answer, but I have my suspicions and they&#8217;re different from those I hear voiced elsewhere.</p>

<p>I suspect it is true that Adobe bought Macromedia to get their hands on Flash. This is a common assumption, and I see no reason for it to be wrong. There was nothing else in the Macromedia toolkit that mattered much to Adobe, except perhaps Dreamweaver which is now taking on renewed significance.</p>

<p>I suspect that the Flash platform tools (Flash Builder and Flash CS Professional) were not the target. These tools are for developers, unlike Adobe&#8217;s other tools, and are built atop a free plug-in which Adobe also have to develop and maintain. I also suspect the Flash platform generates far smaller profit margins than Photoshop, Illustrator and InDesign.</p>

<p>One reasonable suspicion is that Adobe bought Macromedia simply so that someone else didn&#8217;t. They didn&#8217;t want Macromedia&#8217;s design tools in the hands of a company with deeper pockets. This may well be true.</p>

<p>But my suspicion is, back when Adobe bought Macromedia, they looked at the application landscape and concluded, as many others did, that the future of applications was as web-based services. They needed a platform on which to develop web-based versions of Photoshop, Illustrator and InDesign and Flash was an obvious choice for that platform. By buying Macromedia, Adobe gained control of Flash&#8217;s development, and hence of the platform they proposed to use for web-based applications. This enabled them to move development of the Flash player in directions that they needed.</p>

<p>Unfortunately for Adobe, while they were following this strategy the world moved in a different direction. Six years later, the present is not web-based applications, it&#8217;s small, cheap, sometimes throwaway, native applications that use the web as a data source and nothing more.</p>

<p>Adobe were not the only ones caught out by this &#8211; Apple themselves, when they launched the iPhone, thought most phone apps would be web apps. They were just more agile in moving with the times and switching emphasis to native apps.</p>

<p>Adobe are making their move now. In fact, they have been for the last couple of years, but it&#8217;s only now that killing bits of the Flash platform (specifically the mobile browser plug-in) has become part of that move.</p>

<h3>What now?</h3>

<p>So now Adobe find themselves with a profitable, but not massively so, set of products in the Flash platform that don&#8217;t fit neatly within their product portfolio. I wonder if Adobe now wish they hadn&#8217;t bought Macromedia, but that&#8217;s all in the past. They need to make the best of the current situation.</p>

<p>Killing Flash on the desktop would be madness, although I suspect maintaining Flash&#8217;s 98% desktop penetration is now less important, and it&#8217;s a decline in this figure that will be the first indication of Flash&#8217;s true decline. But, while there&#8217;s money to be made and a reasonable profit margin available, the Flash plug-in and the tools surrounding it will continue.</p>

<p>On top of that, the one thing the development world needs is a good cross-platform mobile app development platform. Unity3d provides a good tool for cross-platform game development, but the best cross-platform tools for general app development are mediocre at best. Adobe Air is currently one of those mediocre platforms, and with sufficient work it could become a good platform for mobile development. I hope it does. It has a lot of merit.</p>

<p>It sounds like Adobe may have identified this need and the potential of Air, so it&#8217;s just possible that Actionscript developers have a bright future ahead of them. Time will tell.</p>

<p>Meanwhile, if you&#8217;re an Actionscript developer it&#8217;s high time to diversify in whatever direction makes most sense to you. Javascript/Unity3d/Objective-C/Ruby&#8230; there&#8217;s lots of interesting stuff out there. Go and have fun. But you don&#8217;t have to abandon Flash and Actionscript just yet &#8211; Adobe haven&#8217;t.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/so-what-are-adobe-up-to-with-flash/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Four ways to link a list (a performance test on linked list architectures)</title>
		<link>http://www.richardlord.net/blog/linked-list-performance-test</link>
		<comments>http://www.richardlord.net/blog/linked-list-performance-test#comments</comments>
		<pubDate>Tue, 25 Oct 2011 19:26:47 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ember]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Xember]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=868</guid>
		<description><![CDATA[In looking at entity systems for Flash games, and particularly the projects Ember and Xember, I was wondering what is the most efficient architecture for the linked lists used by these systems. So I ran some tests. The code for these tests is all available on Github. The lists in these frameworks are used to [...]]]></description>
			<content:encoded><![CDATA[<p>In looking at entity systems for Flash games, and particularly the projects <a href="https://github.com/tdavies/Ember">Ember</a> and <a href="https://github.com/alecmce/xember">Xember</a>, I was wondering what is the most efficient architecture for the linked lists used by these systems. So I ran some tests.</p>

<p><a href="https://github.com/richardlord/Four-ways-to-link-a-list">The code for these tests is all available on Github.</a></p>

<p>The lists in these frameworks are used to manage the component sets for the systems that run the game. These lists need to provide three functions &#8211; add an item, remove an item, and loop through all the items, and they need to do this as efficiently as possible.</p>

<p>So I created four different architectures for linked lists and ran a few performance tests.</p>

<h3>1. The list node contains the data (NodeContainsDataList).</h3>

<p><a href="https://github.com/richardlord/Four-ways-to-link-a-list/blob/master/src/lists/NodeContainsDataList.as">(source code)</a></p>

<p>This is a classic linked list architecture where the nodes in the list have a data property which contains the data to be added to the list. Because removing data from the list requires finding the node that contains the data, I added a dictionary for quickly finding the node that contains a specific piece of data.</p>

<p>I expect adding an item to the list to be slow because it involves creating a node object. Reading the data from the node requires casting from a dynamic property to the specific data type, which may slow it down a little. Removing data from the list also requires removing data from the dictionary, which will slow it down somewhat.</p>

<h3>2. The data extends the list node class (DataExtendsNodeList).</h3>

<p><a href="https://github.com/richardlord/Four-ways-to-link-a-list/blob/master/src/lists/DataExtendsNodeList.as">(source code)</a></p>

<p>In this scenario the data class to be stored in the list extends a list node class. So this architecture uses inheritance rather than composition to create the list node that contains the data. This is the mechanism used in Ember.</p>

<p>Adding and removing data from the list should be quick because the data is the node. There is no casting and no object creation required. However, looping through the list members requires an upcast from the base list node type to the specific data type which is likely to slow it down.</p>

<h3>3. The data is the list node (DataIsNodeList).</h3>

<p><a href="https://github.com/richardlord/Four-ways-to-link-a-list/blob/master/src/lists/DataIsNodeList.as">(source code)</a></p>

<p>In this scenario the data node is the list node. The data node has two properties, next and previous, which link it in to the list. This is the mechanism used in Xember.</p>

<p>Adding and removing items may be slowed a little by the dynamic casts required, but looping should be very fast since the data type is explicitly known at all times and no type-casting is required.</p>

<h3>4. There is no list node (NoNodeList).</h3>

<p><a href="https://github.com/richardlord/Four-ways-to-link-a-list/blob/master/src/lists/NoNodeList.as">(source code)</a></p>

<p>Rather than using list nodes, this list maintains two dictionaries for mapping between each data item and the next and previous data items in the list.</p>

<p>This is an attempt to find a solution that had the simplicity of the NodeContainsDataList class, where the data requires no modification for storage within the list, but without the penalty of creating nodes for each data item. It does require the use of dictionary objects, which are not particularly fast, so it&#8217;s interesting to see if it&#8217;s faster or slower than the other scenarios.</p>

<h2>The results</h2>

<p>I ran the tests over Flash&#8217;s native Array and Vector classes too. The tests add 50,000 items to a list, remove 50,000 items from a list, and loop through 500,000 items in a list. I ran the tests four times and display the average of the results below. The tests were run using the release version of Flash Player 11.0.1.152 on a MacBook Pro. The times are measured in milliseconds.</p>

<table>
<tr><td>Collection</td><td>Add</td><td>Remove</td><td>Loop</td></tr>
<tr><td>Array</td><td class="right">3</td><td class="right">11824</td><td class="right">13</td></tr>
<tr><td>Vector</td><td class="right">4</td><td class="right">11448</td><td class="right">14</td></tr>
<tr><td>NodeContainsDataList</td><td class="right">31</td><td class="right">34</td><td class="right">9</td></tr>
<tr><td>DataExtendsNodeList</td><td class="right">2</td><td class="right">5</td><td class="right">23</td></tr>
<tr><td>DataIsNodeList</td><td class="right">3</td><td class="right">9</td><td class="right">11</td></tr>
<tr><td>NoNodeList</td><td class="right">22</td><td class="right">53</td><td class="right">56</td></tr>
</table>

<p>(N.B. Linked list performance is disproportionately affected by using the debug version of the Flash Player. If you <a href="https://github.com/richardlord/Four-ways-to-link-a-list/tree/master/bin">run the tests yourself</a> use the release version of the player.)</p>

<p>As expected, the fastest architecture overall is the one where the data is the node (DataIsNodeList). However, lets consider the scenario for an entity &#038; component based game architecture.</p>

<p>Given the size of the data sets, the only overwhelmingly slow results are for removing items from the Array and Vector collections. If we reject these, all four linked list architectures have reasonable speeds.</p>

<p>For an entity system, the most critical aspect of the collection architecture is the loop speed. In this context, only two of the loop architectures stand out as significantly slower, DataExtendsNodeList and NoNodeList. Rejecting these leaves two architectures to choose from.</p>

<p>Of these, NodeContainsDataList is, surprisingly, a little faster on the loop test despite the dynamic cast required to read the data. However, I&#8217;m not convinced that the difference is significant relative to other differences.</p>

<p>In the add and removal tests, DataIsNodeList is significantly faster for reasons outlined above. But add and remove are far less critical to the game engine than looping through the list items.</p>

<p>There is one other significant difference between these two list architectures. DataIsNodeList requires the user of the game engine to explicitly add the next and previous properties to the data class, while NodeContainsDataList requires no modification to the data class. This ease of use may outweigh the speed difference, particularly in a framework designed for general use.</p>

<p>What do you think? Is there another, potentially better, architecture that I&#8217;ve missed?</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/linked-list-performance-test/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Flint Particles 4.0.0 released</title>
		<link>http://www.richardlord.net/blog/flint-particles-4-0-0-released</link>
		<comments>http://www.richardlord.net/blog/flint-particles-4-0-0-released#comments</comments>
		<pubDate>Tue, 18 Oct 2011 06:21:59 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Flint]]></category>
		<category><![CDATA[Particles]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=860</guid>
		<description><![CDATA[<p>Last week I released version 4.0.0 of <a href="http://flintparticles.org/">Flint Particles</a>. This version adds support for the latest versions of <a href="http://away3d.com/">Away3d</a>, <a href="http://www.flare3d.com/">Flare3d</a> and <a href="http://alternativaplatform.com/">Alternativa3d</a>. Specifically, the supported versions of these three libraries themselves support the new Stage3D in Flash 11. This is the first step in Flint supporting Stage3D. We hope to add further support later, through 2d libraries like <a href="http://www.starling-framework.org/">Starling</a> and <a href="https://github.com/nulldesign/nd2d">ND2D</a>, and possibly using Stage3D within Flint's own renderers.</p>

<p><a href="http://flintparticles.org/blog/version-4-0-0-released">The release notes</a> for this version are on <a href="http://flintparticles.org/blog/version-4-0-0-released">the Flint Particles website</a>, along with information where to <a href="http://flintparticles.org/source-code">download the new version</a>...</p>]]></description>
			<content:encoded><![CDATA[<p>Last week I released version 4.0.0 of <a href="http://flintparticles.org/">Flint Particles</a>. This version adds support for the latest versions of <a href="http://away3d.com/">Away3d</a>, <a href="http://www.flare3d.com/">Flare3d</a> and <a href="http://alternativaplatform.com/">Alternativa3d</a>. Specifically, the supported versions of these three libraries themselves support the new Stage3D in Flash 11. This is the first step in Flint supporting Stage3D. We hope to add further support later, through 2d libraries like <a href="http://www.starling-framework.org/">Starling</a> and <a href="https://github.com/nulldesign/nd2d">ND2D</a>, and possibly using Stage3D within Flint&#8217;s own renderers.</p>

<p><a href="http://flintparticles.org/blog/version-4-0-0-released">The release notes</a> for this version are on <a href="http://flintparticles.org/blog/version-4-0-0-released">the Flint Particles website</a>, along with information where to <a href="http://flintparticles.org/source-code">download the new version</a>. Here&#8217;s a little demo using Away3d 4 and Stage3D.</p>

<div class="spaced"><div id="swf4f2e7079a4bec">
<p><b>Flash required:</b> You need version 10 or later of the free Flash player from Adobe to use this content. To download and install the free player from Adobe's web site <a href="http://get.adobe.com/flashplayer/">click here</a>.</p>
</div>
<script type="text/javascript">
var params = {loop:"false",quality:"high",allowfullscreen:"true",wmode:"direct"};
var flashvars = {};
swfobject.embedSWF("http://flintparticles.org/source/examples3D/Planets/Away3d4/Planets.swf", "swf4f2e7079a4bec", "500", "500", "11.0.0", "/swf/expressInstall.swf", flashvars, params, {} );
</script></div>

<p><a href="http://flintparticles.org/examples/planets">View source code</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/flint-particles-4-0-0-released/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Bookshelf</title>
		<link>http://www.richardlord.net/my-bookshelf</link>
		<comments>http://www.richardlord.net/my-bookshelf#comments</comments>
		<pubDate>Mon, 23 May 2011 20:27:08 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
		
		<guid isPermaLink="false">http://www.richardlord.net/?page_id=843</guid>
		<description><![CDATA[I like books and read a lot of them. Many of them are about programming, and a few are about design. Here are some of the better ones.&#160; Shelfari: Book reviews on your book blogA Smile in the Mind by Beryl McAlhoneTricks of the 3D&#8230; by Andre LaMotheGame Coding Complete by Mike McShaffry]]></description>
			<content:encoded><![CDATA[<p>I like books and read a lot of them. Many of them are about programming, and a few are about design. Here are some of the better ones.<br />&nbsp;</p>
<div id="ShelfariWidget174098"><a href='http://www.shelfari.com/'>Shelfari: Book reviews on your book blog</a><script src="http://www.shelfari.com/ws/174098/widget.js?r=65114" type="text/javascript" language="javascript"></script></div><noscript><ul><li><a href="http://www.shelfari.com/books/631580/A-Smile-in-the-Mind?widgetId=174098">A Smile in the Mind</a> by Beryl McAlhone</li><li><a href="http://www.shelfari.com/books/8175311/Tricks-of-the-3D-Game-Programming-Gurus-The-Next-Generation?widgetId=174098">Tricks of the 3D&#8230;</a> by Andre LaMothe</li><li><a href="http://www.shelfari.com/books/444292/Game-Coding-Complete?widgetId=174098">Game Coding Complete</a> by Mike McShaffry</li></ul></noscript>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/my-bookshelf/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ant scripts for Blackberry Playbook development</title>
		<link>http://www.richardlord.net/blog/ant-scripts-for-blackberry-playbook-development</link>
		<comments>http://www.richardlord.net/blog/ant-scripts-for-blackberry-playbook-development#comments</comments>
		<pubDate>Thu, 12 May 2011 16:14:01 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Ant]]></category>
		<category><![CDATA[Playbook]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=836</guid>
		<description><![CDATA[The early days of Playbook development have been quite painful &#8211; for some more than others. I remember fondly the struggle to get live debugging working, along with many other adventures. But I use FDT as my tool of choice for Actionscript development, and I always create Ant scripts for my build process. That means, [...]]]></description>
			<content:encoded><![CDATA[<p>The early days of <a href="http://us.blackberry.com/developers/tablet/adobe.jsp">Playbook development</a> have been quite painful &#8211; for some more than others. I remember fondly the struggle to get live debugging working, along with many other adventures. But I use <a href="http://www.fdt.powerflasher.com/">FDT</a> as my tool of choice for Actionscript development, and I always create <a href="http://ant.apache.org/">Ant</a> scripts for my build process.</p>

<p>That means, by the time I finished building <a href="/particle-soup">Particle Soup</a> I had a nice collection of Ant scripts for Playbook development. You can <a href="https://github.com/richardlord/playbook-ant-tasks">find them on Github</a>. Please feel free to use them in your own Playbook development.</p>

<p>The main purpose of the scripts is to enable one click building, packaging, signing and deployment of the app. There are three key tasks.</p>

<dl>
<dt>build.deploy.debug</dt>
<dd>Builds a debug version of the app, packages it for debugging, and deploys it to the Playbook. The app will attempt to <a href="http://supportforums.blackberry.com/t5/Tablet-OS-SDK-for-Adobe-AIR/Compile-and-Debug-without-Flash-Builder-Using-a-Command-Line/ta-p/628675">connect to a debugger</a> on your development computer. If using a Playbook (rather than the simulator) this task requires a valid <a href="http://docs.blackberry.com/en/developers/deliverables/23959/Create_a_debug_token_cmd_line_1585437_11.jsp">debug token</a> on the Playbook.</dd>
<dt>build.deploy.dev</dt>
<dd>Builds a release version of the app, packages it in a bar, and deploys it to the Playbook. If using a Playbook (rather than the simulator) this task requires a valid <a href="http://docs.blackberry.com/en/developers/deliverables/23959/Create_a_debug_token_cmd_line_1585437_11.jsp">debug token</a> on the Playbook.</dd>
<dt>build.deploy.signed</dt>
<dd>Builds a release version of the app, packages it in a bar, <a href="http://docs.blackberry.com/en/developers/deliverables/23959/Signing_your_application_1422721_11.jsp">signs it for release</a>, and deploys it to the Playbook. No debug token is required but you must alter the version number or build number with every build or the signing will fail. The resulting .bar file is ready for submission to the App World.</dd>
</dl>

<p>Each script is broken into discrete tasks so the individual tasks can be run independently if you wish. And there are also tasks to uninstall the app.</p>

<p>The scripts make some assumptions about the structure of your project, particularly where you place the xml config and image files for your project, so I&#8217;ve bundled the scripts into a little Playbook project to demonstrate this. You can grab the whole lot <a href="https://github.com/richardlord/playbook-ant-tasks">from Github</a> or <a href="https://github.com/downloads/richardlord/playbook-ant-tasks/PlaybookExample.1.1.zip">download it here</a>.</p>

<p>Before running the scripts, edit the settings in the build.config file to match your development environment. Have fun and happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/ant-scripts-for-blackberry-playbook-development/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>My first Playbook app</title>
		<link>http://www.richardlord.net/blog/my-first-playbook-app</link>
		<comments>http://www.richardlord.net/blog/my-first-playbook-app#comments</comments>
		<pubDate>Wed, 11 May 2011 17:59:37 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Flint]]></category>
		<category><![CDATA[Particle Soup]]></category>
		<category><![CDATA[Particles]]></category>
		<category><![CDATA[Playbook]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=826</guid>
		<description><![CDATA[Like many Flash developers, I jumped at the chance to create an app for the Blackberry Playbook. With the Playbook we have a platform where Flash is a first class citizen. Indeed, for some time Flash (more specifically, Air 2.5) was the only development platform available for the Playbook. On top of that, Research in [...]]]></description>
			<content:encoded><![CDATA[<p>Like many Flash developers, I jumped at the chance to create an app for the <a href="http://us.blackberry.com/developers/tablet/">Blackberry Playbook</a>. With the Playbook we have a platform where Flash is a first class citizen. Indeed, for some time Flash (more specifically, Air 2.5) was the only development platform available for the Playbook.</p>

<p>On top of that, Research in Motion offered free Playbooks to any developer who had an app accepted into the App World store before the launch of the device &#8211; who could resist. So I built an app.</p>

<p>I was in the fortunate position of having a lot of existing code I could use, and I decided to create a particle effects toy using <a href="http://flintparticles.org/">Flint</a>. The result is <a href="/particle-soup">Particle Soup</a>. It&#8217;s small, self contained and a great showcase for Flint. I hope you <a href="/particle-soup">enjoy the results</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/my-first-playbook-app/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

