diff --git a/Blarg.GameFramework/Blarg.GameFramework.csproj b/Blarg.GameFramework/Blarg.GameFramework.csproj index 5b50fc1..a8d4abe 100644 --- a/Blarg.GameFramework/Blarg.GameFramework.csproj +++ b/Blarg.GameFramework/Blarg.GameFramework.csproj @@ -137,6 +137,9 @@ + + + diff --git a/Blarg.GameFramework/Support/BasicObjectPool.cs b/Blarg.GameFramework/Support/BasicObjectPool.cs new file mode 100644 index 0000000..a7aa273 --- /dev/null +++ b/Blarg.GameFramework/Support/BasicObjectPool.cs @@ -0,0 +1,23 @@ +using System; + +namespace Blarg.GameFramework.Support +{ + public class BasicObjectPool : ObjectPool where T : class, new() + { + public BasicObjectPool() + : base() + { + } + + public BasicObjectPool(int initialCapacity) + : base(initialCapacity) + { + } + + protected override T Allocate() + { + return new T(); + } + } +} + diff --git a/Blarg.GameFramework/Support/IPoolable.cs b/Blarg.GameFramework/Support/IPoolable.cs new file mode 100644 index 0000000..fca0c91 --- /dev/null +++ b/Blarg.GameFramework/Support/IPoolable.cs @@ -0,0 +1,10 @@ +using System; + +namespace Blarg.GameFramework.Support +{ + public interface IPoolable + { + void Reset(); + } +} + diff --git a/Blarg.GameFramework/Support/ObjectPool.cs b/Blarg.GameFramework/Support/ObjectPool.cs new file mode 100644 index 0000000..d2c2079 --- /dev/null +++ b/Blarg.GameFramework/Support/ObjectPool.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; + +namespace Blarg.GameFramework.Support +{ + public abstract class ObjectPool where T : class + { + List _objects; + int _objectCount; + + public ObjectPool() + : this(16) + { + } + + public ObjectPool(int initialCapacity) + { + _objects = new List(initialCapacity); + _objectCount = 0; + } + + protected abstract T Allocate(); + + public T Take() + { + if (_objectCount == 0) + return Allocate(); + else + { + // remove the last object in the list + int index = _objectCount - 1; + T obj = _objects[index]; + + // shrink the object list + _objects[index] = null; + --_objectCount; + + return obj; + } + } + + public void Free(T obj) + { + if (obj == null) + throw new ArgumentNullException("obj"); + + int index = _objectCount; + if (index >= _objects.Count) + // need to grow the object list by one + _objects.Add(obj); + else + _objects[index] = obj; + + ++_objectCount; + + if (obj is IPoolable) + ((IPoolable)obj).Reset(); + } + } +} +