1 // If we didn't have to worry about alpha in the bottom layer,
2 // this would be a simple mix(). However, since people might
3 // compose multiple layers together and we don't really have
4 // any control over the order, it's better to do it right.
6 // These formulas come from Wikipedia:
8 // http://en.wikipedia.org/wiki/Alpha_compositing
10 vec4 FUNCNAME(vec2 tc) {
11 vec4 bottom = INPUT1(tc);
12 vec4 top = INPUT2(tc);
13 float new_alpha = mix(bottom.a, 1.0, top.a);
14 if (new_alpha < 1e-6) {
15 // new_alpha = 0 only if top.a = bottom.a = 0, at least as long as
16 // both alphas are within range. (If they're not, the result is not
17 // meaningful anyway.) And if new_alpha = 0, we don't really have
18 // any meaningful output anyway, so just set it to zero instead of
19 // getting division-by-zero below.
22 vec3 premultiplied_color = mix(bottom.rgb * bottom.aaa, top.rgb, top.a);
23 vec3 color = premultiplied_color / new_alpha;
24 return vec4(color.r, color.g, color.b, new_alpha);