Showing posts with label flyweight. Show all posts
Showing posts with label flyweight. Show all posts

Wednesday, January 16, 2013

Final pool version

Since I went from C# to AS3 in order to complete web games I realized that the lack of generics in AS3 was going to be a huge problem for my pooling system, this forced me to think things once again and the result was something more elegant, secure and completely contained within the pooled class.

Making use of the factory design pattern once again I was able to create a pool system within the same class (which is now a template in my IDE), here is how it goes:

public class PooledItem
{
   private static var PoolHead:PooledItem;
   private var Next:PooledItem;
   private var Self:PooledItem;

   public function PooledItem()
   {
      Self = this;
   }

   public static function Create():PooledItem
   {
      var Vessel:PooledItem;
      if(PooledHead != null)
      {
         Vessel = PoolHead;
         PoolHead = PoolHead.Next;
      }
      else
      {
         Vessel = new PooledItem();
      }
      
      return Vessel;
   }
}


The PoolHead is private and static, making it unique locally and impossible to access from outside this class, then we have the Next and the Self which are unique to each instance of the PooledItem, and finally we have a factory pattern which creates a new instance of a PooledItem if the head is null, but if the head is not null it will return it and set the new head as the next element in the queue.

One thing to have in mind is that AS3 does not allow to have private constructors, thus making it possible to create an instance of the PooledItem without the factory method, if this happens and you don't properly get rid of it by calling its recycle method then you will have an extra element (outside the pool) doing nothing, but even if you create it without the "create" function you can still put it back in the pool by calling recycle, so no real harm done if handled properly, still if this was not AS3 I would make the constructor private.

Going to the recycle function now, the recycle function is where I do all my clean up code (if required depending on the elements of the class) as well as to put elements back into the pool:

public function Recycle():void
{
   //Do clean up code, maybe recycle other pooled items that were created within this
   //class or release references of an element to let GC deal with it, etc.

   Next = PoolHead; //we set the next element as the current head.
   PoolHead = Self; //and finally we set the this element as the new head.
}


And that's it, it is amazing how essential and memory friendly this can be, allocating memory and deallocating memory can be very tasking in the system, specially if you are planning on putting your games in mobile devices, have in mind also that the more memory you use the more battery it might consume, so in order to have some balance make sure to maintain your pools, this can be achieve by an internal reference counter and releasing some of them if the number gets to a certain point, however you want to handle that I will leave to you.


Friday, October 19, 2012

My Factory Design Pattern

I will talk a bit about how I create my "Game objects".

The first thing you need to know is that I do not use the keyword "New" to instantiate a new object, this is because I need to have control over my game objects (coming from the pools), Let's create a quick example, I am going to assume that you know about my pool system, but if you don't please take a look at the previous post.

We will start with the body of the class.

public class Slime: PooleanNode<Slime> 
{
    static LinkedPoolean<Slime> Pool = new LinkedPoolean<Slime>();

    public Slime()
    {
    }
}

Here we have declared a "Slime class" that can be pooled with my pool class, as you can see the constructor is public so we can instantiate them with the activator class, also there's a static pool of slimes living inside this class, this will mean that in every single slime object you will have access to the same pool, this is important cause all the slimes need to come from the pool, now moving into the "creational" method.

public static Slime Create() //this function must live inside the slime class.
{
    Slime Vessel;
    Pool.Get(out Vessel); //if it doesn't live inside the class, the pool wouldn't be
    return Vessel;        //visible, you would have to make it public and access it
}                         //like "Slime.Pool", I don't recommend that. 

And done, we have create an static method that will take slimes out of the pool and return them, simple as that! now for some logic on why I do this, by making a new slime this way I make sure they come from the pool and that they are not generated outside of the pool, this is handy when we want to manage them and when we want to avoid tasking the garbage collector, since we are not allocating new memory.

Now let's expand on it, to make it useful, you can declare multiple creation methods to obtain different results, let's say that the Slime has some fields like position or maybe current hit points, etc, we can modify these elements like this:

