Home > Back-end >  How to Handle Apple Metal Texture RGB instead of RGBA
How to Handle Apple Metal Texture RGB instead of RGBA

Time:12-13

I'm working on an Apple Metal project in C , and I was trying to implement things from learnopengl.com like the model loader. One part that I'm having trouble on is loading the textures correctly. In the code, I do:

MTL::Texture* loadTextureFromFile(...) {
    ...
    int width, height, nrComponents;
    unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
    
    MTL::Texture* texture = nullptr;
    if (data) {
        MTL::PixelFormat format;
        if (nrComponents == 1) format = MTL::PixelFormatR8Unorm;
        else if (nrComponents == 3) format = MTL::PixelFormatRGBA8Unorm;
        else if (nrComponents == 4) format = MTL::PixelFormatRGBA8Unorm;

I left the if statement when (nrComponents == 3) the same as (nrComponents == 4) because I couldn't find a pixel format that handles RGB without the alpha channel.

I know that in the opengl version of this code, it would use GL_RGB which is RGBA but automatically puts an alpha value of 1.0 in its place. I was wondering if there's a way to do this in Metal or if I have to manually add the alpha value myself for it to work.

CodePudding user response:

24 bit per pixel pixel formats don't play well with GPUs and require an API to do some conversions for you under the cover. This is why the Metal doesn't have those. In your case, I would get the number of components in the file using stbi_info first, and then either use desired_channel argument to stbi_load

int desired_channels -- if non-zero, # of image components requested in result

You can use it to force the component count to either 1 or 4. And then use an actual MTLPixelFormat you want to use.

  • Related