commonMain.ru.casperix.opengl.renderer.shader.ShaderUniform.kt Maven / Gradle / Ivy
package ru.casperix.opengl.renderer.shader
import ru.casperix.math.color.float32.Color3f
import ru.casperix.math.color.float32.Color4f
import ru.casperix.math.quad_matrix.float32.Matrix3f
import ru.casperix.math.quad_matrix.float32.Matrix4f
import ru.casperix.math.vector.float32.Vector2f
import ru.casperix.math.vector.float32.Vector3f
import ru.casperix.math.vector.float32.Vector4f
import ru.casperix.opengl.core.*
import ru.casperix.opengl.renderer.texture.GLTexture
import ru.casperix.opengl.renderer.texture.GLTexture2D
import ru.casperix.opengl.renderer.texture.GLTextureCube
import kotlin.reflect.KClass
class ShaderUniform(val location: GLLocation) {
companion object {
fun from(buffer: ShaderBuffer, name: String): ShaderUniform? {
return from(buffer.programId, name)
}
fun from(programId: Int, name: String): ShaderUniform? {
val location = glGetUniformLocation(programId, name) ?: return null
if (location == -1) return null
return ShaderUniform(location)
}
}
fun set(matrix: Matrix4f) {
glUniformMatrix4fv(location, false, matrix.data)
}
fun set(matrix: Matrix3f) {
glUniformMatrix3fv(location, false, matrix.data)
}
fun set(value: Vector4f) = value.apply {
glUniform4f(location, x, y, z, w)
}
fun set(value: Color4f) = value.apply {
glUniform4f(location, red, green, blue, alpha)
}
fun set(value: Color3f) = value.apply {
glUniform3f(location, red, green, blue)
}
fun set(value: Vector3f) = value.apply {
glUniform3f(location, x, y, z)
}
fun set(value: Vector2f) = value.apply {
glUniform2f(location, x, y)
}
fun set(value: Float) {
glUniform1f(location, value)
}
fun set(value: Int) {
glUniform1i(location, value)
}
fun set(textureLayer: Int, texture: GLTexture) {
texture.bind(textureLayer)
glUniform1i(location, textureLayer)
}
fun unset(textureLayer: Int, textureClass: KClass) {
glActiveTexture(GL_TEXTURE0 + textureLayer)
when (textureClass) {
GLTexture2D::class -> glBindTexture(GL_TEXTURE_2D, 0)
GLTextureCube::class -> glBindTexture(GL_TEXTURE_CUBE_MAP, 0)
else -> throw Error("Unsupported texture type for $textureClass")
}
glUniform1i(location, textureLayer)
}
}