/* Bits++_Mono++_FormattingShader.frag.txt -- Mono++ output formatter
 *
 * This shader converts a HDR texture into a RGBA8 8bpc framebuffer
 * image, suitable for display with the CRS Bits++ system in Mono++
 * mode. It expects the luminance image data in the red channel of
 * the texture, with values ranging from 0.0 - 1.0, remaps it into
 * the 16 bit data range of Bits++, then encodes the 16 bit luminance
 * value into the red+green channels (8 MSB in red, 8 LSB in green). The
 * blue channel is set to 0.0, i.e., black. The alpha channel is set to
 * a fixed maximum value of 1.0, because alpha blending on such an image
 * would be an undefined operation.
 *
 * This shader is intended for use as a plugin for the 'FinalOutputFormattingBlit'
 * chain of the Psychtoolbox-3 imaging pipeline.
 *
 * (c)2007, 2008 by Mario Kleiner, part of PTB-3, licensed to you under MIT license.
 * See file License.txt in the Psychtoolbox root folder for the license.
 *
 */

#extension GL_ARB_texture_rectangle : enable

uniform sampler2DRect Image;

/* Declare external function for luminance color conversion: */
float icmTransformColor1(float incolor);

/* Dynamically generated overlay color index lookup function: */
float getMonoOverlayIndex(vec2 pos);

void main()
{
    /* Retrieve RGBA HDR input color value. */
    float incolor = texture2DRect(Image, gl_TexCoord[0].st).r;

    /* Apply some color transformation (clamping, gamma correction etc.): */
    incolor = icmTransformColor1(incolor);

    /* Remap red channel from 0.0 - 1.0 to 0 to 65535: */
    float index = incolor * 65535.0 + 0.01;

    /* Compute high byte (8 MSBs) and store in red output color. */
    gl_FragColor.r = floor(index / 256.0) / 255.0;

    /* Compute low byte (8 LSBs) and store in green output color. */
    gl_FragColor.g = mod(index, 256.0) / 255.0;

    /* Get blue channel value from overlay subfunction. */
    gl_FragColor.b = getMonoOverlayIndex(gl_TexCoord[0].st);

    /* Fix alpha channel to 1.0. */
    gl_FragColor.a = 1.0;
}
