uniform sampler2D envimap;
uniform float shlimit;
uniform sampler2D texmap;
uniform float texblend;
uniform int mapping;

varying vec3 opos;
varying vec3 normal;
varying vec3 look;
varying float shredpos;
varying float dist;

#define pi 3.141593

vec2 envicoord(vec3 n, vec3 u) {
  vec2 pier;
  vec3 r = reflect(u, n);
  float m = 2.0*sqrt(r.x*r.x + r.y*r.y + (r.z+1.0)*(r.z+1.0));
	pier.x = r.x/m + 0.5;
	pier.y = 1.0-(r.y/m + 0.5);
	return pier;
}

void main(void) {
  vec2 ec=envicoord(normal, look);
  vec4 ecol=texture2D(envimap, ec);
  float shred=sin(shredpos*3.412+sin(shredpos*2.432-sin(shredpos*5.321)))*0.5+0.5;
  float alpha;
    
  if (shred<shlimit) alpha=0.0;
  else alpha=1.0;
  
  if (texblend>0.0) {
    vec2 tc;
    vec4 tmap;
    if (mapping==1) tc = vec2(4.0*(atan(opos.y, opos.x)/(pi*2.0))+0.5, opos.z/32.0+0.1);
    else if (mapping==2) tc = vec2(4.0*(atan(opos.x, opos.z)/(pi*2.0))+0.5, opos.y/128.0+0.5);
    else tc = gl_TexCoord[0].xy;
    tmap = texture2D(texmap, tc);
    ecol = ecol+tmap*texblend;
  }

  gl_FragData[0] = vec4(vec3(ecol), alpha);
  gl_FragData[1].r = dist;
  gl_FragData[1].a = 0;

}
