float noise(vec2 pos,int seed);
float cosInterpolate(vec2 a, float x);
float smooth_2d_noise(vec2 pos,int seed);

float noise(vec2 pos,int seed) {
	float ret = fract(sin(seed+dot(pos,vec2(12.9898,78.233)))*43758.5453)*2.0-0.8;
	return ret;
}

float smooth_2d_noise(vec2 pos,int seed) {
	vec3 a = vec3(0,0,0);
	float ret;
	a.x = (noise(vec2(pos.x-1,pos.y-1),seed) + noise(vec2(pos.x+1,pos.y-1),seed) + noise(vec2(pos.x-1,pos.y+1),seed) + noise(vec2(pos.x+1,pos.y+1),seed)) / 16;
	a.y = (noise(vec2(pos.x-1,pos.y),seed) + noise(vec2(pos.x+1,pos.y),seed) + noise(vec2(pos.x,pos.y-1),seed) + noise(vec2(pos.x,pos.y+1),seed) ) / 8;
	a.z = noise(pos,seed)/4;
	ret = a.x + a.y + a.z;
	return ret;
}

float cosInterpolate(vec2 a, float x) {
	float ft,f,ret;
	float PI = 3.14159265358979323846264;
	ft = (x*PI);
	f = ((1-cos(ft)) * 0.5);
	ret = a.x*(1-f)+a.y*f;
	return ret;
}


float cos_2d_noise(vec2 pos, int seed) {
	vec2 int_pos = floor(pos);
	vec2 frac_pos = pos - int_pos;//fract(pos);
	float ret;
	vec4 v;
	vec2 i;
	
	v.x = smooth_2d_noise(int_pos,seed);	
	v.y = smooth_2d_noise(vec2(int_pos.x+1.0,int_pos.y),seed);
	v.z = smooth_2d_noise(vec2(int_pos.x,int_pos.y+1),seed);
	v.a = smooth_2d_noise(vec2(int_pos.x+1.0,int_pos.y+1.0),seed);
	
	i.x = cosInterpolate(vec2(v.x,v.y),frac_pos.x);
	i.y = cosInterpolate(vec2(v.z,v.a),frac_pos.x);
	
	ret = cosInterpolate(i,frac_pos.y);
	
	return ret;
}


float perlinNoise(vec2 pos,int seed) {
	int i;
	float ret = 0.0;
	float freq,amp;
	int p = 3;
	int n = 3;
	
	for(i=0;i<n;i++) {
		freq = pow(2,i);
		amp = pow(p,i);
		ret += cos_2d_noise(vec2(pos.x*freq,pos.y*freq),seed) *amp;
		ret += 0.1;
	}
	
	return ret;
}

varying vec3 normal;
varying vec4 pos;
varying vec4 rawpos;

void main() {

	float scale=0.007;
	float scale2=0.007;
	float height = 6;

	vec3 v0,v1,v2;

   v0 = gl_Vertex.xyz;
   v1 = v0 + vec3(-scale,0,0);
   v2 = v0 + vec3(0,0,scale);
 
   v0.y = perlinNoise(vec2(v0.x*scale,v0.z*scale),10)*height;
	v1.y = perlinNoise(vec2(v1.x*scale,v1.z*scale),10)*height;
	v2.y = perlinNoise(vec2(v2.x*scale,v2.z*scale),10)*height;
  	 
	vec3 tangent = v1-v0;
	vec3 bitangent = v2-v0;
 
	vec3 fn = cross(tangent,bitangent);
	fn = normalize(fn);//normalize(gl_NormalMatrix * fn);

	normal = normalize(gl_NormalMatrix*fn);

	gl_Vertex.xyz = v0;
	gl_Position = ftransform();
	pos = gl_ModelViewMatrix * gl_Vertex;
	rawpos = gl_Vertex;
	pos.z = -pos.z/800;
	gl_TexCoord[0] = gl_MultiTexCoord0;
}
