Fragment shader race condition, merging transparent pixels

I draw two overlapping shapes, both with alpha < 1. Where they overlap, the final screen pixels are darker, as expected.


Now I want a fragment shader that blends not by adding, but by picking the one with higher alpha. I tried the code below. It creates crazy ribbons of color and white that I’m guessing come from a race condition.


Is there a technique for this - a way to make sure that the fragment shader runs to compute the pixel contribution of one triangle, only after the previous one has written to the color attachments?


typedef struct {
    float4 color [[color(0)]];
    float stroke_alpha [[color(1)]];
} FragOut;

fragment FragOut fragmentShader(RasterizerData in [[stage_in]],
                                float4 dest [[color(0)]],
                                float stroke_alpha [[color(1)]])
{
    float new_a = in.color.a;
    FragOut out;
    if (new_a > stroke_alpha) {
        out.color = in.color;
        out.stroke_alpha = new_a;
    } else {
        out.color = dest;
        out.stroke_alpha = stroke_alpha;
    }
    
    return out;
}



Rob

Accepted Reply

I just discovered "Raster Order Groups" and they look like exactly what I need here.

Replies

I just discovered "Raster Order Groups" and they look like exactly what I need here.