iosopengl-eslightingmultipass

How do you add light with multiple passes in OpenGL?


I have two functions that I want to combine the results of:

drawAmbient
drawDirectional

They each work fine individually, drawing the scene with the ambient light only, or the directional light only. I want to show both the ambient and directional light but am having a bit of trouble. I try this:

[self drawAmbient];

glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);

[self drawDirectional];

glDisable(GL_BLEND);

but I only see the results from first draw. I calculate the depth in the same way for both sets of draw calls. I could always just render to texture and blend the textures, but that seems redundant. Is there I way that I can add the lighting together when rendering to the default framebuffer?


Solution

  • You say you calculate the depth the same way in both passes. This is of course correct, but as the default depth comparison function is GL_LESS, nothing will actually be rendered in the second pass, since the depth is never less than what is currently in the depth buffer.

    So for the second pass just change the depth test to

    glDepthFunc(GL_EQUAL);
    

    and then back to

    glDepthFunc(GL_LESS);
    

    Or you may also set it to GL_LEQUAL for the whole runtime to cover both cases.