Friday 8 January 2016

OpenGL clipping technique.

Part of the physics simulation I am working on at the moment involves cutting a cylinder in half, so that spheres have a defined space to interact but we can also view them.

First I created a cylinder in 3ds max, with normals included. I didn't create the half cylinder because I want to have multiple cylinder objects for the spheres to collide with (also I was interested in the process).

So I implemented an extra expression in my GLSL fragment shader, to say:
 If the X value (the camera looks down the X axis) of a fragment (in worldspace) is < 0 then discard that fragment.

Initially, using the `discard` in-built function I got really strange results, with some fragments being removed and some staying. It looked like static on a TV.


This problem was solved by implementing alpha blending, and setting the alpha value of fragments I want to discard to 0.0.


This was great! however I wanted more control over the clipping (hardcoded at the time), so I decided to define a "clipping plane" (a vector which represents the normal of the plane).

Then I find the cosine of the position of any given fragment (in world space) and that clipping plane normal. If that value < 0 then I know that that fragment is behind the "face" of the plane, so it can be discarded. Here's the GLSL code to implement that:
    outColour.a = max(0.0, sign( dot( ClipPlane.xyz, vVaryingPos ) ) );
 Where vVaryingPos is the position of the vertex in world space, computed in the vertex shader like:
    vVaryingPos = ( modelMatrix * vec4( vVertex, 1.0 ) ).xyz;

The resulting image was exactly the same, awesome! Now I can do funky things like...

Due to face culling and the fact the cylinder only has normals facing inwards, when the back of the cylinder faces us, it isn't rendered! See here.



No comments:

Post a Comment

The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...