Search code examples
openglmask

How to mask OpenGL quad with another quad


I am trying to make display a quad, but only when it is over an other quad that I know the position of. I thought about using that quad as a mask for the other quad, but I am unsure about how to do it (I already found this post that talks about masking, however in my case I don't have a mask texture; I only know the X, Y, width and height of the area to mask). The current solution I found is to use glBlendFunc, and it only works if I don't render anything behind it, which won't be the case later on.

glBlendFunc(GL_ONE, GL_ZERO);
// draw the background quad, that is acting as the mask...
glBlendFuncSeparate(GL_ZERO, GL_ONE, GL_SRC_ALPHA, GL_ZERO);
// draw the background quad again, this time it will act as a mask...
glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
// draw the quads that will be masked...
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // this is the blend func used for the rest of the rendering

Before drawing each frame, I also have a function that clears the screen:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0,0,0,0);

How could I make it so that whatever it is that I draw before that, it will only mask on the previous quad?


Solution

  • If you want to restrict the rendering to a rectangular area than you can use the Scissor Test.
    The scissor test has to be enabled (GL_SCISSOR_TEST) a nd th rectangular area can be set by glScissor. e.g.:

    glEnable(GL_SCISSOR_TEST);
    glScissor(x, w, width, height);