Skip to content

Commit cd85f15

Browse files
committed
[gltf-model] Improve conversion of rgb data to rgba (thanks to user asymptotically from Discord)
1 parent f4701fc commit cd85f15

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

src/vulkan-renderer/gltf2/gltf2_model.cpp

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,26 +26,21 @@ void Model::load_textures() {
2626

2727
// We need to convert RGB-only images to RGBA format, because most devices don't support rgb-formats in Vulkan.
2828
if (texture.component == 3) {
29-
std::vector<unsigned char> conversion_buffer;
29+
std::vector<std::array<std::uint32_t, 3>> rgb_source;
30+
rgb_source.reserve(texture_size);
3031

31-
// Preallocate memory for a texture with 4 channels (RGBA).
32-
conversion_buffer.reserve(texture_size);
32+
// Copy the memory into the vector so we can safely perform std::transform on it.
33+
std::memcpy(rgb_source.data(), &texture.image[0], texture_size);
3334

34-
// The pointer to which we will write data to.
35-
unsigned char *mem_target_rgba = conversion_buffer.data();
35+
std::vector<std::array<std::uint32_t, 4>> rgba_target;
36+
rgba_target.reserve(texture_size);
3637

37-
// The pointer to the rgb data we read from.
38-
unsigned char *mem_source_rgb = &texture.image[0];
38+
std::transform(rgb_source.begin(), rgb_source.end(), rgba_target.begin(),
39+
[](const std::array<std::uint32_t, 3> a) {
40+
return std::array<std::uint32_t, 4>{a[0], a[1], a[2], 1};
41+
});
3942

40-
for (std::size_t i = 0; i < texture.width * texture.height; ++i) {
41-
std::memcpy(mem_target_rgba, mem_source_rgb, sizeof(unsigned char) * 3);
42-
// TODO: Remove pointer arithmetic or add NOLINT
43-
mem_target_rgba += 4;
44-
// TODO: Remove pointer arithmetic or add NOLINT
45-
mem_source_rgb += 3;
46-
}
47-
48-
m_textures.emplace_back(m_device, &conversion_buffer[0], texture_size, texture.width, texture.height,
43+
m_textures.emplace_back(m_device, rgba_target.data(), texture_size, texture.width, texture.height,
4944
texture.component, 1, "glTF2 model texture");
5045
} else if (texture.component == 4) {
5146
m_textures.emplace_back(m_device, &texture.image[0], texture_size, texture.width, texture.height,

0 commit comments

Comments
 (0)