TextPool.hx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package textbox;
  2. import flixel.util.FlxDestroyUtil;
  3. class TextPool implements IFlxPool<Text>
  4. {
  5. public var length(get, never):Int;
  6. private var _pool:Array<Text> = [];
  7. /**
  8. * Objects aren't actually removed from the array in order to improve performance.
  9. * _count keeps track of the valid, accessible pool objects.
  10. */
  11. private var _count:Int = 0;
  12. public function new()
  13. {
  14. }
  15. public function get():Text
  16. {
  17. if (_count == 0)
  18. {
  19. return new Text();
  20. }
  21. var c:Text = _pool[--_count];
  22. c.clear();
  23. return c;
  24. }
  25. public function put(obj:Text):Void
  26. {
  27. // we don't want to have the same object in the accessible pool twice (ok to have multiple in the inaccessible zone)
  28. if (obj != null)
  29. {
  30. var i:Int = _pool.indexOf(obj);
  31. // if the object's spot in the pool was overwritten, or if it's at or past _count (in the inaccessible zone)
  32. if (i == -1 || i >= _count)
  33. {
  34. // Make the character invisible and not updated instead of destroying the shit out of it.
  35. obj.kill();
  36. _pool[_count++] = obj;
  37. }
  38. }
  39. }
  40. public function putUnsafe(obj:Text):Void
  41. {
  42. if (obj != null)
  43. {
  44. // Make the character invisible and not updated instead of destroying the shit out of it.
  45. obj.kill();
  46. _pool[_count++] = obj;
  47. }
  48. }
  49. public function preAllocate(numObjects:Int):Void
  50. {
  51. while (numObjects-- > 0)
  52. {
  53. _pool[_count++] = new Text();
  54. }
  55. }
  56. public function clear():Array<Text>
  57. {
  58. _count = 0;
  59. var oldPool = _pool;
  60. _pool = [];
  61. return oldPool;
  62. }
  63. private inline function get_length():Int
  64. {
  65. return _count;
  66. }
  67. }
  68. interface IFlxPooled extends IFlxDestroyable
  69. {
  70. public function put():Void;
  71. private var _inPool:Bool;
  72. }
  73. interface IFlxPool<T:IFlxDestroyable>
  74. {
  75. public function preAllocate(numObjects:Int):Void;
  76. public function clear():Array<Text>;
  77. }