65 lines
1.9 KiB
C++
65 lines
1.9 KiB
C++
//
|
|
// Created by atdunbg on 2026/9/20.
|
|
//
|
|
|
|
#include <Engine/Vulkan/Buffer.h>
|
|
#include <Engine/Vulkan/Device.h>
|
|
#include <Engine/Vulkan/MemoryAllocator.h>
|
|
#include <Engine/Core/Log.h>
|
|
|
|
#include <cstring>
|
|
|
|
#include "Engine/Core/Stats.h"
|
|
|
|
namespace Engine {
|
|
|
|
Buffer::Buffer(Device& device, MemoryAllocator& allocator,
|
|
vk::DeviceSize size, vk::BufferUsageFlags usage,
|
|
vk::MemoryPropertyFlags memProps)
|
|
: m_Device(device), m_Allocator(allocator) , m_Size(size)
|
|
{
|
|
vk::BufferCreateInfo bufferInfo;
|
|
bufferInfo.setSize(size)
|
|
.setUsage(usage)
|
|
.setSharingMode(vk::SharingMode::eExclusive);
|
|
|
|
m_Buffer = m_Device.GetDevice().createBuffer(bufferInfo);
|
|
|
|
auto reqs = m_Device.GetDevice().getBufferMemoryRequirements(m_Buffer);
|
|
auto alloc = allocator.Allocate(reqs, memProps);
|
|
|
|
m_Memory = alloc.Memory;
|
|
m_Offset = alloc.Offset;
|
|
m_MappedPtr = alloc.MappedPtr;
|
|
|
|
m_Device.GetDevice().bindBufferMemory(m_Buffer, m_Memory, m_Offset);
|
|
|
|
m_Allocation = alloc; // 成员变量,保存起来
|
|
|
|
STATS.AddBuffer(m_Size);
|
|
}
|
|
|
|
Buffer::~Buffer()
|
|
{
|
|
m_Device.GetDevice().destroyBuffer(m_Buffer);
|
|
m_Allocator.Free(m_Allocation);
|
|
STATS.RemoveBuffer(m_Size);
|
|
}
|
|
|
|
void Buffer::Upload(const void* data, vk::DeviceSize size, vk::DeviceSize offset)
|
|
{
|
|
if (!m_MappedPtr) {
|
|
ENGINE_ERROR("Buffer::Upload: buffer is not host visible");
|
|
return;
|
|
}
|
|
memcpy(static_cast<char*>(m_MappedPtr) + offset, data, size);
|
|
|
|
// flush 整个内存块,避免对齐问题
|
|
vk::MappedMemoryRange range;
|
|
range.setMemory(m_Memory)
|
|
.setOffset(0)
|
|
.setSize(VK_WHOLE_SIZE);
|
|
|
|
m_Device.GetDevice().flushMappedMemoryRanges(range);
|
|
}
|
|
} // namespace Engine
|