ravi.joshi53's picture

Making some portion of the texture transparent

Hi,

I have loaded a texture and I can draw it easily in the GameWindow. I wanted to make some of its portion invisible. Let say, I want to display only 40% (in length) of the entire object.

How to achieve it?


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

The simplest way would be to use a stencil buffer. Instructions:

The basic idea is that you render a stencil mask over the region you wish to discard and then enable stencil testing to discard everything that is rendered on that region.

Pseudocode from the first link:

  // RenderFrame event
  glClear(GL_DEPTH_BUFFER_BIT);
 
  // setup stencil buffer
  glEnable(GL_STENCIL_TEST);
  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  glDepthMask(GL_FALSE);
  glStencilFunc(GL_NEVER, 1, 0xFF);
  glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP);  // draw 1s on test fail (always)
 
  // draw stencil mask
  glStencilMask(0xFF);
  glClear(GL_STENCIL_BUFFER_BIT);  // needs mask=0xFF
  DrawStencilMaskHere();
 
  // go back to normal rendering
  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  glDepthMask(GL_TRUE);
  glStencilMask(0x00);
 
  // now draw where stencil's value is 0
  glStencilFunc(GL_EQUAL, 0, 0xFF);
  DrawObject();
 
  // or draw where stencil's value is 1
  glStencilFunc(GL_EQUAL, 1, 0xFF);
  DrawObject();
 
  glDisable(GL_STENCIL_TEST);
ravi.joshi53's picture

Thanks Fiddler,

Never heard about Stencil buffer... Sounds strange... Can you please provide a sample OpenTK code, which can draw texture and make half of it invisible.

the Fiddler's picture

Check out the Stencil CSG sample from OpenTK.Examples. It demonstrates how to render constructive solid geometry by using the stencil buffer to combine geometric shapes.

You can run this example using the example browser (opentk/Binaries/OpenTK/Release/Examples.exe -> OpenGL -> Stencil CSG.)

ravi.joshi53's picture

Hi Fiddler,

In my case, the app is having a texture set as a background and there is an another texture, which is drawn in a rectangle. The whole app is in 2D. I want to show only some portion of this rectangular texture.

I looked over the StencilCSG.cs example code and tried to get the logic of RenderCsg() function. It would be highly appreciable, if you can post a code, specific only to the scenario.

Thanks a lot.