draw its intersection with the sub-portal shape to get a new portal clip shape

repeat

To get the intersection is not straightforward:

draw the outer portal using GL_INCR

draw the sub-portal using GL_INCR

re-draw the outer portal using GL_DECR

pixels >= 1 represent the intersection between the outer portal and the sub-portal

Technically we could save and restore the buffer at each level of recursion (instead of re-drawing all the portal shapes from scratch), but this would be slow, and retrieving the stencil buffer data is not possible with OpenGL ES 2.

The outer portal and sub-portal are exactly the same object, only the View matrix changes. So we pass a stack of view to the function, and push a new View matrix with each new level of recursion.

Note that the stencil drawing must support volumetric portals, which means it may be written to more than once (so you cannot achieve intersection using just GL_INVERT).