title: OpenGL GLSL blend two textures by arbitrary shape
body: <p>I have a full screen quad with two textures.</p>
  
  <p>I want to blend two textures in arbitrary shape according to user selection.</p>
  
  <p>For example, the quad at first is 100% texture0 while texture1 is transparent.</p>
  
  <p>If the user selects a region, for example a circle, by dragging the mouse on the quad, then 
  circle region should display both texture0 and texture1 as translucent.</p>
  
  <p>The region not enclosed by the circle should still be texture0.</p>
  
  <p>Please see example image, textures are simplified as colors.</p>
  
  <p><img src="https://i.imgur.com/RqT0WeQ.png" alt="image"></p>
  
  <p>For now, I have achieved blending two textures on the quad, but the blending region can only be vertical slices because I use the step() function.</p>
  
  <p>My frag shader:</p>
  
  <pre><code>uniform sampler2D Texture0;
  uniform sampler2D Texture1;
  uniform float alpha;
  uniform float leftBlend;
  uniform float rightBlend;
  varying vec4 oColor;
  varying vec2 oTexCoord;
  void main()
  {
  vec4 first_sample = texture2D(Texture0, oTexCoord);
  vec4 second_sample = texture2D(Texture1, oTexCoord);
  
  float stepLeft = step(leftBlend, oTexCoord.x);
  float stepRight = step(rightBlend, 1.0 - oTexCoord.x);
  if(stepLeft == 1.0 &amp;&amp; stepRight == 1.0)
      gl_FragColor = oColor * first_sample;
  else
      gl_FragColor = oColor * (first_sample * alpha + second_sample * (1.0-alpha)); 
  
  if (gl_FragColor.a &lt; 0.4)
     discard;
  }
  </code></pre>
  
  <p>To achieve arbitrary shape, I assume I need to create a alpha mask texture which is the same size as texture0 and texture 1?</p>
  
  <p>Then I pass that texture to frag shader to check values, if value is 0 then texture0, if value is 1 then blend texture0 and texture1.</p>
  
  <p>Is my approach correct? Can you point me to any samples?</p>
  
  <p>I want effect such as <a href="https://stackoverflow.com/questions/5097145/opengl-mask-with-multiple-textures">OpenGL - mask with multiple textures</a></p>
  
  <p>but I want to create mask texture in my program dynamically, and I want to implement blending in GLSL</p>
  
  <p>I have got blending working with mask texture of black and white</p>
  
  <pre><code>uniform sampler2D TextureMask;
  vec4 mask_sample = texture2D(TextureMask, oTexCoord);
  if(mask_sample.r == 0)
    gl_FragColor = first_sample;
  else
    gl_FragColor =  (first_sample * alpha + second_sample * (1.0-alpha)); 
  </code></pre>
  
  <p>now mask texture is loaded statically from a image on disk, now I just need to create mask texture dynamically in opengl</p>