I started to look into shaders and what you can do with them recently and got started on a small project aswell. The thing I’m thinking about is to limit the drawing of terrain for example so that only the visible part of a terrain(mesh) is drawn.
I started out with giving my shader the normalized look direction of the camera and with that I calculated the dot product from a vector3 pointing from each vertex to the camera. This would allow me to cut out part of the vertices behind the camera and increasing performance with it.
It seemed like a good idea and I got some code in place for it but not the result I was expecting.
But, as matrices and the MVP stuff is quite blurry to me I do not know if I need to use them or not, since the best result is given when I use the gl_Position value.
Vertex shader:
//----------------------------------------
uniform mat4 modelViewProjection;
attribute vec4 position;
attribute vec4 color;
attribute vec2 texCoord;
//playerPos is the global position of the camera/player
uniform vec3 playerPos;
uniform vec3 playerLook;
varying lowp vec4 vColor;
varying highp vec2 vTexCoord;
varying lowp float dotProd;
void main()
{
//Pass the mesh color to the fragment shader
vColor = color;
vTexCoord = texCoord;
vec4 pos = modelViewProjection * position;
lowp vec3 plToP = normalize(vec3(pos.x,pos.y,pos.z)-playerPos);
dotProd = dot(plToP,playerLook);
//Multiply the vertex position by our combined transform
gl_Position = pos;
}
//-----------------------------------
Fragment shader:
//-----------------------------------
precision highp float;
//This represents the current texture on the mesh
uniform lowp sampler2D texture;
//The interpolated vertex color for this fragment
varying lowp vec4 vColor;
varying lowp float dotProd;
//The interpolated texture coordinate for this fragment
varying highp vec2 vTexCoord;
void main()
{
if(!gl_FrontFacing) { discard; }
if(dotProd > 0.0) { discard; }
lowp vec4 col = texture2D( texture, vTexCoord ) * vColor;
gl_FragColor = col;
}
Note:I removed some unrelated fog code to shorten the shader code here.
Am I doing my calculations wrong here or what?
Some screens(I couldn’t find any info on how to show smaller thumbnails here)
http://imgur.com/ugLm6B7
http://imgur.com/js312WV
Note the holes in the ground in the distance.