#version 460
precision mediump float;
out vec4 o;
const float PI = 3.14159265;
const float TAU = (2. * PI);
const float PHI = sqrt(5.) * 0.5 + 0.5;
layout(location = 0) uniform float syncs[7];
layout(location = 8) uniform float fft_output[512]; // FFT_SIZE / 4
float u_time = syncs[0];

vec2 getUV(vec2 offset) {
    vec2 uv = 2.0 * ((gl_FragCoord.xy + offset *0.5) / vec2(1920,1080) - 0.5);
    uv.x *= 1920/1080;
    return uv;
}

float noise(in vec2 xy, in float seed) {
    return fract(tan(distance(xy * PHI, xy) * seed) * xy.x);
}

// Hexagonal prism, circumcircle variant
float fHexagonCircumcircle(vec3 p, vec2 h) {
    vec3 q = abs(p);
    return max(q.y - h.y, max(q.x * sqrt(3.) * 0.5 + q.z * 0.5, q.z) - h.x);
	//this is mathematically equivalent to this line, but less efficient:
	//return max(q.y - h.y, max(dot(vec2(cos(PI/3), sin(PI/3)), q.zx), q.z) - h.x);
}

float sdHex(vec3 pos, float i, float angle) {
    float d1 = fHexagonCircumcircle(pos, vec2(0.86, i));
    return d1;
}

// Modify your mapScene function
vec2 mapScene(in vec3 p) {
    float mat = 0.;
    float d = 1e9;
    float a = 0.;
    vec3 po = p;


    vec3 rippleCenter = vec3(7.5, 0, 7.5);
    float rippleSpeed = 4.0;
    float rippleFreq = 1.0;
    float rippleDecay = 0.25;


    // Hexagonal grid
    float counter = 0.;
    float hexGap = 0.2;

    for(float j = 0.; j < 15.; j++) {
        po = p;
        po += vec3(1.5 * 7.5, 0., 7.5);
        po += vec3(0, 0.,  (1.88 + hexGap)*j);

        for(float i = 0.; i < 15.; i++) {
            if( mod(i, 2.) == 0.) {
                po -= vec3(1.6+hexGap, 0., 1.);
            } else {
                po += vec3(-(1.6+hexGap), 0., 1.);
            }

            // Add individual hexagon ripples based on distance from center
            float hexDist = length(vec2(i , j) - rippleCenter.xz);
            float wave = sin(hexDist * rippleFreq - u_time * rippleSpeed) * exp(-hexDist * rippleDecay);


            // Apply ripple to hexagon size and position
            float hexSize =  fft_output[int(i+1)*int(j+1)]*5.0; // sin(1.5*u_time)+ wave
            a = sdHex(po, 1. + hexSize, 0.);
            d = min(d, a);

            if (d == a) {
                mat = 4.;
            }
            counter += 1.;
        }
    }

    return vec2(d, mat);
}

vec3 castRay(vec3 ro, vec3 rd, inout vec3 pos) {
    float t = 0.;
    float mat = 0.;
    float hit = 0.;
    // Reduced from 40 to 24 steps
    for(int i = 0; i < 24; i++) {
        pos = ro + rd * t;
        vec2 res = mapScene(pos);
        // Increase step size multiplier for faster marching
        t += res.x * 1.2;
        mat = res.y;
        if(t > 60.) { // Reduced max distance
            break;
        }
        if(res.x < 0.001 * t) { // Less precise hit detection
            hit = 1.;
            break;
        }
    }
    if(t > 60.) t = 0.;

    return vec3(t, mat, hit);
}

float softshadow(in vec3 ro, in vec3 rd, float mint, float maxt, float w) {
    float res = 1.0;
    float t = mint;
    for(int i = 0; i < 6; i++) {
        if(t > maxt)
            break;
        float h = mapScene(ro + t * rd).x;
        res = min(res, h / (w * t));
        t += clamp(h, 0.1, 0.80);
        if(res < -1.0)
            break;
    }
    res = max(res, -1.0);
    return 0.25 * (1.0 + res) * (1.0 + res) * (2.0 - res);
}