public class Slime: PooleanNode<Slime> 
{
    static LinkedPoolean<Slime> Pool = new LinkedPoolean<Slime>();

    Vector2 Position;
    int HP;

    public Slime()
    {
        Position = Vector2.Zero;
        HP = 1;
    }

    public static Slime Create(Vector2 Position, int HP) 
    {
        Slime Vessel;
        Pool.Get(out Vessel); 
        Vessel.Position = Position;
        Vessel.HP = HP;
        return Vessel;       
    } 
}

By default the slime starts at position 0,0 and with 1 HP, but we can create any slime anywhere we want as well as giving it any amount of HP we want, we can create more methods to define things ever further.

Lastly I define a recycle method that I use when I need to get rid of the object and sent it back to the pool, like this:

public void Recycle()
{
    Pool.ReturnPoolable(this);
}

That makes sure that the object is sent back into the pool to be reused by the factory method, this is an overly simplified version of what I use in my current game, if you would like to check the game out, here:

Game

Thanks for reading!

Monday, October 15, 2012

Taking casting out of the picture

Once again! I have done another revision to the way I am doing pools, it is almost like an obsession, in any case, it has proven to be fantastic, onto the code:

public class LinkedPoolean<T> where T : PooleanNode<T>, new()
    {
        public T Head;

        public LinkedPoolean()
        {
            Head = Activator.CreateInstance<T>();
        }

        public void Get(out T Vessel)
        {
            if (Head != null)
            {
                Vessel = Head;
                Head = Head.Next;
            }
            else
            {
                Vessel = Activator.CreateInstance<T>();
            }
         
        }

        public void ReturnPoolable(T Return)
        {
            Return.Next = Head;
            Head = Return;
        }
    }

The Key change here is the way we access the "Activator", you see, there's a function to create an instance that takes a Generic parameter T, and there's another version of the function that takes an argument "Type" and returns an "Object", the object returned by the second function is sadly not the right type, so in order to use it I used to cast it, this would create a hit on the performance. The function that takes a parameter of type T returns an object of type T, making casting unnecessary.

This improvement was only possible though if the PooleanNode knew which "kind of poolean node" it was, new Poolean node class:

public class PooleanNode<T> where T: PooleanNode<T>
    {
        public T Next;
    }


This in turn makes the poolean node type safe, before hand it was potentially possible to subscribe a poolean node into a pool of another type, it was kind of weird at the beginning to see a class expecting itself to be the template, but it is kind of cool the way it works.

Thanks for reading~

Friday, September 21, 2012

The Pooling Redo

I can't believe that I first attempted to make a proper pool back in April, that's only 6 months ago! I learned so much and looking back I feel dumb, but that's the main purpose of this blog! I like to check out my learning curve.

Anyways, to the pools, not too long ago I read about intrusive lists and how they were awesome for managing your game objects, before that my take on recursions were weird as well, I abandon the method and just made a while loop scanning of the nodes to traverse the tree, so no more recursion because the Xbox hates you using memory!

My last revision on the pool was cool, managed and it served it's purpose pretty well, but then I read about recursive lists and I thought that I could use something like that in the pool, a linked list pretty much but instead of using the built in linked list I wanted to make the nodes of the pool the actual objects and not a sub object attached to a node.

public class LinkedPoolean<t> where T : PooleanNode, new()
    {
       Type TypeOfT;

        T Head;

        public LinkedPoolean()
        {
            TypeOfT = typeof(T);
            Head = (T)Activator.CreateInstance(TypeOfT);
        }

        public void Get(out T Vessel)
        {
            if (Head != null)
            {
                Vessel = Head;
                Head = (T)Head.Next;
            }
            else
            {
                Vessel = (T)Activator.CreateInstance(TypeOfT);
            }
        }

        public void ReturnPoolable(T Return)
        {
            Return.Next = Head;
            Head = Return;
        }
    }

