Huh, I think I just invented something kinda cool (I'm sure I'm not the first to...

@lina@vt.social

Huh, I think I just invented something kinda cool (I'm sure I'm not the first to come up with it?). A way to render "layer groups" with a shared opacity (without internal overlaps being revealed), like offscreen rendering, without actually doing any offscreen rendering or switching framebuffers.

The tradeoff is you have to render those groups twice (once for an alpha pre-pass) and your framebuffer alpha needs to be expendable (so, opaque background behind everything). But you can have as many such groups as you want (single level deep, no nesting).

The trick is to first render such a group as alpha mask only (clearing FB alpha and then accumulating the group alpha into it, standard blending with alpha write only), then render a couple quads to compute:

(pass 1)
Adst' = Adst * Asrc
(pass 2)
Cdst' = Cdst * (1 - Adst)
Adst' = 1 - Asrc

Where Asrc is the layer group opacity (which can in fact be any arbitrary mask, not necessarily a constant).

Then finally render the group again, front to back, with front to back blending formulas:

Cdst = Cdst + Csrc * (1 - Adst)
Adst = Adst + Asrc * (1 - Adst)

The first part leaves the FB RGB as a combined semitransparent "front layer" (background at 1 - layer group opacity) + pre-accumulated "back layer" in the RGB channels (background at (layer group opacity * (1 - layer group alpha))).

The second part renders the layer group "in between".

Repeat for more layer groups, back to front.

Surely I'm not the first to come up with this?