vec3 calcNormal(vec3 pos) {
    vec2 e = vec2(.01, 0.);
    vec3 n = vec3(mapScene(pos + e.xyy).x - mapScene(pos - e.xyy).x,
                  mapScene(pos + e.yxy).x - mapScene(pos - e.yxy).x,
                  mapScene(pos + e.yyx).x - mapScene(pos - e.yyx).x);
    return normalize(n);
}

vec3 fresnel(vec3 F0, vec3 h, vec3 l) {
    return F0 + (1.0 - F0) * pow(clamp(1.0 - dot(h, l), 0.0, 1.0), 5.0);
}

vec3 addPointLight(vec3 light_pos, vec3 light_color, float shininess, vec3 v, vec3 dir, vec3 n, float occ) {
    vec3 Ks = vec3(.4545);
    vec3 Kd = vec3(1.);
    vec3 ref = reflect(dir, n);
    vec3 vl = normalize(v);
    vec3 diffuse = Kd * vec3(max(0.0, dot(vl, n)));
    vec3 specular = vec3(max(0.0, dot(vl, ref)));
    vec3 F = fresnel(Ks, normalize(vl - dir), vl);
    float shadow = softshadow(v + n * 0.054, light_pos, .01, 30., 8.);

    //specular = pow(specular, vec3(shininess)) * occ;
    return light_color * mix(diffuse, specular, F) * shadow;

}

float getAmbientOcc(vec3 p, vec3 n) {
    float occ = 0.;
    float weight = 1.;
    for(int i = 0; i < 8; i++) {
        float len = 0.01 + 0.02 * float(i * i);
        float dist = mapScene(p + n * len).x;
        occ += (len - dist) * weight;
        weight *= 0.85;
    }
    return 1.0 - clamp(0.6 * occ, 0., 1.);
}

vec3 shading(vec3 v, vec3 n, vec3 dir, float material) {
    float shininess = 0.1;
    //float occ = getAmbientOcc(v, n);
    float occ = 0.8;
    vec3 outMaterial = vec3(0.0, 0.0, 0.0);

    if(material == 0.) {
        outMaterial = vec3(0.8314, 0.2941, 0.2941);
        shininess = 0.5;
    } else if(material == 1.) {
        outMaterial = vec3(0.6275, 0.1569, 0.9412);
        shininess = 2.;
    } else if(material == 2.) {
        outMaterial = vec3(0.3255, 0.4784, 0.3255);
        shininess = .2;
    } else if(material == 3.) {
        outMaterial = vec3(0.2471, 0.3059, 0.6314);
        shininess = 1.0;
    } else if(material == 4.) {
        outMaterial = vec3(0.9961, 1.0, 0.9922);
        shininess = .3;
    }
    else if(material == 5.) {
        outMaterial = vec3(0.9961, 1.0, 0.9922);
        shininess = .3;
    }

    vec3 lights = vec3(0.);
    // lights += addPointLight(vec3(-2., 10., 0.), vec3(0.73, 0.73, 0.64), shininess, v, dir, n, occ);
    lights += addPointLight(vec3(-2., 10., -5.), vec3(0.77, 0.26, 0.73) * 1., shininess, v, dir, n, occ);
    lights += addPointLight(vec3( 20., 10.0, -5.0 ),vec3(0.08, 0.62, 0.75)*1., shininess, v, dir, n, occ);

    vec3 lightDir = vec3(0., 1., 6.);
    //float sun_dif = clamp(dot(n, lightDir), 0., 1.);
    //float shadow = softshadow(v + n * 0.01, lightDir, .01, 30., 18.);
    //lights += vec3(0.6431, 0.7804, 0.8588) * sun_dif * shadow * occ;

    float ind = clamp(dot(n, normalize(lightDir * vec3(.0, -1.0, -1.0))), 0.0, 1.0);
    lights += vec3(0.1255, 0.1255, 0.1255) * ind;

    return outMaterial * max(vec3(0.), lights);
}

