#version 120
attribute vec2  in_geometry;
attribute vec3  in_position;
attribute vec3  in_velocity;
attribute float in_maxDist;

uniform float age;
uniform float size;
uniform float maxVelocity;
uniform float halfAge;
uniform vec3  explCenter;

varying float decay;
varying vec3  velocity;
varying vec2  vertex;
varying float explCenterDist;

uniform float aspectRatio;

// TODO: rotate to face the user!
void main()
{
  // add a bit variation to the decay compution by adding part of the initial
  // position to the age
  float ageMod = age + mod(20.0*in_position.z + 10.0*in_position.x + in_position.y, 0.5);

  //decay = min(1.0, age+5.0*length(velocity)) / halfAge;
  //decay = max(decay*decay, sqrt(decay));
  decay = ageMod / halfAge;

  // faster particles are smaller
  // TODO: scale by time too! scale down fast after 3 halfAges
  float scaleBySpeed = (1.0 - 0.95*length(in_velocity)/maxVelocity);
  float finalSize = size * scaleBySpeed * (1.0-max(0.0, decay-3.0*halfAge)/2.0);
  vec2 base = in_geometry;
  vec3 p = vec3(finalSize*base, 0.0);
  vec3 move = (0.2*age + log(1.0+age*5.0)) * in_velocity;
  float md = length(move);
  if (md > in_maxDist) {
    move *= in_maxDist / md;
  }
  vec3 offset = move + in_position;
  p += offset;

  gl_Position = vec4(p, 1.0);

  vertex   = base.xy;
  velocity = in_velocity;

  explCenterDist = length(explCenter - offset);
}