title: Unable to get Stencil Buffer to work in iOS 4+ (5.0 works fine). [OpenGL ES 2.0]
body: <p>So I am trying to use a stencil buffer in iOS for masking/clipping purposes. Do you guys have any idea why this code may not work? This is everything I have associated with Stencils. On iOS 4 I get a black screen. On iOS 5 I get exactly what I expect. The transparent areas of the image I drew in the stencil are the only areas being drawn later.</p>
  
  <p>Code is below.</p>
  
  <p>This is where I setup the frameBuffer, depth and stencil. In iOS the depth and stencil are combined.</p>
  
  <pre><code>-(void)setupDepthBuffer
  {
      glGenRenderbuffers(1, &amp;depthRenderBuffer);
      glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBuffer);
      glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, self.frame.size.width * [[UIScreen mainScreen] scale], self.frame.size.height * [[UIScreen mainScreen] scale]);
  }
  
  -(void)setupFrameBuffer
  {    
      glGenFramebuffers(1, &amp;frameBuffer);
      glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
      glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer);
      glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer);
      glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer);
  
      // Check the FBO.
      if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
          NSLog(@"Failure with framebuffer generation: %d", glCheckFramebufferStatus(GL_FRAMEBUFFER));
      }
  }
  </code></pre>
  
  <p>This is how I am setting up and drawing the stencil. (Shader code below.)</p>
  
  <pre><code>glEnable(GL_STENCIL_TEST);
  glDisable(GL_DEPTH_TEST);
  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  glDepthMask(GL_FALSE);
  
  glStencilFunc(GL_ALWAYS, 1, -1);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  
  glColorMask(0, 0, 0, 0);
  glClear(GL_STENCIL_BUFFER_BIT);
  
  machineForeground.shader = [StencilEffect sharedInstance];
  [machineForeground draw];
  machineForeground.shader = [BasicEffect sharedInstance];
  
  glDisable(GL_STENCIL_TEST);
  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  glDepthMask(GL_TRUE);
  </code></pre>
  
  <p>Here is where I am using the stencil.</p>
  
  <pre><code>glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  glStencilFunc(GL_EQUAL, 1, -1);
  
  ...Draw Stuff here
  
  glDisable(GL_STENCIL_TEST);
  </code></pre>
  
  <p>Finally here is my fragment shader.</p>
  
  <pre><code>varying lowp vec2 TexCoordOut;
  uniform sampler2D Texture;
  
  void main(void)
  {
      lowp vec4 color = texture2D(Texture, TexCoordOut);
  
      if(color.a &lt; 0.1)
          gl_FragColor = color;
      else
          discard;
  }
  </code></pre>