BulBul
BulBul

Reputation: 1209

unexpected behavior while using SDL_image for texture in Vulkan

i managed to load jpg images and use them as textures in vulkan, however different images give different results, with some images it works just fine, with others it does not map well.

here is the code block related to image loading and format transition:-

void Vulkan::createTextureImage()
{
    SDL_Surface *tempImg;
    SDL_RWops *rwop;

    rwop = SDL_RWFromFile("Textures/img1.jpg", "rb");
    tempImg = IMG_LoadJPG_RW(rwop);



    SDL_Surface *image = SDL_ConvertSurfaceFormat(tempImg, SDL_PIXELFORMAT_ABGR8888, 0);

    VkDeviceSize imageSize = image->format->BytesPerPixel * image->h * image->w;


    if (!image)
    {
        throw std::runtime_error("failed to load texture image!");
    }

    VkImage stagingImage;
    VkDeviceMemory staingImageMemory;

    createImage(
        image->w, image->h, 
        VK_FORMAT_R8G8B8A8_UNORM, 
        VK_IMAGE_TILING_LINEAR, 
        VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 
        stagingImage, 
        staingImageMemory);

    std::cout << "the image size is " << imageSize << std::endl;

    void * data;
    vkMapMemory(device, staingImageMemory, 0, imageSize, 0, &data);
    memcpy(data, image->pixels, (size_t)imageSize);
    vkUnmapMemory(device, staingImageMemory);

    createImage(
        image->w, image->h,
        VK_FORMAT_R8G8B8A8_UNORM,
        VK_IMAGE_TILING_OPTIMAL,
        VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
        textureImage,
        textureImageMemory);

    transitionImageLayout(stagingImage, VK_FORMAT_R8G8B8A8_UNORM,
        VK_IMAGE_LAYOUT_PREINITIALIZED,
        VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
    transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_UNORM,
        VK_IMAGE_LAYOUT_PREINITIALIZED,
        VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

    copyImage(stagingImage, textureImage, image->w, image->h);

    transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_UNORM,
        VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
        VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);

}

the only modification i have done is to flip the V component of the texture to fix the mirrored images

image results: no problem loading this image

this one does not map well enter image description here

while it should show something like this enter image description here

Upvotes: 2

Views: 874

Answers (1)

ratchet freak
ratchet freak

Reputation: 48216

It looks like the row pitch of sdl doesn't match the row pitch that vulkan wants.

Instead you can use a buffer to image copy from staging memory with vkCmdCopyBufferToImage instead of a image to image blit there you pass the row pitch explicitly in the VkBufferImageCopy struct.

Upvotes: 1

Related Questions