#version 330 core

layout (location = 0) out vec4 color;
layout (location = 1) out vec4 BrightColor;

in vec3 position_out;


// Improved hash function for noise generation
float hash(vec3 p) {
    p = fract(p * 0.3183099 + 0.1);
    p *= 17.0;
    return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
}

// Improved noise function
float noise(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    f = f*f*(3.0-2.0*f);
    return mix(mix(mix(hash(i + vec3(0,0,0)), 
                       hash(i + vec3(1,0,0)), f.x),
                   mix(hash(i + vec3(0,1,0)), 
                       hash(i + vec3(1,1,0)), f.x), f.y),
               mix(mix(hash(i + vec3(0,0,1)), 
                       hash(i + vec3(1,0,1)), f.x),
                   mix(hash(i + vec3(0,1,1)), 
                       hash(i + vec3(1,1,1)), f.x), f.y), f.z);
}

// Fractal Brownian Motion for more complex noise patterns
float fbm(vec3 p) {
    float value = 0.0;
    float amplitude = 0.5;
    float frequency = 1.0;
    for (int i = 0; i < 5; i++) {
        value += amplitude * noise(p * frequency);
        p *= 2.0;
        amplitude *= 0.5;
    }
    return value;
}

// Wood grain function with added complexity
float woodGrain(vec3 p) {
    float baseGrain = sin(p.x * 10 + fbm(p * 1.4) * 10.0) * 0.5 + 0.5;
    float knots = fbm(p * 1.4 * 2.0) * 0.5 + 0.5;
    return mix(baseGrain, knots, knots * 0.5);
}

void main() {
    // Convert fragment position to cylindrical coordinates
    float theta = atan(position_out.z, position_out.x);
    float y = position_out.y;

    // Create 3D position for noise
    vec3 pos = vec3(theta * 1, y * 1, 0.0);
    
    // Get wood grain pattern
    float grain = woodGrain(pos);
    
    vec3 woodColor = mix(vec3(0.07, 0.03, 0.01), vec3(0.7, 0.5, 0.3), grain);
    
    // Final color
    color = vec4(woodColor, 1.0);

    // bloom
    float brightness = dot(color.rgb, vec3(0.2126f, 0.7152f, 0.0722f));
    if(brightness > 0.5){
        BrightColor = vec4(color.rgb  * brightness * brightness, 1.0f);
    } else{
        BrightColor = vec4(0.0f, 0.0f, 0.0f, 1.0f);
    }
}