uniform sampler2D front;
uniform sampler2D back;
uniform sampler2D front_depth;
uniform sampler2D back_depth;

uniform sampler2D volume1;
uniform sampler2D volume2;

varying vec2 texCoord;

vec4 combineColor(vec4 back, vec4 front) // in premultiplied!
{
  vec4 res;
  res.a = back.a*front.a;
  res.rgb = front.a*back.rgb + front.rgb;
  /*res.a = 1 - (1-front.a)*(1-back.a);*/
  /*res.rgb = ((1-front.a)*back.a*back.rgb + front.a*front.rgb) / res.a;*/
  return res;
}

void main()
{
  vec4 front_col = premulColor(texture2D(front, texCoord));
  vec4 back_col = premulColor(texture2D(back, texCoord));
  vec4 v1_col = premulColor(texture2D(volume1, texCoord));
  vec4 v2_col = premulColor(texture2D(volume2, texCoord));
  vec4 vcol = mixColors(v1_col, v2_col);
  float front_d = texture2D(front_depth, texCoord).a;
  float back_d = texture2D(back_depth, texCoord).a;
  float depth;

  vec4 col = combineColor(vcol, front_col);
  if(back_d == 1.0)
  {
    depth = 0.999999;
  }
  else
  {
    col = combineColor(back_col, col);
    /*gl_FragColor.a = 1-(1-front_col.a)*(1-back_col.a);*/
    /*gl_FragColor.rgb = ((1-front_col.a)*back_col.a*back_col.rgb + front_col.a*front_col.rgb) / gl_FragColor.a;*/
    depth = max(front_d, back_d);
  }

  gl_FragColor.a = 1-col.a;
  gl_FragColor.rgb = col.rgb / (1-col.a);

  /*if(gl_FragColor.a > 0.99)*/
    /*gl_FragDepth = 0.999999;*/
  /*else*/
  gl_FragDepth = depth;
}

