BsVulkanHardwareBuffer.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsVulkanHardwareBuffer.h"
  4. #include "BsVulkanRenderAPI.h"
  5. #include "BsVulkanDevice.h"
  6. #include "BsVulkanUtility.h"
  7. #include "BsVulkanCommandBufferManager.h"
  8. #include "BsVulkanCommandBuffer.h"
  9. #include "BsVulkanTexture.h"
  10. namespace bs
  11. {
  12. VulkanBuffer::VulkanBuffer(VulkanResourceManager* owner, VkBuffer buffer, VkBufferView view, VkDeviceMemory memory,
  13. UINT32 rowPitch, UINT32 slicePitch)
  14. : VulkanResource(owner, false), mBuffer(buffer), mView(view), mMemory(memory), mRowPitch(rowPitch)
  15. {
  16. if (rowPitch != 0)
  17. mSliceHeight = slicePitch / rowPitch;
  18. else
  19. mSliceHeight = 0;
  20. }
  21. VulkanBuffer::~VulkanBuffer()
  22. {
  23. VulkanDevice& device = mOwner->getDevice();
  24. if (mView != VK_NULL_HANDLE)
  25. vkDestroyBufferView(device.getLogical(), mView, gVulkanAllocator);
  26. vkDestroyBuffer(device.getLogical(), mBuffer, gVulkanAllocator);
  27. device.freeMemory(mMemory);
  28. }
  29. UINT8* VulkanBuffer::map(VkDeviceSize offset, VkDeviceSize length) const
  30. {
  31. VulkanDevice& device = mOwner->getDevice();
  32. UINT8* data;
  33. VkResult result = vkMapMemory(device.getLogical(), mMemory, offset, length, 0, (void**)&data);
  34. assert(result == VK_SUCCESS);
  35. return data;
  36. }
  37. void VulkanBuffer::unmap()
  38. {
  39. VulkanDevice& device = mOwner->getDevice();
  40. vkUnmapMemory(device.getLogical(), mMemory);
  41. }
  42. void VulkanBuffer::copy(VulkanTransferBuffer* cb, VulkanBuffer* destination, VkDeviceSize srcOffset,
  43. VkDeviceSize dstOffset, VkDeviceSize length)
  44. {
  45. VkBufferCopy region;
  46. region.size = length;
  47. region.srcOffset = srcOffset;
  48. region.dstOffset = dstOffset;
  49. vkCmdCopyBuffer(cb->getCB()->getHandle(), mBuffer, destination->getHandle(), 1, &region);
  50. }
  51. void VulkanBuffer::copy(VulkanTransferBuffer* cb, VulkanImage* destination, const VkExtent3D& extent,
  52. const VkImageSubresourceLayers& range, VkImageLayout layout)
  53. {
  54. VkBufferImageCopy region;
  55. region.bufferRowLength = mRowPitch;
  56. region.bufferImageHeight = mSliceHeight;
  57. region.bufferOffset = 0;
  58. region.imageOffset.x = 0;
  59. region.imageOffset.y = 0;
  60. region.imageOffset.z = 0;
  61. region.imageExtent = extent;
  62. region.imageSubresource = range;
  63. vkCmdCopyBufferToImage(cb->getCB()->getHandle(), mBuffer, destination->getHandle(), layout, 1, &region);
  64. }
  65. void VulkanBuffer::update(VulkanTransferBuffer* cb, UINT8* data, VkDeviceSize offset, VkDeviceSize length)
  66. {
  67. vkCmdUpdateBuffer(cb->getCB()->getHandle(), mBuffer, offset, length, (uint32_t*)data);
  68. }
  69. VulkanHardwareBuffer::VulkanHardwareBuffer(BufferType type, GpuBufferFormat format, GpuBufferUsage usage,
  70. UINT32 size, GpuDeviceFlags deviceMask)
  71. : HardwareBuffer(size), mBuffers(), mStagingBuffer(nullptr), mStagingMemory(nullptr), mMappedDeviceIdx(-1)
  72. , mMappedGlobalQueueIdx(-1), mMappedOffset(0), mMappedSize(0), mMappedLockOptions(GBL_WRITE_ONLY)
  73. , mDirectlyMappable((usage & GBU_DYNAMIC) != 0), mSupportsGPUWrites(type == BT_STORAGE), mRequiresView(false)
  74. , mIsMapped(false)
  75. {
  76. VkBufferUsageFlags usageFlags = 0;
  77. switch(type)
  78. {
  79. case BT_VERTEX:
  80. usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  81. break;
  82. case BT_INDEX:
  83. usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
  84. break;
  85. case BT_UNIFORM:
  86. usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
  87. break;
  88. case BT_GENERIC:
  89. usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT;
  90. mRequiresView = true;
  91. break;
  92. case BT_STORAGE:
  93. usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
  94. mRequiresView = true;
  95. break;
  96. }
  97. mBufferCI.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  98. mBufferCI.pNext = nullptr;
  99. mBufferCI.flags = 0;
  100. mBufferCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  101. mBufferCI.usage = usageFlags;
  102. mBufferCI.queueFamilyIndexCount = 0;
  103. mBufferCI.pQueueFamilyIndices = nullptr;
  104. mViewCI.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  105. mViewCI.pNext = nullptr;
  106. mViewCI.flags = 0;
  107. mViewCI.format = VulkanUtility::getBufferFormat(format);
  108. mViewCI.offset = 0;
  109. mViewCI.range = VK_WHOLE_SIZE;
  110. VulkanRenderAPI& rapi = static_cast<VulkanRenderAPI&>(RenderAPICore::instance());
  111. VulkanDevice* devices[BS_MAX_DEVICES];
  112. VulkanUtility::getDevices(rapi, deviceMask, devices);
  113. // Allocate buffers per-device
  114. for (UINT32 i = 0; i < BS_MAX_DEVICES; i++)
  115. {
  116. if (devices[i] == nullptr)
  117. continue;
  118. mBuffers[i] = createBuffer(*devices[i], size, false, true);
  119. }
  120. }
  121. VulkanHardwareBuffer::~VulkanHardwareBuffer()
  122. {
  123. for (UINT32 i = 0; i < BS_MAX_DEVICES; i++)
  124. {
  125. if (mBuffers[i] == nullptr)
  126. continue;
  127. mBuffers[i]->destroy();
  128. }
  129. assert(mStagingBuffer == nullptr);
  130. }
  131. VulkanBuffer* VulkanHardwareBuffer::createBuffer(VulkanDevice& device, UINT32 size, bool staging, bool readable)
  132. {
  133. VkBufferUsageFlags usage = mBufferCI.usage;
  134. if (staging)
  135. {
  136. mBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  137. // Staging buffers are used as a destination for reads
  138. if (readable)
  139. mBufferCI.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  140. }
  141. else if(readable) // Non-staging readable
  142. mBufferCI.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  143. mBufferCI.size = size;
  144. VkMemoryPropertyFlags flags = (mDirectlyMappable || staging) ?
  145. (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) : // Note: Try using cached memory
  146. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  147. VkDevice vkDevice = device.getLogical();
  148. VkBuffer buffer;
  149. VkResult result = vkCreateBuffer(vkDevice, &mBufferCI, gVulkanAllocator, &buffer);
  150. assert(result == VK_SUCCESS);
  151. VkMemoryRequirements memReqs;
  152. vkGetBufferMemoryRequirements(vkDevice, buffer, &memReqs);
  153. VkDeviceMemory memory = device.allocateMemory(memReqs, flags);
  154. result = vkBindBufferMemory(vkDevice, buffer, memory, 0);
  155. assert(result == VK_SUCCESS);
  156. VkBufferView view;
  157. if (mRequiresView && !staging)
  158. {
  159. mViewCI.buffer = buffer;
  160. result = vkCreateBufferView(vkDevice, &mViewCI, gVulkanAllocator, &view);
  161. assert(result == VK_SUCCESS);
  162. }
  163. else
  164. view = VK_NULL_HANDLE;
  165. mBufferCI.usage = usage; // Restore original usage
  166. return device.getResourceManager().create<VulkanBuffer>(buffer, view, memory);
  167. }
  168. void* VulkanHardwareBuffer::map(UINT32 offset, UINT32 length, GpuLockOptions options, UINT32 deviceIdx, UINT32 queueIdx)
  169. {
  170. if ((offset + length) > mSize)
  171. {
  172. LOGERR("Provided offset(" + toString(offset) + ") + length(" + toString(length) + ") "
  173. "is larger than the buffer " + toString(mSize) + ".");
  174. return nullptr;
  175. }
  176. if (length == 0)
  177. return nullptr;
  178. VulkanBuffer* buffer = mBuffers[deviceIdx];
  179. if (buffer == nullptr)
  180. return nullptr;
  181. mIsMapped = true;
  182. mMappedDeviceIdx = deviceIdx;
  183. mMappedGlobalQueueIdx = queueIdx;
  184. mMappedOffset = offset;
  185. mMappedSize = length;
  186. mMappedLockOptions = options;
  187. VulkanRenderAPI& rapi = static_cast<VulkanRenderAPI&>(RenderAPICore::instance());
  188. VulkanDevice& device = *rapi._getDevice(deviceIdx);
  189. VulkanCommandBufferManager& cbManager = gVulkanCBManager();
  190. GpuQueueType queueType;
  191. UINT32 localQueueIdx = CommandSyncMask::getQueueIdxAndType(queueIdx, queueType);
  192. VkAccessFlags accessFlags;
  193. if (options == GBL_READ_ONLY)
  194. accessFlags = VK_ACCESS_HOST_READ_BIT;
  195. else if (options == GBL_READ_WRITE)
  196. accessFlags = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT;
  197. else
  198. accessFlags = VK_ACCESS_HOST_WRITE_BIT;
  199. // If memory is host visible try mapping it directly
  200. if(mDirectlyMappable)
  201. {
  202. // Check is the GPU currently reading or writing from the buffer
  203. UINT32 useMask = buffer->getUseInfo(VulkanUseFlag::Read | VulkanUseFlag::Write);
  204. // Note: Even if GPU isn't currently using the buffer, but the buffer supports GPU writes, we consider it as
  205. // being used because the write could have completed yet still not visible, so we need to issue a pipeline
  206. // barrier below.
  207. bool isUsedOnGPU = useMask != 0 || mSupportsGPUWrites;
  208. // We're safe to map directly since GPU isn't using the buffer
  209. if (!isUsedOnGPU)
  210. {
  211. // If some CB has an operation queued that will be using the current contents of the buffer, create a new
  212. // buffer so we don't modify the previous use of the buffer
  213. if(buffer->isBound())
  214. {
  215. VulkanBuffer* newBuffer = createBuffer(device, mSize, false, true);
  216. // Copy contents of the current buffer to the new one, unless caller explicitly specifies he doesn't
  217. // care about the current contents
  218. if (options != GBL_WRITE_ONLY_DISCARD)
  219. {
  220. UINT8* src = buffer->map(offset, length);
  221. UINT8* dst = newBuffer->map(offset, length);
  222. memcpy(dst, src, length);
  223. buffer->unmap();
  224. newBuffer->unmap();
  225. }
  226. buffer->destroy();
  227. buffer = newBuffer;
  228. mBuffers[deviceIdx] = buffer;
  229. }
  230. return buffer->map(offset, length);
  231. }
  232. // Caller guarantees he won't touch the same data as the GPU, so just map even though the GPU is using the buffer
  233. if (options == GBL_WRITE_ONLY_NO_OVERWRITE)
  234. return buffer->map(offset, length);
  235. // Caller doesn't care about buffer contents, so just discard the existing buffer and create a new one
  236. if (options == GBL_WRITE_ONLY_DISCARD)
  237. {
  238. buffer->destroy();
  239. buffer = createBuffer(device, mSize, false, true);
  240. mBuffers[deviceIdx] = buffer;
  241. return buffer->map(offset, length);
  242. }
  243. // We need to read the buffer contents
  244. if(options == GBL_READ_ONLY || options == GBL_READ_WRITE)
  245. {
  246. // We need to wait until (potential) read/write operations complete
  247. VulkanTransferBuffer* transferCB = cbManager.getTransferBuffer(deviceIdx, queueType, localQueueIdx);
  248. // Ensure flush() will wait for all queues currently using to the buffer (if any) to finish
  249. // If only reading, wait for all writes to complete, otherwise wait on both writes and reads
  250. if (options == GBL_READ_ONLY)
  251. useMask = buffer->getUseInfo(VulkanUseFlag::Write);
  252. else
  253. useMask = buffer->getUseInfo(VulkanUseFlag::Read | VulkanUseFlag::Write);
  254. transferCB->appendMask(useMask);
  255. // Make any writes visible before mapping
  256. if (mSupportsGPUWrites)
  257. {
  258. // Issue a barrier so :
  259. // - If reading: the device makes the written memory available for read (read-after-write hazard)
  260. // - If writing: ensures our writes properly overlap with GPU writes (write-after-write hazard)
  261. transferCB->memoryBarrier(buffer->getHandle(),
  262. VK_ACCESS_SHADER_WRITE_BIT,
  263. accessFlags,
  264. // Last stages that could have written to the buffer:
  265. VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
  266. VK_PIPELINE_STAGE_HOST_BIT
  267. );
  268. }
  269. // Submit the command buffer and wait until it finishes
  270. transferCB->flush(true);
  271. // If writing and some CB has an operation queued that will be using the current contents of the buffer,
  272. // create a new buffer so we don't modify the previous use of the buffer
  273. if (options == GBL_READ_WRITE && buffer->isBound())
  274. {
  275. VulkanBuffer* newBuffer = createBuffer(device, mSize, false, true);
  276. // Copy contents of the current buffer to the new one
  277. UINT8* src = buffer->map(offset, length);
  278. UINT8* dst = newBuffer->map(offset, length);
  279. memcpy(dst, src, length);
  280. buffer->unmap();
  281. newBuffer->unmap();
  282. buffer->destroy();
  283. buffer = newBuffer;
  284. mBuffers[deviceIdx] = buffer;
  285. }
  286. return buffer->map(offset, length);
  287. }
  288. // Otherwise, we're doing write only, in which case it's best to use the staging buffer to avoid waiting
  289. // and blocking, so fall through
  290. }
  291. // Can't use direct mapping, so use a staging buffer or memory
  292. // We might need to copy the current contents of the buffer to the staging buffer. Even if the user doesn't plan on
  293. // reading, it is still required as we will eventually copy all of the contents back to the original buffer,
  294. // and we can't write potentially uninitialized data. The only exception is when the caller specifies the buffer
  295. // contents should be discarded in which he guarantees he will overwrite the entire locked area with his own
  296. // contents.
  297. bool needRead = options != GBL_WRITE_ONLY_DISCARD_RANGE && options != GBL_WRITE_ONLY_DISCARD;
  298. // See if we can use the cheaper staging memory, rather than a staging buffer
  299. if(!needRead && offset % 4 == 0 && length % 4 == 0 && length <= 65536)
  300. {
  301. mStagingMemory = (UINT8*)bs_alloc(length);
  302. return mStagingMemory;
  303. }
  304. // Create a staging buffer
  305. mStagingBuffer = createBuffer(device, length, true, needRead);
  306. if (needRead)
  307. {
  308. VulkanTransferBuffer* transferCB = cbManager.getTransferBuffer(deviceIdx, queueType, localQueueIdx);
  309. // Similar to above, if buffer supports GPU writes or is currently being written to, we need to wait on any
  310. // potential writes to complete
  311. UINT32 writeUseMask = buffer->getUseInfo(VulkanUseFlag::Write);
  312. if(mSupportsGPUWrites || writeUseMask != 0)
  313. {
  314. // Ensure flush() will wait for all queues currently writing to the buffer (if any) to finish
  315. transferCB->appendMask(writeUseMask);
  316. }
  317. // Queue copy command
  318. buffer->copy(transferCB, mStagingBuffer, offset, 0, length);
  319. // Ensure data written to the staging buffer is visible
  320. transferCB->memoryBarrier(mStagingBuffer->getHandle(),
  321. VK_ACCESS_TRANSFER_WRITE_BIT,
  322. accessFlags,
  323. VK_PIPELINE_STAGE_TRANSFER_BIT,
  324. VK_PIPELINE_STAGE_HOST_BIT
  325. );
  326. // Submit the command buffer and wait until it finishes
  327. transferCB->flush(true);
  328. assert(!buffer->isUsed());
  329. }
  330. return mStagingBuffer->map(0, length);
  331. }
  332. void VulkanHardwareBuffer::unmap()
  333. {
  334. // Possibly map() failed with some error
  335. if (!mIsMapped)
  336. return;
  337. // Note: If we did any writes they need to be made visible to the GPU. However there is no need to execute
  338. // a pipeline barrier because (as per spec) host writes are implicitly visible to the device.
  339. if(mStagingMemory == nullptr && mStagingBuffer == nullptr) // We directly mapped the buffer
  340. {
  341. mBuffers[mMappedDeviceIdx]->unmap();
  342. }
  343. else
  344. {
  345. if(mStagingBuffer != nullptr)
  346. mStagingBuffer->unmap();
  347. bool isWrite = mMappedLockOptions != GBL_READ_ONLY;
  348. // We the caller wrote anything to the staging buffer, we need to upload it back to the main buffer
  349. if(isWrite)
  350. {
  351. VulkanRenderAPI& rapi = static_cast<VulkanRenderAPI&>(RenderAPICore::instance());
  352. VulkanDevice& device = *rapi._getDevice(mMappedDeviceIdx);
  353. VulkanCommandBufferManager& cbManager = gVulkanCBManager();
  354. GpuQueueType queueType;
  355. UINT32 localQueueIdx = CommandSyncMask::getQueueIdxAndType(mMappedGlobalQueueIdx, queueType);
  356. VulkanBuffer* buffer = mBuffers[mMappedDeviceIdx];
  357. VulkanTransferBuffer* transferCB = cbManager.getTransferBuffer(mMappedDeviceIdx, queueType, localQueueIdx);
  358. // If the buffer is used in any way on the GPU, we need to wait for that use to finish before
  359. // we issue our copy
  360. UINT32 useMask = buffer->getUseInfo(VulkanUseFlag::Read | VulkanUseFlag::Write);
  361. bool isNormalWrite = false;
  362. if(useMask != 0) // Buffer is currently used on the GPU
  363. {
  364. // Try to avoid the wait by checking for special write conditions
  365. // Caller guarantees he won't touch the same data as the GPU, so just copy
  366. if (mMappedLockOptions == GBL_WRITE_ONLY_NO_OVERWRITE)
  367. {
  368. // Fall through to copy()
  369. }
  370. // Caller doesn't care about buffer contents, so just discard the existing buffer and create a new one
  371. else if (mMappedLockOptions == GBL_WRITE_ONLY_DISCARD)
  372. {
  373. buffer->destroy();
  374. buffer = createBuffer(device, mSize, false, true);
  375. mBuffers[mMappedDeviceIdx] = buffer;
  376. }
  377. else // Otherwise we have no choice but to issue a dependency between the queues
  378. {
  379. transferCB->appendMask(useMask);
  380. isNormalWrite = true;
  381. }
  382. }
  383. else
  384. isNormalWrite = true;
  385. // Check if the buffer will still be bound somewhere after the CBs using it finish
  386. if (isNormalWrite)
  387. {
  388. UINT32 useCount = buffer->getUseCount();
  389. UINT32 boundCount = buffer->getBoundCount();
  390. bool isBoundWithoutUse = boundCount > useCount;
  391. // If buffer is queued for some operation on a CB, then we need to make a copy of the buffer to
  392. // avoid modifying its use in the previous operation
  393. if (isBoundWithoutUse)
  394. {
  395. VulkanBuffer* newBuffer = createBuffer(device, mSize, false, true);
  396. // Avoid copying original contents if the staging buffer completely covers it
  397. if (mMappedOffset > 0 || mMappedSize != mSize)
  398. {
  399. buffer->copy(transferCB, newBuffer, 0, 0, mSize);
  400. transferCB->getCB()->registerResource(buffer, VK_ACCESS_TRANSFER_READ_BIT, VulkanUseFlag::Read);
  401. }
  402. buffer->destroy();
  403. buffer = newBuffer;
  404. mBuffers[mMappedDeviceIdx] = buffer;
  405. }
  406. }
  407. // Queue copy/update command
  408. if (mStagingBuffer != nullptr)
  409. {
  410. mStagingBuffer->copy(transferCB, buffer, 0, mMappedOffset, mMappedSize);
  411. transferCB->getCB()->registerResource(mStagingBuffer, VK_ACCESS_TRANSFER_READ_BIT, VulkanUseFlag::Read);
  412. }
  413. else // Staging memory
  414. {
  415. buffer->update(transferCB, mStagingMemory, mMappedOffset, mMappedSize);
  416. }
  417. transferCB->getCB()->registerResource(buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VulkanUseFlag::Write);
  418. // We don't actually flush the transfer buffer here since it's an expensive operation, but it's instead
  419. // done automatically before next "normal" command buffer submission.
  420. }
  421. if (mStagingBuffer != nullptr)
  422. {
  423. mStagingBuffer->destroy();
  424. mStagingBuffer = nullptr;
  425. }
  426. if(mStagingMemory != nullptr)
  427. {
  428. bs_free(mStagingMemory);
  429. mStagingMemory = nullptr;
  430. }
  431. }
  432. mIsMapped = false;
  433. }
  434. void VulkanHardwareBuffer::copyData(HardwareBuffer& srcBuffer, UINT32 srcOffset,
  435. UINT32 dstOffset, UINT32 length, bool discardWholeBuffer, UINT32 queueIdx)
  436. {
  437. if ((dstOffset + length) > mSize)
  438. {
  439. LOGERR("Provided offset(" + toString(dstOffset) + ") + length(" + toString(length) + ") "
  440. "is larger than the destination buffer " + toString(mSize) + ". Copy operation aborted.");
  441. return;
  442. }
  443. if ((srcOffset + length) > srcBuffer.getSize())
  444. {
  445. LOGERR("Provided offset(" + toString(srcOffset) + ") + length(" + toString(length) + ") "
  446. "is larger than the source buffer " + toString(srcBuffer.getSize()) + ". Copy operation aborted.");
  447. return;
  448. }
  449. VulkanHardwareBuffer& vkSource = static_cast<VulkanHardwareBuffer&>(srcBuffer);
  450. VulkanRenderAPI& rapi = static_cast<VulkanRenderAPI&>(RenderAPICore::instance());
  451. VulkanCommandBufferManager& cbManager = gVulkanCBManager();
  452. GpuQueueType queueType;
  453. UINT32 localQueueIdx = CommandSyncMask::getQueueIdxAndType(queueIdx, queueType);
  454. // Perform copy on every device that has both buffers
  455. for (UINT32 i = 0; i < BS_MAX_DEVICES; i++)
  456. {
  457. VulkanBuffer* src = vkSource.mBuffers[i];
  458. VulkanBuffer* dst = mBuffers[i];
  459. if (src == nullptr || dst == nullptr)
  460. continue;
  461. VulkanDevice& device = *rapi._getDevice(i);
  462. VulkanTransferBuffer* transferCB = cbManager.getTransferBuffer(i, queueType, localQueueIdx);
  463. // If either source or destination buffer is currently being written to do need to sync the copy operation so
  464. // it executes after both are done
  465. // If destination is being used on the GPU we need to wait until it finishes before writing to it
  466. UINT32 dstUseMask = dst->getUseInfo(VulkanUseFlag::Read | VulkanUseFlag::Write);
  467. // If discard is enabled and destination is used, instead of waiting just discard the existing buffer and make a new one
  468. bool isNormalWrite = true;
  469. if(dstUseMask != 0 && discardWholeBuffer)
  470. {
  471. dst->destroy();
  472. dst = createBuffer(device, mSize, false, true);
  473. mBuffers[i] = dst;
  474. dstUseMask = 0;
  475. isNormalWrite = false;
  476. }
  477. // If source buffer is being written to on the GPU we need to wait until it finishes, before executing copy
  478. UINT32 srcUseMask = src->getUseInfo(VulkanUseFlag::Write);
  479. // Wait if anything is using the buffers
  480. if(dstUseMask != 0 || srcUseMask != 0)
  481. transferCB->appendMask(dstUseMask | srcUseMask);
  482. // Check if the destination buffer will still be bound somewhere after the CBs using it finish
  483. if (isNormalWrite)
  484. {
  485. UINT32 useCount = dst->getUseCount();
  486. UINT32 boundCount = dst->getBoundCount();
  487. bool isBoundWithoutUse = boundCount > useCount;
  488. // If destination buffer is queued for some operation on a CB (ignoring the ones we're waiting for), then we
  489. // need to make a copy of the buffer to avoid modifying its use in the previous operation
  490. if (isBoundWithoutUse)
  491. {
  492. VulkanBuffer* newBuffer = createBuffer(device, mSize, false, true);
  493. // Avoid copying original contents if the copy completely covers it
  494. if (dstOffset > 0 || length != mSize)
  495. {
  496. dst->copy(transferCB, newBuffer, 0, 0, mSize);
  497. transferCB->getCB()->registerResource(dst, VK_ACCESS_TRANSFER_READ_BIT, VulkanUseFlag::Read);
  498. }
  499. dst->destroy();
  500. dst = newBuffer;
  501. mBuffers[i] = dst;
  502. }
  503. }
  504. src->copy(transferCB, dst, srcOffset, dstOffset, length);
  505. // Notify the command buffer that these resources are being used on it
  506. transferCB->getCB()->registerResource(src, VK_ACCESS_TRANSFER_READ_BIT, VulkanUseFlag::Read);
  507. transferCB->getCB()->registerResource(dst, VK_ACCESS_TRANSFER_WRITE_BIT, VulkanUseFlag::Write);
  508. // We don't actually flush the transfer buffer here since it's an expensive operation, but it's instead
  509. // done automatically before next "normal" command buffer submission.
  510. }
  511. }
  512. void VulkanHardwareBuffer::readData(UINT32 offset, UINT32 length, void* dest, UINT32 deviceIdx, UINT32 queueIdx)
  513. {
  514. void* lockedData = lock(offset, length, GBL_READ_ONLY, deviceIdx, queueIdx);
  515. memcpy(dest, lockedData, length);
  516. unlock();
  517. }
  518. void VulkanHardwareBuffer::writeData(UINT32 offset, UINT32 length, const void* source, BufferWriteType writeFlags,
  519. UINT32 queueIdx)
  520. {
  521. GpuLockOptions lockOptions = GBL_WRITE_ONLY_DISCARD_RANGE;
  522. if (writeFlags == BTW_NO_OVERWRITE)
  523. lockOptions = GBL_WRITE_ONLY_NO_OVERWRITE;
  524. else if (writeFlags == BWT_DISCARD)
  525. lockOptions = GBL_WRITE_ONLY_DISCARD;
  526. // Write to every device
  527. for (UINT32 i = 0; i < BS_MAX_DEVICES; i++)
  528. {
  529. if (mBuffers[i] == nullptr)
  530. continue;
  531. void* lockedData = lock(offset, length, lockOptions, i, queueIdx);
  532. memcpy(lockedData, source, length);
  533. unlock();
  534. }
  535. }
  536. }