<?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>Sgt. Conker &#187; A.I</title>
	<atom:link href="http://www.sgtconker.com/category/xna/ai/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Thu, 09 Sep 2010 00:28:52 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Article : Spatial hashing implementation for fast 2D collisions</title>
		<link>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/</link>
		<comments>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:19:06 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[A.I]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Collision]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[SPATIAL HASHING]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=21</guid>
		<description><![CDATA[This article describes how to use a spatial hashing implementation to speed up collisions in your games.]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.conkerjo.com/">Conkerjo</a></h4>
<p>This article describes how to use a spatial hashing implementation to speed up collisions in your games.</p>
<p>This is a sample prototype I wrote to fix a performance limitation with collision checking in my game.<br />
So what is spatial hashing? Here is a good 1 liner I will borrow from the source material i used.</p>
<p><span id="more-21"></span></p>
<p>“Spatial hashing is a process by which a 3D or 2D domain space is projected into a 1D hash table.” <a href="http://www.cs.ucf.edu/~jmesit/publications/scsc%202005.pdf" target="_blank">Optimization of Large-Scale, Real-Time Simulations by Spatial Hashing</a></p>
<p>So why do we need it?</p>
<p>Well, for me it was a problem in my collision code and my A.I code which was trying to find nearby objects to check collisions for. Due to my brute force nature if I had 10 monsters in the world there would be 10*10 = 100 collision checks in every update. Now ramp the number up to 100 to be a bit excessive and we end up with 100*100=10,000 collision checks. This makes the cpu cry like a little baby as I’m sure you can imagine.<br />
To rectify this we need to reduce the amount of collision checks we need to do in the first place.<br />
This is where spatial hashing comes in handy.</p>
<p>Imagine the game world in a flat 2d grid. 100 by 100 pixels and each cell was 25 by 25 pixels. Now number the cells from left to right, top to bottom 0 onwards.<br />
You will end up with something like this. The orange circles are the game objects, in my case, monsters.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/06/image_thumb.png" border="0" alt="image" width="162" height="150" /><br />
</a></p>
<p>Each cell is a bucket of game objects and a unique hash id. If we imagine the bucket as a list of 16 buckets, 0-15 cells and placed the game objects in that bucket.<br />
It might look something like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/image1.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/06/image_thumb1.png" border="0" alt="image" width="60" height="244" /></a></p>
<p>This is our 1D grid mentioned in the introduction.</p>
<p>It’s a simple premise really, any item in bucket 3 for example, cannot possibly collide with something in bucket 9.<br />
This reduces the amount of times we need to cycle the nearby objects but also dramatically reduce the amount of times we need to check if a collision is happening.</p>
<p>Ok, so the above implementation is fine as long as a game object only ever exists in 1 bucket. But what if it crosses a line and exists in more than 1 bucket.<br />
To resolve this I imagined a box around each game object, and I calculated the hash id for each corner of the box.<br />
I then populate a List; going through each bucket the game object is in. Sounds simple ?</p>
<p>Let me show you some of this theory in code.</p>
<p>First we need a game object. For this sample all we need is a position and a radius.</p>
<pre class="brush: csharp;">
    public class GameObject
    {
        public Vector2 Position { get; set; }
        public float Radius { get; set; }
    }
	</pre>
<p>We create a new class to store the grid data in including the buckets. I’m terrible at naming classes so I called it SpatialManager.<br />
I gave this class a Setup method which takes a full scenewidth, height and a cellsize. In our example this would be 100,100,25</p>
<pre class="brush: csharp;">
    public void Setup(int scenewidth, int sceneheight, int cellsize)
    {
</pre>
<p>We can work out how many buckets we need by first calculating the rows and cols then simply create a new Dictionary of buckets to the tune of Rows*Cols.<br />
I also store these variables passed in for future use.</p>
<pre class="brush: csharp;">
    Cols= scenewidth / cellsize;
    Rows= sceneheight / cellsize;
    Buckets = new Dictionary&amp;lt;int, List&amp;lt;GameObject&amp;gt;(Cols * Rows);

    for (int i = 0; i &amp;amp;lt; Cols*Rows; i++)
    {
        Buckets.Add(i, new List());
    }

    SceneWidth = scenewidth;
    SceneHeight = sceneheight;
    CellSize = cellsize;
}
</pre>
<p>Each update, we need to clear out the buckets and re calculate the buckets each game object are in. I created a method called ClearBuckets to start fresh.</p>
<pre class="brush: csharp;">
   internal void ClearBuckets()
   {
       Buckets.Clear();
       for (int i = 0; i &amp;amp;lt; Cols * Rows; i++)
       {
           Buckets.Add(i, new List());
       }
   }</pre>
<p>We now need a method to register a game object into the buckets it sits in.</p>
<pre class="brush: csharp;">
    internal void RegisterObject(GameObject obj)
    {
        List cellIds= GetIdForObj(obj);
        foreach (var item in cellIds)
        {
            Buckets[item].Add(obj);
        }
    }
</pre>
<p>As you can see, the code retrieves a list of cellids to add the game object to.</p>
<p>In the GetIdForObj method it calculates the cell id for each corner of the game object.</p>
<p>If we were just checking the position of the game object the calculation would be.</p>
<pre class="brush: csharp;">
    float width = SceneWidth / CellSize; // 100 / 25
    int hashid=(int)(
    (Math.Floor(position.X / CellSize)) +
    (Math.Floor(position.Y / CellSize)) * width);
	</pre>
<p>We need to do this for each corner and add our game to each bucket.</p>
<p>The GetIdForObj method looks like this.</p>
<pre class="brush: csharp;">
    private List GetIdForObj(GameObject obj)
    {
        List bucketsObjIsIn = new List();

        Vector2 min = new Vector2(
            obj.Position.X - (obj.Radius),
            obj.Position.Y - (obj.Radius));
        Vector2 max = new Vector2(
            obj.Position.X + (obj.Radius),
            obj.Position.Y + (obj.Radius));

        float width = SceneWidth / CellSize;
        //TopLeft
        AddBucket(min,width,bucketsObjIsIn);
        //TopRight
        AddBucket(new Vector2(max.X, min.Y), width, bucketsObjIsIn);
        //BottomRight
        AddBucket(new Vector2(max.X, max.Y), width, bucketsObjIsIn);
        //BottomLeft
        AddBucket(new Vector2(min.X, max.Y), width, bucketsObjIsIn);

	return bucketsObjIsIn;
    }
</pre>
<p>And here is the AddBucket method which uses the calculation described above and adds it to the list of bucket id's to add to.</p>
<pre class="brush: csharp;">
    private void AddBucket(Vector2 vector,float width,List buckettoaddto)
    {
        int cellPosition = (int)(
                   (Math.Floor(vector.X / CellSize)) +
                   (Math.Floor(vector.Y / CellSize)) *
                   width
        );
        if(!buckettoaddto.Contains(cellPosition))
            buckettoaddto.Add(cellPosition);

    }
</pre>
<p>Now that we have our grid of buckets. It's a very simple retrieval process. I added a method to get the nearby objects of a given object. This uses the GetIdForObj method and populates a list of GameObject's and returns once complete. This is the key part to this solution, you only now need to check items which are actually nearby and not items the other side of the theoretical world.</p>
<pre class="brush: csharp;">
    internal List GetNearby(GameObject obj)
    {
        List objects = new List();
        List bucketIds = GetIdForObj(obj);
        foreach (var item in bucketIds)
        {
            objects.AddRange(Buckets[item]);
        }
        return objects;
    }
</pre>
<p>So that’s it. Now you can do your normal collision checking by retrieving nearby GameObjects. And here’s a screenshot to prove it.</p>
<p>I’ve placed my mouse over one of the GameObjects and it’s highlighted all nearby items. Notice how they cross over cells. This is because the item i hover over is on the line and exists in multiple cells. Also notice the amount of checks it has to do. For brute force it has to do 250,000 bounding box collision checks. For spatial hashing, it checks only 4840 times. Wicked.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/spatialhashing.png"><img style="display:inline;border-width:0;" title="SpatialHashing" src="http://conkerjo.files.wordpress.com/2009/06/spatialhashing_thumb.png" border="0" alt="SpatialHashing" width="468" height="367" /></a></p>
<p>And what would a sample be without source code?</p>
<p>Enjoy</p>
<p><a href="http://conkerjoe.ziggyware.com/wm/SpatialTest.zip" target="_blank">Link To Sample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Article: Behavior Tree Overview</title>
		<link>http://www.sgtconker.com/2009/10/behavior-tree-overview-placeholder/</link>
		<comments>http://www.sgtconker.com/2009/10/behavior-tree-overview-placeholder/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:17:11 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[A.I]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Behavior Tree]]></category>
		<category><![CDATA[BRAINS]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=19</guid>
		<description><![CDATA[This article talks about some of the basic behavior tree concepts and how to apply them using XNA and the BRAINS library I wrote]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.conkerjo.com/">Conkerjo</a></h4>
<p>This article talks about some of the basic behavior tree concepts and how to apply them using XNA and the BRAINS library I wrote</p>
<p>The Brains library is built up of a world map, an A.I agent and a behavior tree implementation.</p>
<p><span id="more-19"></span></p>
<p><strong>The Map</strong></p>
<p>A world map is made up of a grid. In it’s simplest form a world map could look like this</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/07/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb.png" border="0" alt="image" width="68" height="68" /></a></p>
<p>It would be made up of 1 grid which is 16 GridCells and have 4 columns and 4 rows of GridCells.</p>
<p>A more complex world might have over 100x100 GridCells in it’s map. Brains can split this into a cluster for you which will greatly increase the speed of path finding and other A.I techniques.<br />
As a simple sample we could have a map made up of 8x8 cells and have a cluster of 4 grids.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/07/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb.png" border="0" alt="image" width="68" height="68" /></a><br />
<a href="http://conkerjo.files.wordpress.com/2009/07/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb.png" border="0" alt="image" width="68" height="68" /></a></p>
<p><a href="http://conkerjo.files.wordpress.com/2009/07/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb.png" border="0" alt="image" width="68" height="68" /></a><br />
<a href="http://conkerjo.files.wordpress.com/2009/07/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb.png" border="0" alt="image" width="68" height="68" /></a></p>
<p>In the real world they wouldn't have a gap in between, this is just to represent that they are separate grids in a map cluster.</p>
<p>When loading a world map you simply specify the width and height of the map in world coordinates, pixels for example,<br />
the cell size to split the world into again in world coordinates and if you have a large world you can decide to create a cluster by specifying the rows and columns to split the bigger world into.<br />
In this example that would look something like this.</p>
<p><code>World.SetupMap(1280,1280,160,2,2);</code></p>
<p>You can also load a world map by loading from a texture.<br />
In the current implementation it will assume 1 pixel of the image to be 1 GridCell. Here is a blown up example of one of the demos in the source code.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/07/image1.png"><br />
<img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb1.png" border="0" alt="image" width="244" height="184" /></a></p>
<p>Brains will set any pixel that is black, to be a blocked type of GridCell, and any other colour to be an empty GridCell.<br />
The red and green pixels are loaded and annotated on the grid for your use but are not used internally in the engine.<br />
This makes it super easy to knock up a quick map to test out.</p>
<p><strong>The Agent</strong></p>
<p>A Brains A.I world also contains a list of Agent types. This type is used to provide autonomous behaviors to your game. An Agent stores some simple positioning properties such as Position,<br />
Radius and the Cells the Agent is currently in. It also stores the desired orientation and the desired position of an Agent for use with a Locomotion controller.</p>
<p>An Agent can store a set of feelers which can be used by your behaviors to poke data around the world.</p>
<p>The last defining feature of an Agent is it’s RootBehavior property.<br />
This is an IBehavior type which can be any type of behavior built into Brains, or your own custom implementation.</p>
<p>You can inherit from the Agent type to give you that extra flexibility when creating your autonomous characters.</p>
<p><strong>Locomotion Controller</strong></p>
<p>The Locomotion Controller is what controls the movement of an Agent.<br />
This is isolated from the Agent so that you can extend and implement the default implementation to get your characters moving how you want them to.<br />
There are 2 types of LocomotionController implemented in Brains. The basic movement controller which moves the agent from its current position to its desired position,<br />
and rotates it to face the desired rotation. The other Locomotion Controller is the LocomotionSteering which will allow you to make use of the famous<br />
<a href="http://www.red3d.com/cwr/steer/" target="_blank">Steering Behaviors For Autonomous Characters</a> by Craig Reynolds.<br />
My version isn’t quite finished yet as I’m working on a better group design but the basic steering behaviors are working at the moment.</p>
<p><strong>Behaviors</strong></p>
<p>Brains contains some built in behaviors to form the basis of any combination of behaviors you may ever need to build.<br />
You can of course ignore these and implement your own.</p>
<p>With the Brains building blocks you can quickly build very complex behaviour trees without writing a ton of spaghetti code.</p>
<p>A Behavior Tree is made up of smaller blocks of hierarchical logic and built to recursively go down the tree until it finds a behavior to run.<br />
A simple representation of a Behavior Tree can be shown like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/07/image2.png"><br />
<img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/07/image_thumb2.png" border="0" alt="image" width="244" height="244" /></a></p>
<p>The circles represent a behavior and the lines show how the behavior breaks down into active actions an Agent may take based on decisions further up the tree.<br />
The Behavior tree is a much larger the subject than the scope of this post though so I will brush over the behavior building blocks built right into Brains.</p>
<p><strong>Sequence Behavior</strong></p>
<p>The Sequence Behavior has a set of sub behaviors which will run the first item in the list until it is successful,<br />
it will then move onto the next behavior in it's sub behaviours in sequence. If a behavior fails it will fail the whole sequence.</p>
<p><strong>Selector Behavior</strong></p>
<p>The Selector Behavior also has a set of sub behaviors which it will run in sequence until it finds a success and then complete as a success itself.</p>
<p><strong>Random Behavior</strong></p>
<p>This Behavior randomly selects one of its child behaviors to run.</p>
<p><strong>ParallelBehavior</strong></p>
<p>This is a very primitive implementation of a Behavior which will run multiple behaviors at the same time.<br />
This raises a lot of complications with access to current data so will currently prove troublesome if the parallel is not a simple one.</p>
<p><strong>Condition Behavior</strong></p>
<p>Used to provide conditions before running other sub behaviors</p>
<p><strong>Task Behavior</strong></p>
<p>This is the behavior which would contain your A.I logic code. You would generally inherit from this to provide the specific game A.I logic.</p>
<p>Combining these set of components with your own and your imagination you can create extremely complex A.I decision making agents with great ease.<br />
With the added bonus of a Behavior Tree designer provided with the source code it’s even easier to let you just put on your game designer hat or give the ability to a game designer to create a better game A.I</p>
<p>Brains also contains a few Task Behaviors for pathfinding around the world. You can also extend upon these to provide more flexible pathfinding.</p>
<p>They are:</p>
<p><strong>Find Path Behavior</strong></p>
<p>Finds a path from 1 GridCell to another.</p>
<p><strong>Follow Path Behavior</strong></p>
<p>Follows a provided path.</p>
<p><strong>GoTo Behavior</strong></p>
<p>This behavior combines the FindPath and FollowPath behaviors.</p>
<p><strong>FollowRouteBehavior</strong></p>
<p>This Behavior takes a series of GridCells. It will pathfind from one GridCell to the next and cycle once it’s complete. This makes use of the GoTo Behavior.</p>
<p>That’s a brief roundup of what Brains has to offer. It’s still unfinished and will continue to get development done to it.<br />
I want to tidy up some of the API exposure I’m not happy about yet (a few dirty hacks) and then I’ll post the source code for you to have a play with and give me some feedback.</p>
<p><strong> </strong></p>
<p><strong>Credits</strong></p>
<p>The majority of my A.I reading has been from the <a href="http://aigamedev.com/" target="_blank">AIGameDev</a> web site.<br />
I’ve learned so much from there, I highly recommend it.</p>
<p>Some other helpful sites are of course the <a href="http://creators.xna.com/" target="_blank">XNA Creators Club Online</a></p>
<p>A few other XNA A.I related projects have also been a great source of inspiration. Most notably <a href="http://simpleai.codeplex.com/" target="_blank">Simple AI Engine for XNA</a> and<br />
<a href="http://www.codeplex.com/SharpSteer" target="_blank">SharpSteer</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/behavior-tree-overview-placeholder/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
