Debian Codegraph @

Sources/nCine/Graphics/RHI/Vulkan/VulkanTexture.cpp

raw
1 #include "VulkanTexture.h"
2 #include "VulkanDevice.h"
3 #include "VulkanCommon.h"
4
5 #include <cstring>
6
7 namespace nCine::RHI::Vulkan
8 {
9 namespace
10 {
11 // Copies one packed row into the store, expanding a narrower source (RGB8) to a wider store
12 // (RGBA8) by filling the extra channel with 255 (opaque). A same-width copy is a plain memcpy.
13 void CopyExpandRow(std::uint8_t* dst, std::int32_t dstBpp, const std::uint8_t* src, std::int32_t srcBpp, std::int32_t width)
14 {
15 if (srcBpp == dstBpp) {
16 std::memcpy(dst, src, std::size_t(width) * std::size_t(dstBpp));
17 return;
18 }
19 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
20 for (std::int32_t x = 0; x < width; x++) {
21 std::int32_t c = 0;
22 for (; c < shared; c++) {
23 dst[x * dstBpp + c] = src[x * srcBpp + c];
24 }
25 for (; c < dstBpp; c++) {
26 dst[x * dstBpp + c] = 255;
27 }
28 }
29 }
30
31 VkFormat MapVkFormat(PixelFormat format)
32 {
33 switch (format) {
34 case PixelFormat::RGBA8: return VK_FORMAT_R8G8B8A8_UNORM;
35 case PixelFormat::RGBA16F: return VK_FORMAT_R16G16B16A16_SFLOAT;
36 case PixelFormat::RGBA32F: return VK_FORMAT_R32G32B32A32_SFLOAT;
37 default: return VK_FORMAT_R8G8B8A8_UNORM; // the store is promoted to RGBA8 for R8/RG8/RGB8
38 }
39 }
40
41 VkComponentSwizzle MapSwizzle(SwizzleChannel channel, VkComponentSwizzle identity)
42 {
43 switch (channel) {
44 case SwizzleChannel::Red: return VK_COMPONENT_SWIZZLE_R;
45 case SwizzleChannel::Green: return VK_COMPONENT_SWIZZLE_G;
46 case SwizzleChannel::Blue: return VK_COMPONENT_SWIZZLE_B;
47 case SwizzleChannel::Alpha: return VK_COMPONENT_SWIZZLE_A;
48 case SwizzleChannel::Zero: return VK_COMPONENT_SWIZZLE_ZERO;
49 case SwizzleChannel::One: return VK_COMPONENT_SWIZZLE_ONE;
50 default: return identity;
51 }
52 }
53 }
54
55 std::uint32_t VulkanTexture::_nextHandle = 1;
56
57 VulkanTexture::VulkanTexture(TextureTarget target)
58 : _handle(_nextHandle++), _target(target), _format(PixelFormat::Unknown), _uploadFormat(PixelFormat::Unknown),
59 _width(0), _height(0), _strideBytes(0),
60 _minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), _wrap(SamplerWrapping::ClampToEdge),
61 _textureUnit(0), _isRenderTarget(false),
62 _gpuImage(0), _gpuMemory(0), _gpuView(0), _gpuSampler(0),
63 _currentLayout(VK_IMAGE_LAYOUT_UNDEFINED), _gpuFormat(VK_FORMAT_R8G8B8A8_UNORM),
64 _contentsDirty(false), _viewDirty(false), _hasCpuData(false),
65 _samplerFilter(nCine::SamplerFilter::Unknown), _samplerWrap(SamplerWrapping::Unknown)
66 {
67 _swizzle[0] = SwizzleChannel::Red;
68 _swizzle[1] = SwizzleChannel::Green;
69 _swizzle[2] = SwizzleChannel::Blue;
70 _swizzle[3] = SwizzleChannel::Alpha;
71 }
72
73 VulkanTexture::~VulkanTexture()
74 {
75 // Unbind from the device first so a later draw can't dereference this freed texture via _boundTextures
76 VulkanDevice::UnbindTexture(this);
77 ReleaseGpu();
78 }
79
80 void VulkanTexture::ReleaseGpu() const
81 {
82 // Defer the GPU frees instead of destroying immediately: an in-flight frame's command buffer or descriptor
83 // set may still reference this image / view / sampler (up to MaxFramesInFlight frames run concurrently), so
84 // freeing now would be a GPU use-after-free that loses the device (the level->menu freeze). The device frees
85 // them once every frame that could reference them has completed; VkEnqueueDestroy no-ops if the device is
86 // already gone (teardown) - vkDestroyDevice implicitly destroys these handles then.
87 VkEnqueueDestroy(VkDeferredResource::ImageView, _gpuView);
88 VkEnqueueDestroy(VkDeferredResource::Sampler, _gpuSampler);
89 VkEnqueueDestroy(VkDeferredResource::Image, _gpuImage);
90 VkEnqueueDestroy(VkDeferredResource::DeviceMemory, _gpuMemory);
91 _gpuView = 0;
92 _gpuSampler = 0;
93 _gpuImage = 0;
94 _gpuMemory = 0;
95 _currentLayout = VK_IMAGE_LAYOUT_UNDEFINED;
96 }
97
98 std::int32_t VulkanTexture::BytesPerPixel(PixelFormat format)
99 {
100 switch (format) {
101 case PixelFormat::R8: return 1;
102 case PixelFormat::RG8: return 2;
103 case PixelFormat::RGB8: return 3;
104 case PixelFormat::RGBA8: return 4;
105 default: return 0;
106 }
107 }
108
109 void VulkanTexture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height)
110 {
111 // Promote the narrower runtime formats (RGB8 render targets, palette-index R8 / RG8) to an RGBA8 store
112 _uploadFormat = format;
113 _format = (format == PixelFormat::RGB8 || format == PixelFormat::R8 || format == PixelFormat::RG8) ? PixelFormat::RGBA8 : format;
114 _width = width;
115 _height = height;
116 const std::int32_t bpp = BytesPerPixel(_format);
117 _strideBytes = width * bpp;
118 _pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0));
119 // The size/format changed, so the GPU image must be rebuilt on the next bind
120 ReleaseGpu();
121 _contentsDirty = true;
122 _viewDirty = true;
123 }
124
125 void VulkanTexture::EnsureGpu() const
126 {
127 VkDevice device = VkDeviceHandle();
128 if (device == VK_NULL_HANDLE || _width <= 0 || _height <= 0) {
129 return;
130 }
131
132 if (_gpuImage == 0) {
133 _gpuFormat = std::uint32_t(MapVkFormat(_format));
134 VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT;
135 if (_isRenderTarget) {
136 usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
137 } else {
138 usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
139 }
140
141 VkImageCreateInfo ici = {};
142 ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
143 ici.imageType = VK_IMAGE_TYPE_2D;
144 ici.format = VkFormat(_gpuFormat);
145 ici.extent = { std::uint32_t(_width), std::uint32_t(_height), 1 };
146 ici.mipLevels = 1;
147 ici.arrayLayers = 1;
148 ici.samples = VK_SAMPLE_COUNT_1_BIT;
149 ici.tiling = VK_IMAGE_TILING_OPTIMAL;
150 ici.usage = usage;
151 ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
152 ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
153 VkImage image = VK_NULL_HANDLE;
154 if (vkCreateImage(device, &ici, nullptr, &image) != VK_SUCCESS) {
155 return;
156 }
157
158 VkMemoryRequirements req;
159 vkGetImageMemoryRequirements(device, image, &req);
160 const std::uint32_t memType = VkFindMemoryType(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
161 VkMemoryAllocateInfo mai = {};
162 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
163 mai.allocationSize = req.size;
164 mai.memoryTypeIndex = memType;
165 VkDeviceMemory memory = VK_NULL_HANDLE;
166 if (memType == UINT32_MAX || vkAllocateMemory(device, &mai, nullptr, &memory) != VK_SUCCESS) {
167 vkDestroyImage(device, image, nullptr);
168 return;
169 }
170 vkBindImageMemory(device, image, memory, 0);
171 _gpuImage = reinterpret_cast<std::uint64_t>(image);
172 _gpuMemory = reinterpret_cast<std::uint64_t>(memory);
173 _currentLayout = VK_IMAGE_LAYOUT_UNDEFINED;
174 _viewDirty = true;
175
176 if (_isRenderTarget) {
177 // Bring the fresh attachment to COLOR_ATTACHMENT_OPTIMAL so the device's LOAD-op render pass
178 // (initialLayout == COLOR_ATTACHMENT_OPTIMAL) is valid on first use; contents stay undefined
179 // until the engine clears / overwrites them.
180 VkCommandBuffer cmd = VkBeginOneTimeCommands();
181 if (cmd != VK_NULL_HANDLE) {
182 VkImageMemoryBarrier b = {};
183 b.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
184 b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
185 b.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
186 b.srcAccessMask = 0;
187 b.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
188 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
189 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
190 b.image = image;
191 b.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
192 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
193 0, 0, nullptr, 0, nullptr, 1, &b);
194 VkEndOneTimeCommands(cmd);
195 _currentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
196 }
197 }
198 }
199
200 // NOTE: CPU texel uploads are NOT recorded here anymore. EnsureGpu() only materializes the image / view /
201 // sampler; the staging copy is recorded into the current FRAME's command buffer by RecordStreamingUpload()
202 // (driven from the device's pre-draw phase, outside any render pass), so per-frame texture streaming (the
203 // palette) no longer forces a vkQueueWaitIdle stall every frame. _contentsDirty stays set until then.
204
205 if (_viewDirty || _gpuView == 0) {
206 if (_gpuView != 0) {
207 // Defer: an in-flight frame's descriptor set may still sample through the old view (see ReleaseGpu)
208 VkEnqueueDestroy(VkDeferredResource::ImageView, _gpuView);
209 _gpuView = 0;
210 }
211 VkImageViewCreateInfo ivci = {};
212 ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
213 ivci.image = reinterpret_cast<VkImage>(_gpuImage);
214 ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
215 ivci.format = VkFormat(_gpuFormat);
216 // The sampling swizzle is applied here (no texel baking) - e.g. RG8 palette textures map A<-Green
217 ivci.components.r = MapSwizzle(_swizzle[0], VK_COMPONENT_SWIZZLE_R);
218 ivci.components.g = MapSwizzle(_swizzle[1], VK_COMPONENT_SWIZZLE_G);
219 ivci.components.b = MapSwizzle(_swizzle[2], VK_COMPONENT_SWIZZLE_B);
220 ivci.components.a = MapSwizzle(_swizzle[3], VK_COMPONENT_SWIZZLE_A);
221 ivci.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
222 VkImageView view = VK_NULL_HANDLE;
223 if (vkCreateImageView(device, &ivci, nullptr, &view) == VK_SUCCESS) {
224 _gpuView = reinterpret_cast<std::uint64_t>(view);
225 }
226 _viewDirty = false;
227 }
228
229 if (_gpuSampler == 0 || _samplerFilter != _magFilter || _samplerWrap != _wrap) {
230 if (_gpuSampler != 0) {
231 // Defer: an in-flight frame's descriptor set may still use the old sampler (see ReleaseGpu)
232 VkEnqueueDestroy(VkDeferredResource::Sampler, _gpuSampler);
233 _gpuSampler = 0;
234 }
235 const bool linear = (_magFilter == nCine::SamplerFilter::Linear ||
236 _magFilter == nCine::SamplerFilter::LinearMipmapNearest || _magFilter == nCine::SamplerFilter::LinearMipmapLinear);
237 VkSamplerAddressMode address;
238 switch (_wrap) {
239 case SamplerWrapping::Repeat: address = VK_SAMPLER_ADDRESS_MODE_REPEAT; break;
240 case SamplerWrapping::MirroredRepeat: address = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; break;
241 default: address = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; break;
242 }
243 VkSamplerCreateInfo sci = {};
244 sci.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
245 sci.magFilter = linear ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
246 sci.minFilter = linear ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
247 sci.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
248 sci.addressModeU = address;
249 sci.addressModeV = address;
250 sci.addressModeW = address;
251 sci.maxLod = VK_LOD_CLAMP_NONE;
252 sci.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
253 VkSampler sampler = VK_NULL_HANDLE;
254 if (vkCreateSampler(device, &sci, nullptr, &sampler) == VK_SUCCESS) {
255 _gpuSampler = reinterpret_cast<std::uint64_t>(sampler);
256 }
257 _samplerFilter = _magFilter;
258 _samplerWrap = _wrap;
259 }
260 }
261
262 void VulkanTexture::RecordStreamingUpload(std::uint64_t cmdBuffer) const
263 {
264 VkDevice device = VkDeviceHandle();
265 if (device == VK_NULL_HANDLE || cmdBuffer == 0) {
266 return;
267 }
268 EnsureGpu(); // materialize the image / view / sampler (no upload)
269 if (_gpuImage == 0 || !_contentsDirty || !_hasCpuData || _isRenderTarget || _pixels.empty()) {
270 return;
271 }
272 VkCommandBuffer cmd = reinterpret_cast<VkCommandBuffer>(cmdBuffer);
273 VkImage image = reinterpret_cast<VkImage>(_gpuImage);
274
275 // Host-visible staging buffer holding the whole level-0 store; the device frees it once the frame's fence signals
276 VkBuffer staging = VK_NULL_HANDLE;
277 VkDeviceMemory stagingMem = VK_NULL_HANDLE;
278 VkBufferCreateInfo bci = {};
279 bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
280 bci.size = _pixels.size();
281 bci.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
282 bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
283 if (vkCreateBuffer(device, &bci, nullptr, &staging) != VK_SUCCESS) {
284 return;
285 }
286 VkMemoryRequirements req;
287 vkGetBufferMemoryRequirements(device, staging, &req);
288 const std::uint32_t memType = VkFindMemoryType(req.memoryTypeBits,
289 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
290 VkMemoryAllocateInfo mai = {};
291 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
292 mai.allocationSize = req.size;
293 mai.memoryTypeIndex = memType;
294 if (memType == UINT32_MAX || vkAllocateMemory(device, &mai, nullptr, &stagingMem) != VK_SUCCESS) {
295 vkDestroyBuffer(device, staging, nullptr);
296 return;
297 }
298 vkBindBufferMemory(device, staging, stagingMem, 0);
299 void* mapped = nullptr;
300 vkMapMemory(device, stagingMem, 0, VK_WHOLE_SIZE, 0, &mapped);
301 std::memcpy(mapped, _pixels.data(), _pixels.size());
302 vkUnmapMemory(device, stagingMem);
303
304 // Barrier into TRANSFER_DST. On a re-upload of a texture the OTHER in-flight frame sampled
305 // (_currentLayout == SHADER_READ_ONLY), the source scope is FRAGMENT_SHADER / SHADER_READ so this write
306 // waits (via queue submission order) for that frame's samples - the shared-image WAR guard for streaming
307 // textures like the palette. A fresh image is UNDEFINED (its contents are discarded, no wait needed).
308 const VkImageLayout oldLayout = VkImageLayout(_currentLayout);
309 VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
310 VkAccessFlags srcAccess = 0;
311 if (oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
312 srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
313 srcAccess = VK_ACCESS_SHADER_READ_BIT;
314 }
315 VkImageMemoryBarrier toDst = {};
316 toDst.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
317 toDst.oldLayout = oldLayout;
318 toDst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
319 toDst.srcAccessMask = srcAccess;
320 toDst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
321 toDst.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
322 toDst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
323 toDst.image = image;
324 toDst.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
325 vkCmdPipelineBarrier(cmd, srcStage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toDst);
326
327 VkBufferImageCopy region = {};
328 region.bufferOffset = 0;
329 region.bufferRowLength = 0;
330 region.bufferImageHeight = 0;
331 region.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
332 region.imageOffset = { 0, 0, 0 };
333 region.imageExtent = { std::uint32_t(_width), std::uint32_t(_height), 1 };
334 vkCmdCopyBufferToImage(cmd, staging, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
335
336 VkImageMemoryBarrier toRead = {};
337 toRead.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
338 toRead.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
339 toRead.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
340 toRead.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
341 toRead.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
342 toRead.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
343 toRead.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
344 toRead.image = image;
345 toRead.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
346 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
347 0, 0, nullptr, 0, nullptr, 1, &toRead);
348
349 _currentLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
350 _contentsDirty = false;
351 VkRegisterFrameStaging(reinterpret_cast<std::uint64_t>(staging), reinterpret_cast<std::uint64_t>(stagingMem));
352 }
353
354 std::uint64_t VulkanTexture::GpuImage() const
355 {
356 EnsureGpu();
357 return _gpuImage;
358 }
359
360 std::uint64_t VulkanTexture::GpuView() const
361 {
362 EnsureGpu();
363 return _gpuView;
364 }
365
366 std::uint64_t VulkanTexture::GpuSampler() const
367 {
368 EnsureGpu();
369 return _gpuSampler;
370 }
371
372 std::uint32_t VulkanTexture::GpuFormat() const
373 {
374 return _gpuFormat;
375 }
376
377 bool VulkanTexture::Bind(std::uint32_t textureUnit) const
378 {
379 _textureUnit = textureUnit;
380 VulkanDevice::BindTexture(textureUnit, this);
381 return true;
382 }
383
384 bool VulkanTexture::Unbind() const
385 {
386 VulkanDevice::BindTexture(_textureUnit, nullptr);
387 return true;
388 }
389
390 bool VulkanTexture::Unbind(std::uint32_t textureUnit)
391 {
392 VulkanDevice::BindTexture(textureUnit, nullptr);
393 return true;
394 }
395
396 void VulkanTexture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data)
397 {
398 static_cast<void>(bgr);
399 if (level != 0) {
400 return;
401 }
402 Allocate(format, width, height);
403 if (data != nullptr && !_pixels.empty()) {
404 _hasCpuData = true;
405 const std::int32_t srcBpp = BytesPerPixel(format);
406 const std::int32_t dstBpp = BytesPerPixel(_format);
407 if (srcBpp == dstBpp) {
408 std::memcpy(_pixels.data(), data, _pixels.size());
409 } else {
410 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
411 for (std::int32_t y = 0; y < _height; y++) {
412 CopyExpandRow(_pixels.data() + std::size_t(y) * _strideBytes,
413 dstBpp, src + std::size_t(y) * std::size_t(_width) * srcBpp, srcBpp, _width);
414 }
415 }
416 }
417 }
418
419 void VulkanTexture::TexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, bool bgr, const void* data)
420 {
421 static_cast<void>(bgr);
422 if (level != 0 || data == nullptr || _pixels.empty()) {
423 return;
424 }
425 _hasCpuData = true;
426 _contentsDirty = true;
427 const std::int32_t srcBpp = BytesPerPixel(format);
428 const std::int32_t dstBpp = BytesPerPixel(_format);
429 for (std::int32_t y = 0; y < height; y++) {
430 const std::int32_t dstY = yoffset + y;
431 if (dstY < 0 || dstY >= _height) {
432 continue;
433 }
434 std::int32_t dstX = xoffset;
435 std::int32_t copyW = width;
436 std::int32_t srcX0 = 0;
437 if (dstX < 0) {
438 srcX0 = -dstX;
439 copyW += dstX;
440 dstX = 0;
441 }
442 if (dstX + copyW > _width) {
443 copyW = _width - dstX;
444 }
445 if (copyW <= 0) {
446 continue;
447 }
448 const std::uint8_t* srcRow = static_cast<const std::uint8_t*>(data) + std::size_t(y) * std::size_t(width) * srcBpp + std::size_t(srcX0) * srcBpp;
449 std::uint8_t* dstRow = _pixels.data() + std::size_t(dstY) * _strideBytes + std::size_t(dstX) * dstBpp;
450 CopyExpandRow(dstRow, dstBpp, srcRow, srcBpp, copyW);
451 }
452 }
453
454 void VulkanTexture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height)
455 {
456 static_cast<void>(levels);
457 Allocate(format, width, height);
458 }
459
460 void VulkanTexture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data)
461 {
462 static_cast<void>(level);
463 static_cast<void>(format);
464 static_cast<void>(width);
465 static_cast<void>(height);
466 static_cast<void>(imageSize);
467 static_cast<void>(data);
468 }
469
470 void VulkanTexture::CompressedTexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, std::int32_t imageSize, const void* data)
471 {
472 static_cast<void>(level);
473 static_cast<void>(xoffset);
474 static_cast<void>(yoffset);
475 static_cast<void>(width);
476 static_cast<void>(height);
477 static_cast<void>(format);
478 static_cast<void>(imageSize);
479 static_cast<void>(data);
480 }
481
482 void VulkanTexture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels)
483 {
484 static_cast<void>(level);
485 static_cast<void>(format);
486 static_cast<void>(bgr);
487 if (pixels == nullptr) {
488 return;
489 }
490
491 // A render target's contents only exist on the GPU (draws never touch the host store), so read them
492 // back through a staging buffer with a one-time submit + queue-idle wait. Readback is a screenshot-rate
493 // operation, so the synchronous wait is acceptable.
494 if (_isRenderTarget && _gpuImage != 0 && _width > 0 && _height > 0 && vkCmdCopyImageToBuffer != nullptr) {
495 VkDevice device = VkDeviceHandle();
496 if (device != VK_NULL_HANDLE) {
497 const VkDeviceSize byteSize = VkDeviceSize(_width) * VkDeviceSize(_height) * 4;
498 VkBuffer staging = VK_NULL_HANDLE;
499 VkDeviceMemory stagingMem = VK_NULL_HANDLE;
500 VkBufferCreateInfo bci = {};
501 bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
502 bci.size = byteSize;
503 bci.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
504 bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
505 if (vkCreateBuffer(device, &bci, nullptr, &staging) == VK_SUCCESS) {
506 VkMemoryRequirements req;
507 vkGetBufferMemoryRequirements(device, staging, &req);
508 const std::uint32_t memType = VkFindMemoryType(req.memoryTypeBits,
509 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
510 VkMemoryAllocateInfo mai = {};
511 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
512 mai.allocationSize = req.size;
513 mai.memoryTypeIndex = memType;
514 if (memType != UINT32_MAX && vkAllocateMemory(device, &mai, nullptr, &stagingMem) == VK_SUCCESS) {
515 vkBindBufferMemory(device, staging, stagingMem, 0);
516
517 VkCommandBuffer cmd = VkBeginOneTimeCommands();
518 if (cmd != VK_NULL_HANDLE) {
519 VkImage image = reinterpret_cast<VkImage>(_gpuImage);
520 const VkImageLayout oldLayout = VkImageLayout(_currentLayout);
521
522 // Conservative full-scope barriers: this is a synchronous, out-of-frame submit
523 VkImageMemoryBarrier toSrc = {};
524 toSrc.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
525 toSrc.oldLayout = oldLayout;
526 toSrc.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
527 toSrc.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
528 toSrc.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
529 toSrc.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
530 toSrc.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
531 toSrc.image = image;
532 toSrc.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
533 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
534 0, 0, nullptr, 0, nullptr, 1, &toSrc);
535
536 VkBufferImageCopy region = {};
537 region.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
538 region.imageExtent = { std::uint32_t(_width), std::uint32_t(_height), 1 };
539 vkCmdCopyImageToBuffer(cmd, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, staging, 1, &region);
540
541 VkImageMemoryBarrier restore = toSrc;
542 restore.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
543 restore.newLayout = oldLayout;
544 restore.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
545 restore.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
546 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
547 0, 0, nullptr, 0, nullptr, 1, &restore);
548
549 VkEndOneTimeCommands(cmd); // submits + waits for the queue to go idle
550
551 void* mapped = nullptr;
552 if (vkMapMemory(device, stagingMem, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS) {
553 std::memcpy(pixels, mapped, std::size_t(byteSize));
554 vkUnmapMemory(device, stagingMem);
555 vkDestroyBuffer(device, staging, nullptr);
556 vkFreeMemory(device, stagingMem, nullptr);
557 return;
558 }
559 }
560 vkFreeMemory(device, stagingMem, nullptr);
561 }
562 vkDestroyBuffer(device, staging, nullptr);
563 }
564 }
565 }
566
567 if (!_pixels.empty()) {
568 std::memcpy(pixels, _pixels.data(), _pixels.size());
569 }
570 }
571
572 void VulkanTexture::SetMinFiltering(nCine::SamplerFilter filter)
573 {
574 _minFilter = filter;
575 }
576
577 void VulkanTexture::SetMagFiltering(nCine::SamplerFilter filter)
578 {
579 _magFilter = filter;
580 }
581
582 void VulkanTexture::SetWrap(SamplerWrapping wrap)
583 {
584 _wrap = wrap;
585 }
586
587 void VulkanTexture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a)
588 {
589 _swizzle[0] = r;
590 _swizzle[1] = g;
591 _swizzle[2] = b;
592 _swizzle[3] = a;
593 // Applied through the image view's component mapping, so a change rebuilds the view (not the texels)
594 _viewDirty = true;
595 }
596
597 void VulkanTexture::SetMaxLevel(std::int32_t maxLevel)
598 {
599 static_cast<void>(maxLevel);
600 }
601
602 void VulkanTexture::SetUnpackAlignment(std::int32_t alignment)
603 {
604 static_cast<void>(alignment);
605 }
606
607 void VulkanTexture::SetObjectLabel(StringView label)
608 {
609 static_cast<void>(label);
610 }
611 }