#define terrainwidth 1024
uniform sampler2D heightmap;
uniform sampler2D bumpmap;
uniform sampler2D densitymap;
uniform vec3 terrainscale;
uniform vec4 frustumplane[6];
uniform float maxslope;
uniform float aabbradius;
varying mat4 instancematrix;
void main( void ) {
//Get the x and y positions and texture coordinate
float x = gl_InstanceID / terrainwidth;
float y = gl_InstanceID - x * terrainwidth;
vec2 terraincoord = vec2( x / float(terrainwidth), y / float(terrainwidth) );
x = x - terrainwidth/2.0;
y = y - terrainwidth/2.0;
//Get terrain height
float terrainheight = texture2D( heightmap, terraincoord ) * terrainscale.y;
//Create 4x4 matrix for instance varying, gets passed to vertex program
instancematrix[3][0]=x;
instancematrix[3][1]=terrainheight;
instancematrix[3][2]=z;
//Check density map
if (texture2D( densitymap, terraincoord ).x<0.5) {
discard;
}
//Check terrain slope
float slope = texture2D( bumpmap, terraincoord ).y * 2.0 - 1.0;
if ( slope > maxslope ) {
discard;
}
//Culling test
for ( int i = 0; i <= 6; i++ ) {
if (PlanePointDistance( instancematrix[3].xyz, frustumplane[i] )<-aabbradius) {
discard;
}
}
//If the instance hasn't been discarded by this point then it will be drawn!
}