uniform float u_weight;
uniform float u_fromIndex;
uniform float u_toIndex;
uniform vec2 u_lightMapUVSize;

varying vec2 v_texCoord;
varying vec2 v_gridTexCoord;


#define LUT_SIZE 16.0
#define LUT_SIZE_MINUS_1 15.0
//normalized lut slice size
#define SLICE 0.0625 //1.0 / LUT_SIZE
//normalized pixel size
#define SLICE_PIXEL 0.00390625 //SLICE / LUT_SIZE
#define SLICE_INNER 0.05859375 //SLICE_PIXEL * LUT_SIZE_MINUS_1

//#define OFFSET_Y 0.01041666 //0.5 / textureHeight
#define OFFSET_Y 0.0078125 //0.5 / textureHeight

#define LUT_V_SIZE 0.25

void main()
{
    vec4 rawColor = texture2D(CC_Texture1, v_texCoord);
    vec4 attColor = texture2D(CC_Texture3, v_texCoord);
    vec4 bulbZone = texture2D(CC_Texture0, v_gridTexCoord * u_lightMapUVSize );
    
    float zBottom = min(floor(rawColor.z * LUT_SIZE), LUT_SIZE_MINUS_1);
    float zTop = min(zBottom + 1.0, LUT_SIZE_MINUS_1);
    float xOffset = SLICE_PIXEL * 0.5 + rawColor.x * SLICE_INNER;
    
    float uBottom = xOffset + zBottom * SLICE;
    float uTop = xOffset + zTop * SLICE;
    float vPos = max(rawColor.y * LUT_V_SIZE - OFFSET_Y, OFFSET_Y );
    float zOffset = mod(rawColor.z * LUT_SIZE, 1.0);
    
    float vOffsetPos = vPos + LUT_V_SIZE * u_fromIndex;
    vec4 bottomColor = texture2D(CC_Texture2, vec2(uBottom, vOffsetPos));
    vec4 topColor = texture2D(CC_Texture2, vec2(uTop, vOffsetPos));
    vec4 fromColor = mix(bottomColor, topColor, zOffset);
    
    vOffsetPos = vPos + LUT_V_SIZE * u_toIndex;
    bottomColor = texture2D(CC_Texture2, vec2(uBottom, vOffsetPos));
    topColor = texture2D(CC_Texture2, vec2(uTop, vOffsetPos));
    vec4 toColor = mix(bottomColor, topColor, zOffset);
    
    //No color correction
    //float original = step(0.01, bulbZone.a);
    vec4 colorOutput = mix(fromColor, toColor, u_weight);

    if (attColor.a  > 0.9) //no glow but color correction
    {
        colorOutput = rawColor;
    }
    
    if (attColor.a <= 0.9) // else does some funky magic on newer devices with iOS 10
    {
        colorOutput = mix( mix(colorOutput, rawColor, attColor.a / 0.9), 1.5 * rawColor, 1.2 * bulbZone.r);
    }
    
    gl_FragColor = colorOutput;
}
