我在我的代码中发现一个错误,该错误在某些情况下使用登台缓冲区导致网格数据损坏。我有:
临时网格数据
具有一定大小的临时缓冲区,命令缓冲区和memcpy可以同时使用该临时缓冲区,但一次不能使用同一段。
缓冲区分配器,提供适当的顶点索引缓冲区的一部分,其中网状数据通过vkCmdCopyBuffer从暂存转移。缓冲区包含许多针对不同网格划分的分段。
当我同时通过命令缓冲区和memcpy使用登台缓冲区时,网格数据写入不正确(变得被覆盖/损坏),甚至严重写入的问题会导致VK_ERROR_DEVICE_LOST。
https://imgur.com/8p53SUW“正确的网格”
https://imgur.com/plJ8V0v“破碎的网格”
[[nodiscard]] static Result writeMeshBuffer(TransferData &data, GpuMesh &buffer)
{
Result result; using namespace vkw;
auto &mesh = buffer.source;
size_t vSize = mesh.vertices_count * mesh.vertex_size;
size_t iSize = mesh.indices_count * mesh.index_size;
size_t mesh_size = vSize + iSize;
auto &staging_offset = data.stagingData.buffer_offset_unused;
// write data to staging buffer
{
// guaranteed that mesh_size will less or equal than staging buffer size
//FIXME false condition generate broken meshes somehow
bool is_wait_before = mesh_size > TransferStagingData::BUFFER_SIZE - staging_offset;
//will work correctly:
//bool is_wait_before = true;
if (is_wait_before) // if we need more memory on staging buffer than not used already
{
result = data.wait_transfer();
if (result != VK_SUCCESS)
return result;
staging_offset = 0;
}
uint8_t *pMemory = static_cast<uint8_t*>(data.stagingData.pMemory) + staging_offset;
memcpy(pMemory, mesh.vertices.pX, vSize);
memcpy(pMemory + vSize, mesh.indices.pXX, iSize);
if (not is_wait_before)
{
result = data.wait_transfer();
if (result != VK_SUCCESS)
return result;
}
}
// write data from staging buffer to mesh buffer
{
auto cmd_cpy_buff = [](CommandBuffer cmd, BufferCopy copy, Offsets offsets, DeviceSizeT size)
{
cmd.cmd_copy_buffer(copy, offsets, size);
};
// SRC DST
BufferCopy copy = { data.stagingData.buffer, buffer.info.buffer };
Offsets offsets = { staging_offset, buffer.info.region.offset };
result = data.transfer.prepare(cmd_cpy_buff, data.transfer.cmd_buffer, copy, offsets, mesh_size);
if (result != VK_SUCCESS)
return result;
data.reset_fence();
result = data.transfer.submit({&data.transfer.cmd_buffer,1},{}, {}, {}, data.transferFence);
if (result != VK_SUCCESS)
return result;
}
// save usused offset to data.stagingData.buffer_offset_unused;
staging_offset = staging_offset == 0 ? mesh_size : 0;
return result;
}
如果我不能使用这种登台缓冲区,那为什么呢?
如果我有错误,请在哪里找到idk。
答案 0 :(得分:1)
问题是
staging_offset = staging_offset == 0 ? mesh_size : 0;
需要更改
staging_offset = staging_offset == 0 ? TransferStagingData::BUFFER_SIZE - mesh_size : 0;
更改后,所有功能均正常工作。