Search code examples
kotlinopengllwjgl

glTextureStorage3D and glTextureSubImage3D are not working


I would like to use multiple textures, but stucking. I tried to bind multiple textures with using, glTextureStorage3D and glTextureSubImage3D. I wrote following code by Kotlin.


    // generate textureId
    val tex = BufferUtils.createIntBuffer(1).run {
        glCreateTextures(GL_TEXTURE_2D_ARRAY, this)
        this.get(0)
    }

    // using STBImage, retrieve image file's width, height and bytebuffer
    val textures = texturePaths.mapIndexed { idx, texture ->
        loadTexture(idx, tex, texture)
    }

    glTextureStorage3D(
            tex,
            1,
            GL_RGB,
            textures.maxBy { it.width }!!.width,
            textures.maxBy { it.height }!!.height,
            textures.size
    )

    textures.forEach { texture ->
        glTextureSubImage3D(tex,
                0,
                0,
                0,
                texture.index,
                texture.width,
                texture.height,
                1,
                GL_RGBA,
                GL_UNSIGNED_BYTE,
                texture.img
        )
    }
    ...
}

private fun loadTexture(idx: Int, tex: Int, texture: String): Texture {

    val width = BufferUtils.createIntBuffer(1)
    val height = BufferUtils.createIntBuffer(1)
    val comp = BufferUtils.createIntBuffer(1)
    val img: ByteBuffer = STBImage.stbi_load(texture, width, height, comp, STBImage.STBI_default)
            ?: throw IllegalStateException("Failed to load $texture")

    logger.debug("$texture load OK")
    val texObj = Texture(idx, width.get(0), height.get(0), comp.get(0), img)

    STBImage.stbi_image_free(img)

    return texObj
}

After executed glBindTexture and call glGetTexImage by texureId, no image data returned. I referred following SO post. https://stackoverflow.com/a/5117806/2565527

How to bind textures correctly ?


Solution

  • I found textures are legitimately loaded. But, a parameter int internalformat is incorrect. If we used GL_RGB, alpha value is not used. So I misunderstood it's not loaded correctly. I just changed GL_RGB to GL_RGBA8 and the problem is resolved.

        glTextureStorage3D(
                tex,
                1,
                GL_RGBA8,
                textures.maxBy { it.width }!!.width,
                textures.maxBy { it.height }!!.height,
                textures.size
        )