How to clip this part of mesh in Opengl?

Viewed 81

I tried to clip mesh in openGl and i think that i have a problem with math. I have a cube enter image description here

And i need to clip for example half of that cube. So i didn't understand how to calculate this clipping plane. White lines illustrate how this clip plane should looks like, it is just parallel one of the cube sides

My clipping

#version 120

varying vec3 ourColor;
varying float clip_distance;
void main()
{
    if ( clip_distance < 0.0 )
        discard;
    gl_FragColor = vec4(ourColor, 1.0);
}
#version 120


attribute vec3 aPos;
attribute vec3 aColor;
varying vec3 ourColor;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;


varying float clip_distance;
const vec4 clipPlane = vec4(1.0, 1.0, 1.0, -1.0);

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    
    clip_distance = dot(gl_Position, clipPlane);
    ourColor = aColor;
}

So, how to calculate this clipping plane. I want to understand how to calculate clipping planes for each of cube sides

1 Answers

Assuming your input vertices describe a (0,0,0) -> (1,1,1) cube, you can solve this with one line at the top of your vertex shader:

aPos = clamp(aPos, vec3(clipMinX, clipMinY, clipMinZ),
                   vec3(clipMaxX, clipMaxY, clipMaxZ));

where the clip{Min,Max}* variables are the axis-aligned distances on which to clip the cube.

For example, aPos = clamp(aPos, vec3(0,0,0), vec3(1,0.5,1)) will cut the top half of the cube.

Related