The thing to note here is that it is so ridiculous simple in comparison to my first attempt, and I was thinking that the last attempt was short! now, in this case I made the "PooleanNode" a base class cause it bugs me to know that I would have to use a "Property" to fetch a single field (which is all that class has in it as for now), but if that doesn't bother you then you may as well make the class an interface.

Poolean class:

public class PooleanNode
    {
        public PooleanNode Next;
    }

Well more weird things will result out of this, I am going to be changing quite a bit of things in my engine, because this method it is not just about 10 times faster and more memory friendly but it is also a good design.

Friday, August 17, 2012

New Poolean

Looking back to when I made my first "Pool" (called Poolean) and the reasons why I made it the way it was I came to realize I was trying to avoid using "List.Remove(T)" besides avoiding to create new elements every time something was needed.
Some time after that I stumbled upon a performance problem that was going to 
hinder my game if the number of elements to be managed was going to be big, let'ssay that a pool is used a lot, meaning that the elements within the pool are
almost always "In use" and often the pool requires to expand (create new elementsto accommodate demand). Following the way the pool used to work, I would have to check if the "next" element was free, and if it was not continue until I ran out of space, then I started back from 0 to right before the element I just used, andif nothing was available then expand the pool.
The problem with this is that if I want something that requires big numbers (likeparticles) it would get hairy real quick.
I was trying to make a class that could hold a collection of objects and be able to remove the objects without having to shift things around (like List.Remove(T) does) because once again that would be very slow, I came with the idea of removing the certain element and swapping the last element in the collection to the position of the element we just removed, putting the count down by one and that would be all, in order to do this, the object I wanted to use in this "Collection" would have to contain an interface that allows access to certain index number, just a simple property to know in which position the element is in the collection. This methodology could fix my Poolean issue, by knowing how many items are in the pool, and knowing I always remove the last one, this made the entire "Searching for the next element" completely obsolete, which made me happy, so now the new Poolean looks like this:    


public class Poolean<T> where T: new()
    {
        public T[] Pool;
        public int Size;
        public int GrowthAmount;
        public int CurrentFreeIndex;
        public Type TypeOfT;

        public Poolean(int size, int Growth)
        {
            CurrentFreeIndex = size - 1;
            GrowthAmount = Growth;
            TypeOfT = typeof(T);

            Pool = new T[size];

            Size = size;

            for (int i = 0; i < Size; i++)
            {
                T NewElement = (T)Activator.CreateInstance(TypeOfT);
                Pool[i] = NewElement;
            }
        }

        public void Get(out T Vessel)
        {
            if (CurrentFreeIndex > -1)
            {
                Vessel = (T)Pool[CurrentFreeIndex];
                Pool[CurrentFreeIndex] = default(T);
                CurrentFreeIndex--;
            }
            else
            {
                //Expand
                CurrentFreeIndex += GrowthAmount;
                Size += GrowthAmount;
                Pool = new T[Size];
                for (int i = 0; i < GrowthAmount; i++)
                {
                    T NewItem = (T)Activator.CreateInstance(TypeOfT);
                    Pool[i] = NewItem;
                }

                //try again
                Vessel = (T)Pool[CurrentFreeIndex];
                Pool[CurrentFreeIndex] = default(T);
                CurrentFreeIndex--;
            }
        }

        public void ReturnPoolable(T Poolable)
        {
            CurrentFreeIndex++;
            Pool[CurrentFreeIndex] = Poolable;
        }
    }


As you can see it is a lot shorted and easier to understand, let's go over the Constructor first, in the constructor you specify how many elements do you want in the pool to begin with and in the event that the pool runs out of space, how many elements you want to add, pretty simple, there we define what type T is and then we populate the array of Ts with objects of type T. Then we have the "Get" function which takes an element out of the pool if it has any left and if it doesn't it expands, and finally we have the "ReturnPoolable" which adds the element back to the pool and gets the count up by one.

This made the pool lightning faster, but I hope I come up with an idea to make it even faster.