How to crop circles in OpenGL

I am wondering if it is possible to simulate the keyhole search effect in OpenGL.

I have my three-dimensional scene, but I want to do everything black everything except the central circle.

I tried this solution, but its completely opposite to what I want:

// here i draw my 3D scene // Begin 2D orthographic mode glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); GLint viewport [4]; glGetIntegerv(GL_VIEWPORT, viewport); gluOrtho2D(0, viewport[2], viewport[3], 0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Here I draw a circle in the center of the screen float radius=50; glBegin(GL_TRIANGLE_FAN); glVertex2f(x, y); for( int n = 0; n <= 100; ++n ) { float const t = 2*M_PI*(float)n/(float)100; glVertex2f(x + sin(t)*r, y + cos(t)*r); } glEnd(); // end orthographic 2D mode glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); 

What I get is a circle drawn in the center, but I would like to get it extra ...

+4
source share
1 answer

Like everything else in OpenGL, there are several ways to do this. Here are two from the head.

Use circle texture: (recommended)

  • Draw a scene.
  • Switch to the spelling projection and draw a square across the screen using a texture that has a white circle in the center. Use the appropriate blending function:

     glEnable(GL_BLEND); glBlendFunc(GL_ZERO, GL_SRC_COLOR); /* Draw a full-screen quad with a white circle at the center */ 

Alternatively, you can use a pixel shader to create a round shape.

Use a stencil test: (not recommended, but might be easier if you don't have textures or shaders)

  • Clean the stencil buffer and draw a circle in it.

     glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, 1, 1); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); /* draw circle */ 
  • Turn on the stencil test for the rest of the scene.

     glEnable(GL_STENCIL_TEST) glStencilFunc(GL_EQUAL, 1, 1); glStencileOp(GL_KEEP, GL_KEEP, GL_KEEP); /* Draw the scene */ 

Footnote: I recommend that you avoid using immediate mode anywhere in your code and use arrays instead. This will improve the compatibility, maintainability, availability and performance of your code --- gain in all areas.

+6
source

Source: https://habr.com/ru/post/1397575/


All Articles