ComputeSystemVKWithAllocator.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2025 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #ifdef JPH_USE_VK
  6. #include <Jolt/Compute/VK/ComputeSystemVK.h>
  7. #include <Jolt/Core/UnorderedMap.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// This extends ComputeSystemVK to provide a default implementation for memory allocation and mapping.
  10. /// It uses a simple block based allocator to reduce the number of allocations done to Vulkan.
  11. class JPH_EXPORT ComputeSystemVKWithAllocator : public ComputeSystemVK
  12. {
  13. public:
  14. JPH_DECLARE_RTTI_VIRTUAL(JPH_EXPORT, ComputeSystemVKWithAllocator)
  15. /// Allow the application to override buffer creation and memory mapping in case it uses its own allocator
  16. virtual bool CreateBuffer(VkDeviceSize inSize, VkBufferUsageFlags inUsage, VkMemoryPropertyFlags inProperties, BufferVK &outBuffer) override;
  17. virtual void FreeBuffer(BufferVK &ioBuffer) override;
  18. virtual void * MapBuffer(BufferVK &ioBuffer) override;
  19. virtual void UnmapBuffer(BufferVK &ioBuffer) override;
  20. protected:
  21. virtual bool InitializeMemory() override;
  22. virtual void ShutdownMemory() override;
  23. uint32 FindMemoryType(uint32 inTypeFilter, VkMemoryPropertyFlags inProperties) const;
  24. void AllocateMemory(VkDeviceSize inSize, uint32 inMemoryTypeBits, VkMemoryPropertyFlags inProperties, MemoryVK &ioMemory);
  25. void FreeMemory(MemoryVK &ioMemory);
  26. VkPhysicalDeviceMemoryProperties mMemoryProperties;
  27. private:
  28. // Smaller allocations (from cMinAllocSize to cMaxAllocSize) will be done in blocks of cBlockSize bytes.
  29. // We do this because there is a limit to the number of allocations that we can make in Vulkan.
  30. static constexpr VkDeviceSize cMinAllocSize = 512;
  31. static constexpr VkDeviceSize cMaxAllocSize = 65536;
  32. static constexpr VkDeviceSize cBlockSize = 524288;
  33. struct MemoryKey
  34. {
  35. bool operator == (const MemoryKey &inRHS) const
  36. {
  37. return mSize == inRHS.mSize && mProperties == inRHS.mProperties;
  38. }
  39. VkDeviceSize mSize;
  40. VkMemoryPropertyFlags mProperties;
  41. };
  42. JPH_MAKE_HASH_STRUCT(MemoryKey, MemoryKeyHasher, t.mProperties, t.mSize)
  43. struct Memory
  44. {
  45. Ref<MemoryVK> mMemory;
  46. VkDeviceSize mOffset;
  47. };
  48. using MemoryCache = UnorderedMap<MemoryKey, Array<Memory>, MemoryKeyHasher>;
  49. MemoryCache mMemoryCache;
  50. };
  51. JPH_NAMESPACE_END
  52. #endif // JPH_USE_VK