2
\$\begingroup\$


I'm programming a 2D game libgdx. I'm using a SpriteBatch of course to draw some Sprites. Now I wanted to use multiple ShaderPrograms with the SpriteBatch, but unfortunately you can set only one `ShaderProgram at a time. For example, I wanted to draw the whole scene with a specific color and wanted to add a parallax effect to some sprites by manipulating the texCoords in the shader. I know in native OpenGL you can just enable as much shaders as you want before your draw call. But it seems that in libgdx it is not possible.

\$\endgroup\$
1
  • \$\begingroup\$ Why don't you just combine the shaders? \$\endgroup\$
    – Charanor
    Commented Jul 21, 2017 at 16:57

1 Answer 1

4
\$\begingroup\$

You can first render your scene to a texture with the first shader, then render the texture with the second shader. This will apply both shaders to your scene. You render to texture using a FrameBuffer.

SpriteBatch batch = new SpriteBatch();
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, width, height, hasDepth);
TextureRegion fboTexture = new TextureRegion(fbo.getColorBufferTexture());
fboTexture.flip(false, true); // Have to flip on Y axis

public void render(float delta) {
    // Draw scene to texture
    batch.setShader(shader1);
    fbo.begin();
    // If you're having issues with the drawing try doing glClear right after fbo.begin().
    batch.begin();
    // Draw here
    batch.end();
    fbo.end();

    // Draw scene to screen
    batch.setShader(shader2);
    batch.begin();
    // Draw here
    batch.end();
}

The much simpler way would be to just combine the two shaders into one shader, though.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 for the answer, however the last sentence may be dubious if you need to apply the second shader selectively for some sprites \$\endgroup\$
    – comodoro
    Commented Jun 23, 2018 at 12:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .