#version 430

layout(binding=0) uniform sampler2D tex;
layout(binding=1) uniform sampler2D texNoise;
layout(binding=2) uniform sampler2D texAgeSwipe;
layout(binding=3) uniform sampler2D texEnv;

in vec4 posG;
in vec2 uvG;
in vec2 uvOrig;
in vec3 colG;
in float sharpnessG;
in vec4 posSS;
in float age;
in vec3 ageColG;

in int gl_PrimitiveID;


layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;


uniform float g_time;
uniform float g_partSize = 0.15;

uniform float zNear = 0.1;
uniform float zFar = 1000.0;
// convert from 0.0 to 1.0 depth sample ds to linear depth
float linearDepth(float ds) {
    ds = 2.0*ds-1.0;
    float zLinear = 2.0*zNear*zFar/(zFar+zNear-ds*(zFar-zNear));
    return zLinear;
}
// result suitable for assigning to gl_FragDepth
float depthSample(float linearDepth) {
    float nonLinearDepth = (zFar+zNear-2.0*zNear*zFar/linearDepth)/(zFar-zNear);
    nonLinearDepth = (nonLinearDepth+1.0)/2.0;
    return nonLinearDepth;
}


#define PI 3.1415926

vec2 latlong(vec3 v) {
  v = normalize(v);
  float theta = acos(v.z); // +z is up
  float phi = atan(v.y, v.x) + PI;
  return vec2(phi, theta)*vec2(.1591549, .6366198);
}


vec3 rotateXY(vec3 p, float a) {
  vec3 r = p;
  r.x = cos(a)*p.x - sin(a)*p.y;
  r.y = sin(a)*p.x + cos(a)*p.y;
  return r;
}


uniform float g_partMapX = 0;
uniform float g_partMapY = 0;


uniform float near = 0.1;
uniform float far = 1000.0;

uniform float g_maxAge;

uniform float g_partBright = 1.0;
uniform float g_partAlpha = 1.0;

uniform float g_useTexture = 0.0;

void main() {
    vec2 myUv = uvG;
    myUv.y *= -1.0;
    float sharpness = sharpnessG*0.25;
    myUv *= 1.0/8.0;
    myUv.x += g_partMapX*1.0/8.0;
    myUv.y += g_partMapY*1.0/8.0;

    vec4 result; // = texture2D(tex, myUv+vec2(0.0, 0.0));
    // vec4 nois = texture2D(texNoise, myUv+vec2(0.0, 0.0));
    // vec4 emitShape = texture2D(texEmitShape, uvOrig);

    vec2 uvm = (uvG-vec2(0.5,0.5))*2.0;
    float dist = (dot(uvm,uvm));

    float circle = clamp(1.0-dist*1.0, 0.0, 1.0);

    sharpness = 0.40;
    float powe = 1.0;

    circle = clamp(pow(circle*sharpness, powe), 0.0, 1.0);
    result.rgb = vec3(circle);

    if (g_useTexture > 0.5) {
        result.rgb = texture2D(tex, myUv+vec2(0.0, 0.0)).rgb;
    }

    result.a = clamp(result.r*1.0, 0.0, 1.0);
    result.rgb *= 0.02*g_partBright;

//    vec3 ageCol = texture2D(texAgeSwipe, vec2(age/g_maxAge,0.10)).rgb;
//    ageCol *= ageCol;

    result.rgb *= ageColG;

  //  result.a = 1.0;
    result.a *= g_partAlpha;

    result.a = clamp(result.a, 0.0, 100.0);

    frag = result;

    if (frag.r < 0.001) {
        discard;
        return;
    }

    if (result.a < 0.01) {
        discard;
    }

    frag.rgb *= (colG*colG*2.0+0.0);
    frag2 = vec4(vec3(1.0)*result.a, result.a);
}

