StackGpuAllocator.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Gr/Common.h>
  7. namespace anki
  8. {
  9. // Forward
  10. class StackGpuAllocatorChunk;
  11. /// @addtogroup graphics
  12. /// @{
  13. /// The user defined output of an allocation.
  14. class StackGpuAllocatorMemory
  15. {
  16. };
  17. /// The user defined methods to allocate memory.
  18. class StackGpuAllocatorInterface
  19. {
  20. public:
  21. virtual ~StackGpuAllocatorInterface()
  22. {
  23. }
  24. /// Allocate memory. Should be thread safe.
  25. virtual ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorMemory*& mem) = 0;
  26. /// Free memory. Should be thread safe.
  27. virtual void free(StackGpuAllocatorMemory* mem) = 0;
  28. /// If the current chunk of the linear allocator is of size N then the next chunk will be of size N*scale+bias.
  29. virtual void getChunkGrowInfo(F32& scale, PtrSize& bias, PtrSize& initialSize) = 0;
  30. virtual U32 getMaxAlignment() = 0;
  31. };
  32. /// The output of an allocation.
  33. class StackGpuAllocatorHandle
  34. {
  35. friend class StackGpuAllocator;
  36. public:
  37. StackGpuAllocatorMemory* m_memory = nullptr;
  38. PtrSize m_offset = 0;
  39. explicit operator Bool() const
  40. {
  41. return m_memory != nullptr;
  42. }
  43. };
  44. /// Linear based allocator.
  45. class StackGpuAllocator
  46. {
  47. public:
  48. StackGpuAllocator() = default;
  49. StackGpuAllocator(const StackGpuAllocator&) = delete; // Non-copyable
  50. ~StackGpuAllocator();
  51. StackGpuAllocator& operator=(const StackGpuAllocator&) = delete; // Non-copyable
  52. void init(GenericMemoryPoolAllocator<U8> alloc, StackGpuAllocatorInterface* iface);
  53. /// Allocate memory.
  54. ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorHandle& handle);
  55. /// Reset all the memory chunks. Not thread safe.
  56. void reset();
  57. StackGpuAllocatorInterface* getInterface() const
  58. {
  59. ANKI_ASSERT(m_iface);
  60. return m_iface;
  61. }
  62. private:
  63. using Chunk = StackGpuAllocatorChunk;
  64. GenericMemoryPoolAllocator<U8> m_alloc;
  65. StackGpuAllocatorInterface* m_iface = nullptr;
  66. Chunk* m_chunkListHead = nullptr;
  67. Atomic<Chunk*> m_crntChunk = {nullptr};
  68. Mutex m_lock;
  69. F32 m_scale = 0.0;
  70. PtrSize m_bias = 0;
  71. PtrSize m_initialSize = 0;
  72. U32 m_alignment = 0;
  73. };
  74. /// @}
  75. } // end namespace anki