Before drawing a sprite in my LibGDX game, I want to apply a grayscale shader to different sprites in a sprite batch depending on a condition. Here is the code that has worked for me, by applying the shader to the rendering sprite batch before calling sprite.draw(batch) on each sprite:
private fun updateShaderFromSpriteComponent(component: SpriteComponent) {
if (component.shouldRenderGrayscale) {
LOG.info { "Rendering grayscale" }
batch.shader = shaderProgram
} else {
batch.shader = null
}
}
But the following does not work:
private fun updateShaderFromSpriteComponent(component: SpriteComponent) {
if (component.shouldRenderGrayscale) {
LOG.info { "Rendering grayscale" }
batch.shader?.setUniformi("u_isGrayscale", 1)
} else {
batch.shader?.setUniformi("u_isGrayscale", 0)
}
}
It will render everything in full colour, I can see in the debugger that the code to set the uniform is being called however.
I thought the point of setting uniform values is that I can parameterize the way that the shader works without needing to swap shaders all the time, which I read was computationally quite intensive. Am I doing something wrong or missing a step? What if I want do something more complicated where just swapping out the shader won't cut it, like fading in a texture based on a changing float value that I want to pass to the shader? Thanks for any tips or advice!
I have tried:
- calling shaderProgram.bind() before and after setting the uniform values
- ...honestly there is just mostly old documentation and very simple examples like applying a shader to one texture, so I'm really stuck and have no idea what else to try!
You need to batch.flush() before changing shader/updating uniforms.