#extension GL_EXT_gpu_shader4 : enable

uniform sampler2D s_tex0; // the noise texture
uniform vec2 u_noiseTextureDim;
uniform sampler2D s_tex1; // the forcegrid texture
uniform vec2 u_forceGridTextureDim;
uniform sampler2D s_tex2; // the simulation state texture
uniform vec2 u_stateTextureDim;
uniform sampler2D s_tex3; // the particle redistribute texture


uniform vec4 u_blendcolor;

uniform vec2 u_forceGridOffset;
uniform float u_forceGridCellsize;
uniform float u_forceGridT;

uniform vec4 u_spawnPosRange;
uniform vec2 u_lifetimeRange;

uniform float u_dt;
//const float u_dt=0.01666666666; // ~1/60, assuming a frame rate of 60Hz

uniform float u_controlPointCount;
uniform float u_velocityFactor;
uniform float u_stretchFactor;

varying vec2 v_texcoord;
varying vec2 v_noiseTc;

void main()
{	
	vec4 currStateData = texture2D( s_tex2, v_texcoord );
	//vec4 currStateData = texelFetch( s_tex2, ivec2( v_texcoord * textureSize( s_tex2, 0 ) ), 0 );

	float life = currStateData.a;
	vec2 pos = currStateData.xy;
	float maxLife = currStateData.b;

	vec4 nextStateData;

	if( life < 0.0 ) // particle has died
	{
		vec4 noiseData = texture2D( s_tex0, v_noiseTc );

		life = mix( u_lifetimeRange.x, u_lifetimeRange.y, noiseData.g );// + u_dt;

		maxLife = life;

		pos = texture2D( s_tex3, v_texcoord ).xy;

		// small random offset per particle
		vec2 noise01 = ( ( noiseData.rb - 0.5 ) * 2.0 );
		pos += noise01 * 3.0; //forcegrids cellsize is always 6
		//pos += noise01 * 6.0; //forcegrids cellsize is always 6
	}
	
	vec2 fg_texCoord = ( pos.xy + u_forceGridOffset ) / ( u_forceGridCellsize * u_forceGridTextureDim );
	//vec2 currForce = texture2D(s_tex1, fg_texCoord + vec2(0.5)/u_forceGridTextureDim).xy;
	vec2 currForce = texture2D( s_tex1, fg_texCoord ).xy;

	pos += u_dt * currForce * u_velocityFactor;	

	life -= u_dt; // reduce life

	nextStateData.xy = pos;
	nextStateData.b = maxLife;
	nextStateData.a = life;

	gl_FragData[0] = nextStateData;
	
}