vec3 postProcess(vec3 col) {
    // float random = noise(gl_FragCoord.xy, 0.01+u_time);
    // float random2 = noise(gl_FragCoord.xy, .2+u_time);
    //col += 0.075*clamp(vec3(0.5*random, 0.5*random2, 0.5*random), 0.02, 1.); // dither

    // Normalized pixel coordinates (from 0 to 1)
    vec2 screenCoord = getUV(vec2(0., 0.)); //gl_FragCoord.xy / u_resolution.xy;

    // Vignette
    float radius = 0.8;
    float d = smoothstep(radius, radius - 0.4, length(screenCoord - vec2(0.5)));
    col = mix(col, col * d, 1.);

    // Contrast
    float contrast = .75;
    col = mix(col, smoothstep(0.0, 1.0, col), contrast);

    // Colour mapping
    col *= vec3(1.0, 1.0, 1.0);

    col = pow(col, vec3(0.4545)); // gamma

    // fade in at the beginning
    //col*=vec3(clamp((u_time-1.8)*0.5,0., 1.));

    // fade out at the end
    // col*=vec3(clamp((120.-u_time)*.35, 0., 1.));

    return col;
}

vec3 getCameraRayDir(vec2 uv, vec3 camPos, vec3 camTarget) {
    // Calculate camera's "orthonormal basis", i.e. its transform matrix components
    vec3 camForward = normalize(camTarget - camPos);
    vec3 camRight = normalize(cross(vec3(.0, 1.0, 0.0), camForward));
    vec3 camUp = normalize(cross(camForward, camRight));
    float fov = 0.7;
    vec3 vDir = normalize(uv.x * camRight + uv.y * camUp + camForward * fov);
    return vDir;
}

vec3 getCameraRayDir2(vec2 uv, vec3 camPos, vec3 lookAt, float zoom) {
    vec3 f = normalize(lookAt - camPos);
    vec3 r = cross(vec3(0.0, 1.0, 0.0), f);
    vec3 u = cross(f, r);
    vec3 c = camPos + f * zoom;
    vec3 i = c + uv.x * r + uv.y * u;
    return normalize(i - camPos);
}

vec3 getCameraFov(vec2 uv, vec3 camPos, vec3 camTarget) {
    vec3 camForward = normalize(camTarget - camPos);
    vec3 camRight = normalize(cross(vec3(0.0, 1.0, 0.0), camForward));
    vec3 camUp = normalize(cross(camForward, camRight));
    float fov = 1.7;
	// Depth of field
    float dof = .3;
    vec2 h = vec2(noise(gl_FragCoord.xy, u_time * 0.1));
    vec3 voff = sqrt(h.x) * (camRight * sin(h.y * 6.283) + camUp * cos(h.y * 6.283)) * dof;
    voff -= camTarget;
    float focusdistance = 50.;
    return normalize(uv.x * camRight + uv.y * camUp + fov * camForward + voff * fov / focusdistance);
}

vec3 render(vec2 uv) {

    bool useDof = !true;
    // camera

    vec3 camTarget = vec3(15., 20., -20.); // Center point to orbit around
    float orbitRadius = 20.0; // Distance from target
    float orbitSpeed = 0.2; // Speed of orbit
    float orbitHeight = 5.0; // Height above target

    // Calculate orbiting position
    float angle = 0. * orbitSpeed;
    vec3 camPos = camTarget + vec3(
        cos(angle) * orbitRadius,
        orbitHeight + sin(0. * 0.8) * 2.0, // Optional vertical movement
        sin(angle) * orbitRadius
    );

    vec3 rayDir;

    // make orbit cam

    if(useDof) {
        rayDir = getCameraFov(uv, camPos, camTarget);
    } else {
        rayDir = getCameraRayDir2(uv, camPos, camTarget, 1.0);
    }

    vec3 col = vec3(0.102, 0.2431, 0.3412);

    vec3 hitPos = vec3(0.);
    vec3 t = castRay(camPos, rayDir, hitPos);

    if (t.z == 1.) {
        vec3 nor = calcNormal(hitPos);
        col = shading(hitPos, nor, rayDir, t.y);
    }

    return col;
}

void main() {

    vec3 finalColor = render(getUV(vec2(0., 0.)));

    //finalColor = postProcess(finalColor);

    o = vec4(finalColor, 1.);

}