All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.opengl.renderer.texture.GLTexture2D.kt Maven / Gradle / Ivy

There is a newer version: 0.11.1
Show newest version
package ru.casperix.opengl.renderer.texture

import ru.casperix.opengl.core.*
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLMagFilter
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLMinFilter
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLWrap
import ru.casperix.renderer.material.Texture2D

class GLTexture2D(val texture: Texture2D) : GLTexture {
    val handle = GLTextureHandlerProvider.next()

    init {
        glBindTexture(GL_TEXTURE_2D, handle)
        texture.config.apply {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, asGLWrap(uWrap))
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, asGLWrap(vWrap))
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, asGLMinFilter(minFilter, useMipMap))
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, asGLMagFilter(magFilter, useMipMap))
        }
        upload()

        if (texture.config.useMipMap) {
            glGenerateMipmap(GL_TEXTURE_2D)
        }
    }

    override fun dispose() {
        glDeleteTexture(handle)
    }

    private fun upload() {
        val image = texture.map
        val data = image.bytes.data
        val bytesPerPixel = image.pixelCodec.bytesPerPixel
        val openGlFormat = when (bytesPerPixel) {
            3 -> GL_RGB8
            4 -> GL_RGBA8
            else -> throw Exception("Unsupported bytesPerPixel: $bytesPerPixel")
        }
        val dataFormat = when (bytesPerPixel) {
            3 -> GL_RGB
            4 -> GL_RGBA
            else -> throw Exception("Unsupported bytesPerPixel: $bytesPerPixel")
        }
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            openGlFormat,
            image.width,
            image.height,
            0,
            dataFormat,
            GL_UNSIGNED_BYTE,
            data.asByteArray()
        )
    }

    override fun bind(channel: Int) {
        glActiveTexture(GL_TEXTURE0 + channel)
        glBindTexture(GL_TEXTURE_2D, handle)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy