Capping nested entities with a color by entity

Hi everyone,

I’m clipping some entities in the scene by setting gl_ClipDistance, I have some doubts about giving caps to entities and I hope you can give me good hints about that: thank you all in advance! :slight_smile:

CONTEXT
I used what I think to be the standard approach to create single coloured cappings:

1. Draw all the entities only in stencil with front face clipping, increasing stencil
2. Draw all the entities only in stencil with back face clipping, decreasing stencil
3. Draw a mesh (color mask on, depth test on [GL_LESS]) representing the clipping plane: the stencil allows only the cap to be drawn

I wanted to take a step further, by giving each entities its own capping color;
my main issue is that entities in my scene can be nested, and I could just came up with the following approach:

1. for each entity in scene
2.     Draw the given entity only in stencil with front face clipping, increasing stencil
3.     Draw the given entity only in stencil with back face clipping, decreasing stencil
4.     Draw the clipping plane (color mask on, depth test on [GL_LESS]) using the entity color 
5.     Next

This approach works (at least, I’m getting the expected results), but I was wondering if something better could be achieved; namely, I change face clipping twice on a per entity basis, as well as stencil operation and depth testing, whilst in the single colour approach I could change all the settings on a per scene draw basis.
I tried some depth-based approaches, but I couldn’t manage to produce a proper result.

SIMPLE USE CASE
A simple situation that I tried to analize is the following, where my attempts with depth failed due to the face pointed at by the green arrow

EXPECTED RESULT
This is the expected result, that I can get with the previously described approach

QUESTION
Is performing two stencil passes and a color draw call for each entity a good enough approach, or is there a better algorithm to achieve the wanted result?
Thank anyone who can share their thoughts on this matter!